blob: 6ebd1d1410e5c82cdafb372f6ba92ade3cf4d30f [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenFunction.h"
22#include "CodeGenTBAA.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000023#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000024#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000025#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000028#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000029#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000030#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000031#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000032#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000033#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000034#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000035#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000036#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000037#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Frontend/CodeGenOptions.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000039#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000040#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000041#include "llvm/IR/CallingConv.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/LLVMContext.h"
45#include "llvm/IR/Module.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000046#include "llvm/Support/CallSite.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000047#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000048#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include "llvm/Target/Mangler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000050
Chris Lattnerbed31442007-05-28 01:07:47 +000051using namespace clang;
52using namespace CodeGen;
53
Julien Lerouge5a6b6982011-09-09 22:41:49 +000054static const char AnnotationSection[] = "llvm.metadata";
55
John McCall614dbdc2010-08-22 21:01:12 +000056static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000057 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000058 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000059 case TargetCXXABI::GenericARM:
60 case TargetCXXABI::iOS:
61 case TargetCXXABI::GenericItanium:
62 return *CreateItaniumCXXABI(CGM);
63 case TargetCXXABI::Microsoft:
64 return *CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000065 }
66
67 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000068}
69
Chris Lattnerbed31442007-05-28 01:07:47 +000070
Chandler Carruthbc55fe22009-11-12 17:24:48 +000071CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall568d4102013-04-16 22:48:20 +000072 llvm::Module &M, const llvm::DataLayout &TD,
David Blaikie9c902b52011-09-25 23:23:43 +000073 DiagnosticsEngine &diags)
John McCallc8e01702013-04-16 22:48:15 +000074 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
75 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
76 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
77 TheTargetCodeGenInfo(0), Types(*this), VTables(*this),
78 ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
Dan Gohman515a60d2012-02-16 00:57:37 +000079 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
80 RRData(0), CFConstantStringClassRef(0),
Peter Collingbournefe883422011-10-06 18:29:37 +000081 ConstantStringClassRef(0), NSConstantStringType(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000082 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
John McCallad7c5c12011-02-08 08:22:06 +000083 BlockObjectAssign(0), BlockObjectDispose(0),
Will Dietzf54319c2013-01-18 11:30:38 +000084 BlockDescriptorType(0), GenericBlockLiteralType(0),
Nadav Rotem1da30942013-03-23 06:43:35 +000085 LifetimeStartFn(0), LifetimeEndFn(0),
Will Dietzf54319c2013-01-18 11:30:38 +000086 SanitizerBlacklist(CGO.SanitizerBlacklistFile),
87 SanOpts(SanitizerBlacklist.isIn(M) ?
88 SanitizerOptions::Disabled : LangOpts.Sanitize) {
89
Chris Lattnerece04092012-02-07 00:39:47 +000090 // Initialize the type cache.
91 llvm::LLVMContext &LLVMContext = M.getContext();
92 VoidTy = llvm::Type::getVoidTy(LLVMContext);
93 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
95 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97 FloatTy = llvm::Type::getFloatTy(LLVMContext);
98 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
99 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
100 PointerAlignInBytes =
101 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
102 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
103 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104 Int8PtrTy = Int8Ty->getPointerTo(0);
105 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
106
John McCall882987f2013-02-28 19:01:20 +0000107 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
108
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000110 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000111 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000112 createOpenCLRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000113 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000114 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000115
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000116 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietzf54319c2013-01-18 11:30:38 +0000117 if (SanOpts.Thread ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000118 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
119 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Dan Gohman2e29eb52010-10-15 20:23:12 +0000120 ABI.getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000121
Nick Lewycky207bce32011-04-21 23:44:07 +0000122 // If debug info or coverage generation is enabled, create the CGDebugInfo
123 // object.
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000124 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000125 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000126 CodeGenOpts.EmitGcovNotes)
127 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000128
129 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000130
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000132 ARCData = new ARCEntrypoints();
133 RRData = new RREntrypoints();
Chris Lattnera087ff92008-03-01 08:45:05 +0000134}
135
136CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000137 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000138 delete OpenCLRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000139 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000140 delete TheTargetCodeGenInfo;
John McCall614dbdc2010-08-22 21:01:12 +0000141 delete &ABI;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000142 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000143 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000144 delete ARCData;
145 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000146}
147
David Chisnall481e3a82010-01-23 02:40:42 +0000148void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000149 // This is just isGNUFamily(), but we want to force implementors of
150 // new ABIs to decide how best to do this.
151 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000152 case ObjCRuntime::GNUstep:
153 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000154 case ObjCRuntime::ObjFW:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000155 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000156 return;
157
158 case ObjCRuntime::FragileMacOSX:
159 case ObjCRuntime::MacOSX:
160 case ObjCRuntime::iOS:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000161 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000162 return;
163 }
164 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000165}
166
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000167void CodeGenModule::createOpenCLRuntime() {
168 OpenCLRuntime = new CGOpenCLRuntime(*this);
169}
170
Peter Collingbournefe883422011-10-06 18:29:37 +0000171void CodeGenModule::createCUDARuntime() {
172 CUDARuntime = CreateNVCUDARuntime(*this);
173}
174
Ted Kremenek2c674f62008-08-05 18:50:11 +0000175void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000176 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000177 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000178 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000179 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000180 if (ObjCRuntime)
181 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000182 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000183 EmitCtorList(GlobalCtors, "llvm.global_ctors");
184 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000185 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000186 EmitStaticExternCAliases();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000187 EmitLLVMUsed();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000188
Daniel Dunbare246fbe2013-04-16 18:21:19 +0000189 if (CodeGenOpts.Autolink && Context.getLangOpts().Modules) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000190 EmitModuleLinkOptions();
191 }
Douglas Gregorea02f262013-01-14 18:28:43 +0000192
John McCall0bdb1fd2010-09-16 06:16:50 +0000193 SimplifyPersonality();
194
John McCall09ae0322010-07-06 23:57:41 +0000195 if (getCodeGenOpts().EmitDeclMetadata)
196 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000197
198 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000199 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000200
201 if (DebugInfo)
202 DebugInfo->finalize();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000203}
204
Devang Patel945b8ae2011-03-23 16:29:39 +0000205void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
206 // Make sure that this type is translated.
207 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000208}
209
Dan Gohman947c9af2010-10-14 23:06:10 +0000210llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
211 if (!TBAA)
212 return 0;
213 return TBAA->getTBAAInfo(QTy);
214}
215
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000216llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
217 if (!TBAA)
218 return 0;
219 return TBAA->getTBAAInfoForVTablePtr();
220}
221
Dan Gohman22695fc2012-09-28 21:58:29 +0000222llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
223 if (!TBAA)
224 return 0;
225 return TBAA->getTBAAStructInfo(QTy);
226}
227
Manman Renc451e572013-04-04 21:53:22 +0000228llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
229 if (!TBAA)
230 return 0;
231 return TBAA->getTBAAStructTypeInfo(QTy);
232}
233
234llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
235 llvm::MDNode *AccessN,
236 uint64_t O) {
237 if (!TBAA)
238 return 0;
239 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
240}
241
Manman Rene1ad74e2013-04-11 23:02:56 +0000242/// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
243/// is the same as the type. For struct-path aware TBAA, the tag
244/// is different from the type: base type, access type and offset.
245/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman947c9af2010-10-14 23:06:10 +0000246void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Rene1ad74e2013-04-11 23:02:56 +0000247 llvm::MDNode *TBAAInfo,
248 bool ConvertTypeToTag) {
249 if (ConvertTypeToTag && TBAA && CodeGenOpts.StructPathTBAA)
250 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
251 TBAA->getTBAAScalarTagInfo(TBAAInfo));
252 else
253 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000254}
255
Chandler Carruth84537952012-03-30 19:44:53 +0000256void CodeGenModule::Error(SourceLocation loc, StringRef error) {
257 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall7ef5cb32011-03-18 02:56:14 +0000258 getDiags().Report(Context.getFullLoc(loc), diagID);
259}
260
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000261/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000262/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000263void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
264 bool OmitOnError) {
265 if (OmitOnError && getDiags().hasErrorOccurred())
266 return;
David Blaikie9c902b52011-09-25 23:23:43 +0000267 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000268 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000269 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000270 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
271 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000272}
Chris Lattner41af8182007-12-02 06:27:33 +0000273
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000274/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000275/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000276void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
277 bool OmitOnError) {
278 if (OmitOnError && getDiags().hasErrorOccurred())
279 return;
David Blaikie9c902b52011-09-25 23:23:43 +0000280 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000281 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000282 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000283 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000284}
285
John McCall23c29fe2011-06-24 21:55:10 +0000286llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
287 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
288}
289
Mike Stump11289f42009-09-09 15:08:12 +0000290void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000291 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000292 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000293 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000294 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000295 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000296 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000297
John McCallc273f242010-10-30 11:50:40 +0000298 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000299 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000300 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
301 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000302}
303
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000304static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
305 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
306 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
307 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
308 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
309 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
310}
311
312static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
313 CodeGenOptions::TLSModel M) {
314 switch (M) {
315 case CodeGenOptions::GeneralDynamicTLSModel:
316 return llvm::GlobalVariable::GeneralDynamicTLSModel;
317 case CodeGenOptions::LocalDynamicTLSModel:
318 return llvm::GlobalVariable::LocalDynamicTLSModel;
319 case CodeGenOptions::InitialExecTLSModel:
320 return llvm::GlobalVariable::InitialExecTLSModel;
321 case CodeGenOptions::LocalExecTLSModel:
322 return llvm::GlobalVariable::LocalExecTLSModel;
323 }
324 llvm_unreachable("Invalid TLS model!");
325}
326
327void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
328 const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000329 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000330
331 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000332 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000333
334 // Override the TLS model if it is explicitly specified.
335 if (D.hasAttr<TLSModelAttr>()) {
336 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
337 TLM = GetLLVMTLSModel(Attr->getModel());
338 }
339
340 GV->setThreadLocalMode(TLM);
341}
342
John McCalle16adc22010-08-04 08:34:44 +0000343/// Set the symbol visibility of type information (vtable and RTTI)
344/// associated with the given type.
345void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
346 const CXXRecordDecl *RD,
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000347 TypeVisibilityKind TVK) const {
Anders Carlssonc6a47892011-01-29 19:39:23 +0000348 setGlobalVisibility(GV, RD);
John McCalle16adc22010-08-04 08:34:44 +0000349
John McCallb3732bb2010-08-12 23:36:15 +0000350 if (!CodeGenOpts.HiddenWeakVTables)
351 return;
352
Anders Carlsson678632f2011-01-29 20:36:11 +0000353 // We never want to drop the visibility for RTTI names.
354 if (TVK == TVK_ForRTTIName)
355 return;
356
John McCalle16adc22010-08-04 08:34:44 +0000357 // We want to drop the visibility to hidden for weak type symbols.
358 // This isn't possible if there might be unresolved references
359 // elsewhere that rely on this symbol being visible.
360
John McCall5513fce92010-08-05 20:39:18 +0000361 // This should be kept roughly in sync with setThunkVisibility
362 // in CGVTables.cpp.
363
John McCalle16adc22010-08-04 08:34:44 +0000364 // Preconditions.
Anders Carlsson571e2ad2011-01-24 00:46:19 +0000365 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCalle16adc22010-08-04 08:34:44 +0000366 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
367 return;
368
369 // Don't override an explicit visibility attribute.
John McCalld041a9b2013-02-20 01:54:26 +0000370 if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
John McCalle16adc22010-08-04 08:34:44 +0000371 return;
372
373 switch (RD->getTemplateSpecializationKind()) {
374 // We have to disable the optimization if this is an EI definition
375 // because there might be EI declarations in other shared objects.
376 case TSK_ExplicitInstantiationDefinition:
377 case TSK_ExplicitInstantiationDeclaration:
378 return;
379
John McCall5513fce92010-08-05 20:39:18 +0000380 // Every use of a non-template class's type information has to emit it.
John McCalle16adc22010-08-04 08:34:44 +0000381 case TSK_Undeclared:
382 break;
383
John McCall5513fce92010-08-05 20:39:18 +0000384 // In theory, implicit instantiations can ignore the possibility of
385 // an explicit instantiation declaration because there necessarily
386 // must be an EI definition somewhere with default visibility. In
387 // practice, it's possible to have an explicit instantiation for
388 // an arbitrary template class, and linkers aren't necessarily able
389 // to deal with mixed-visibility symbols.
390 case TSK_ExplicitSpecialization:
John McCalle16adc22010-08-04 08:34:44 +0000391 case TSK_ImplicitInstantiation:
Douglas Gregor47c08962012-10-24 14:11:55 +0000392 return;
John McCalle16adc22010-08-04 08:34:44 +0000393 }
394
395 // If there's a key function, there may be translation units
396 // that don't have the key function's definition. But ignore
397 // this if we're emitting RTTI under -fno-rtti.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000398 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
John McCall6bd2a892013-01-25 22:31:03 +0000399 // FIXME: what should we do if we "lose" the key function during
400 // the emission of the file?
401 if (Context.getCurrentKeyFunction(RD))
John McCalle16adc22010-08-04 08:34:44 +0000402 return;
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000403 }
John McCalle16adc22010-08-04 08:34:44 +0000404
405 // Otherwise, drop the visibility to hidden.
406 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1e879c2011-01-11 21:44:37 +0000407 GV->setUnnamedAddr(true);
John McCalle16adc22010-08-04 08:34:44 +0000408}
409
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000410StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000411 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
412
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000413 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000414 if (!Str.empty())
415 return Str;
416
John McCall5d865c322010-08-31 07:33:07 +0000417 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000418 IdentifierInfo *II = ND->getIdentifier();
419 assert(II && "Attempt to mangle unnamed decl.");
420
421 Str = II->getName();
422 return Str;
423 }
424
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000425 SmallString<256> Buffer;
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000426 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000427 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000428 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000429 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000430 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000431 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian63628032012-06-26 16:06:38 +0000432 getCXXABI().getMangleContext().mangleBlock(BD, Out,
433 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000434 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000435 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000436
437 // Allocate space for the mangled name.
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000438 Out.flush();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000439 size_t Length = Buffer.size();
440 char *Name = MangledNamesAllocator.Allocate<char>(Length);
441 std::copy(Buffer.begin(), Buffer.end(), Name);
442
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000443 Str = StringRef(Name, Length);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000444
445 return Str;
446}
447
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000448void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
449 const BlockDecl *BD) {
450 MangleContext &MangleCtx = getCXXABI().getMangleContext();
451 const Decl *D = GD.getDecl();
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000452 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000453 if (D == 0)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000454 MangleCtx.mangleGlobalBlock(BD,
455 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000456 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000457 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000458 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000459 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000460 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000461 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson635186a2010-06-09 02:36:32 +0000462}
463
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000465 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000466}
467
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000468/// AddGlobalCtor - Add a function to the list that will be called before
469/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000470void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000471 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000472 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000473}
474
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000475/// AddGlobalDtor - Add a function to the list that will be called
476/// when the module is unloaded.
477void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000478 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000479 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
480}
481
482void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
483 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000484 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000485 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000486
487 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000488 llvm::StructType *CtorStructTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000489 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000490
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000491 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000492 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000493 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000494 llvm::Constant *S[] = {
495 llvm::ConstantInt::get(Int32Ty, I->second, false),
496 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
497 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000498 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000499 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000500
501 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000502 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000503 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000504 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000505 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000506 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000507 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000508}
509
John McCalld4324142010-02-19 01:32:20 +0000510llvm::GlobalValue::LinkageTypes
511CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000512 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000513
Chris Lattner749b8ed2010-06-30 16:58:07 +0000514 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000515 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000516
517 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000518 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000519
520 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000521 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000522
523 // In C99 mode, 'inline' functions are guaranteed to have a strong
524 // definition somewhere else, so we can use available_externally linkage.
525 if (Linkage == GVA_C99Inline)
Fariborz Jahanian7cadb2f2011-02-04 00:08:13 +0000526 return llvm::Function::AvailableExternallyLinkage;
John McCall28a5b322011-09-19 18:05:26 +0000527
528 // Note that Apple's kernel linker doesn't support symbol
529 // coalescing, so we need to avoid linkonce and weak linkages there.
530 // Normally, this means we just map to internal, but for explicit
531 // instantiations we'll map to external.
532
Chris Lattner749b8ed2010-06-30 16:58:07 +0000533 // In C++, the compiler has to emit a definition in every translation unit
534 // that references the function. We should use linkonce_odr because
535 // a) if all references in this translation unit are optimized away, we
536 // don't need to codegen it. b) if the function persists, it needs to be
537 // merged with other definitions. c) C++ has the ODR, so we know the
538 // definition is dependable.
539 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000540 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000541 ? llvm::Function::LinkOnceODRLinkage
542 : llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000543
544 // An explicit instantiation of a template has weak linkage, since
545 // explicit instantiations can occur in multiple translation units
546 // and must all be equivalent. However, we are not allowed to
547 // throw away these explicit instantiations.
548 if (Linkage == GVA_ExplicitTemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000549 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000550 ? llvm::Function::WeakODRLinkage
John McCall28a5b322011-09-19 18:05:26 +0000551 : llvm::Function::ExternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000552
553 // Otherwise, we have strong external linkage.
554 assert(Linkage == GVA_StrongExternal);
555 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000556}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000557
John McCalld4324142010-02-19 01:32:20 +0000558
559/// SetFunctionDefinitionAttributes - Set attributes for a global.
560///
561/// FIXME: This is currently only done for aliases and functions, but not for
562/// variables (these details are set in EmitGlobalVarDefinition for variables).
563void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
564 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000565 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000566}
567
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000568void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000569 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000570 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000571 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000572 AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000573 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling3087d022012-12-07 23:17:26 +0000574 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000575 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000576}
577
John McCall9b0a7ce2011-10-02 01:16:38 +0000578/// Determines whether the language options require us to model
579/// unwind exceptions. We treat -fexceptions as mandating this
580/// except under the fragile ObjC ABI with only ObjC exceptions
581/// enabled. This means, for example, that C with -fexceptions
582/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000583static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000584 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000585 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000586
587 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000588 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000589
590 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000591 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000592 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000593 }
594
595 return true;
596}
597
Daniel Dunbar38932572009-04-14 08:05:55 +0000598void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
599 llvm::Function *F) {
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000600 if (CodeGenOpts.UnwindTables)
601 F->setHasUWTable();
602
David Blaikiebbafb8a2012-03-11 07:00:24 +0000603 if (!hasUnwindExceptions(LangOpts))
Bill Wendling207f0532012-12-20 19:27:06 +0000604 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000605
Eli Friedmanc55efe42011-08-22 23:55:33 +0000606 if (D->hasAttr<NakedAttr>()) {
607 // Naked implies noinline: we should not be inlining such functions.
Bill Wendling207f0532012-12-20 19:27:06 +0000608 F->addFnAttr(llvm::Attribute::Naked);
609 F->addFnAttr(llvm::Attribute::NoInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000610 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000611
Mike Stump3722f582009-08-26 22:31:08 +0000612 if (D->hasAttr<NoInlineAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +0000613 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000614
Eli Friedmanc55efe42011-08-22 23:55:33 +0000615 // (noinline wins over always_inline, and we can't specify both in IR)
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +0000616 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
Bill Wendling5e85be42012-12-30 10:32:17 +0000617 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
618 llvm::Attribute::NoInline))
Bill Wendling207f0532012-12-20 19:27:06 +0000619 F->addFnAttr(llvm::Attribute::AlwaysInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000620
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000621 // FIXME: Communicate hot and cold attributes to LLVM more directly.
622 if (D->hasAttr<ColdAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +0000623 F->addFnAttr(llvm::Attribute::OptimizeForSize);
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000624
Quentin Colombet4e172062012-11-01 23:55:47 +0000625 if (D->hasAttr<MinSizeAttr>())
Bill Wendling207f0532012-12-20 19:27:06 +0000626 F->addFnAttr(llvm::Attribute::MinSize);
Quentin Colombet4e172062012-11-01 23:55:47 +0000627
Rafael Espindola0ee986c1f2011-01-11 00:26:26 +0000628 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
629 F->setUnnamedAddr(true);
630
Richard Smithb555a762012-09-28 22:46:07 +0000631 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
632 if (MD->isVirtual())
633 F->setUnnamedAddr(true);
634
David Blaikiebbafb8a2012-03-11 07:00:24 +0000635 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Bill Wendling207f0532012-12-20 19:27:06 +0000636 F->addFnAttr(llvm::Attribute::StackProtect);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Bill Wendling207f0532012-12-20 19:27:06 +0000638 F->addFnAttr(llvm::Attribute::StackProtectReq);
Will Dietzf54319c2013-01-18 11:30:38 +0000639
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000640 // Add sanitizer attributes if function is not blacklisted.
641 if (!SanitizerBlacklist.isIn(*F)) {
642 // When AddressSanitizer is enabled, set SanitizeAddress attribute
643 // unless __attribute__((no_sanitize_address)) is used.
644 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
645 F->addFnAttr(llvm::Attribute::SanitizeAddress);
646 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
647 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
648 F->addFnAttr(llvm::Attribute::SanitizeThread);
649 }
650 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
651 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
652 F->addFnAttr(llvm::Attribute::SanitizeMemory);
653 }
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000654
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000655 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
656 if (alignment)
657 F->setAlignment(alignment);
658
Mike Stump3472ae52009-10-05 22:49:20 +0000659 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000660 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
661 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000662}
663
Mike Stump11289f42009-09-09 15:08:12 +0000664void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000665 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000666 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
667 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000668 else
669 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000670
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000671 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000672 AddUsedGlobal(GV);
673
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000674 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000675 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000676
Rafael Espindola513499d2013-03-19 15:03:47 +0000677 // Alias cannot have attributes. Filter them here.
678 if (!isa<llvm::GlobalAlias>(GV))
679 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000680}
681
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000682void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
683 llvm::Function *F,
684 const CGFunctionInfo &FI) {
685 SetLLVMFunctionAttributes(D, FI, F);
686 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000687
688 F->setLinkage(llvm::Function::InternalLinkage);
689
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000690 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000691}
692
Anders Carlsson6710c532010-02-06 02:44:09 +0000693void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000694 llvm::Function *F,
695 bool IsIncompleteFunction) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000696 if (unsigned IID = F->getIntrinsicID()) {
697 // If this is an intrinsic function, set the function's attributes
698 // to the intrinsic's attributes.
Bill Wendling311c8322012-10-15 04:47:45 +0000699 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
700 (llvm::Intrinsic::ID)IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000701 return;
702 }
703
Anders Carlsson6710c532010-02-06 02:44:09 +0000704 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
705
Eli Friedman895771a2009-05-26 01:22:57 +0000706 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000707 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000708
Daniel Dunbar38932572009-04-14 08:05:55 +0000709 // Only a few attributes are set on declarations; these may later be
710 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000711
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000712 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000713 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000714 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000715 FD->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000716 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000717 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000718 F->setLinkage(llvm::Function::ExternalWeakLinkage);
719 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000720 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallc273f242010-10-30 11:50:40 +0000721
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000722 LinkageInfo LV = FD->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000723 if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
724 F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
John McCallc273f242010-10-30 11:50:40 +0000725 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000726 }
727
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000728 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000729 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000730}
731
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000732void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000733 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000734 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000735 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000736}
737
738void CodeGenModule::EmitLLVMUsed() {
739 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000740 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000741 return;
742
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000743 // Convert LLVMUsed to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000744 SmallVector<llvm::Constant*, 8> UsedArray;
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000745 UsedArray.resize(LLVMUsed.size());
746 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000747 UsedArray[i] =
748 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Chris Lattner3def9ae2012-02-06 22:16:34 +0000749 Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000750 }
Mike Stump11289f42009-09-09 15:08:12 +0000751
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000752 if (UsedArray.empty())
753 return;
Chris Lattner3def9ae2012-02-06 22:16:34 +0000754 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000755
756 llvm::GlobalVariable *GV =
757 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000758 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000759 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000760 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000761
762 GV->setSection("llvm.metadata");
763}
764
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000765/// \brief Add link options implied by the given module, including modules
766/// it depends on, using a postorder walk.
767static void addLinkOptionsPostorder(llvm::LLVMContext &Context,
768 Module *Mod,
Daniel Dunbar69e47462013-01-17 01:35:06 +0000769 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000770 llvm::SmallPtrSet<Module *, 16> &Visited) {
771 // Import this module's parent.
772 if (Mod->Parent && Visited.insert(Mod->Parent)) {
773 addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
774 }
775
776 // Import this module's dependencies.
777 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
778 if (Visited.insert(Mod->Imports[I-1]))
779 addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
780 }
781
782 // Add linker options to link against the libraries/frameworks
783 // described by this module.
784 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
785 // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
786 // We need to know more about the linker to know how to encode these
787 // options propertly.
788
789 // Link against a framework.
790 if (Mod->LinkLibraries[I-1].IsFramework) {
791 llvm::Value *Args[2] = {
792 llvm::MDString::get(Context, "-framework"),
793 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
794 };
795
796 Metadata.push_back(llvm::MDNode::get(Context, Args));
797 continue;
798 }
799
800 // Link against a library.
801 llvm::Value *OptString
802 = llvm::MDString::get(Context,
803 "-l" + Mod->LinkLibraries[I-1].Library);
804 Metadata.push_back(llvm::MDNode::get(Context, OptString));
805 }
806}
807
808void CodeGenModule::EmitModuleLinkOptions() {
809 // Collect the set of all of the modules we want to visit to emit link
810 // options, which is essentially the imported modules and all of their
811 // non-explicit child modules.
812 llvm::SetVector<clang::Module *> LinkModules;
813 llvm::SmallPtrSet<clang::Module *, 16> Visited;
814 SmallVector<clang::Module *, 16> Stack;
815
816 // Seed the stack with imported modules.
817 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
818 MEnd = ImportedModules.end();
819 M != MEnd; ++M) {
820 if (Visited.insert(*M))
821 Stack.push_back(*M);
822 }
823
824 // Find all of the modules to import, making a little effort to prune
825 // non-leaf modules.
826 while (!Stack.empty()) {
827 clang::Module *Mod = Stack.back();
828 Stack.pop_back();
829
830 bool AnyChildren = false;
831
832 // Visit the submodules of this module.
833 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
834 SubEnd = Mod->submodule_end();
835 Sub != SubEnd; ++Sub) {
836 // Skip explicit children; they need to be explicitly imported to be
837 // linked against.
838 if ((*Sub)->IsExplicit)
839 continue;
840
841 if (Visited.insert(*Sub)) {
842 Stack.push_back(*Sub);
843 AnyChildren = true;
844 }
845 }
846
847 // We didn't find any children, so add this module to the list of
848 // modules to link against.
849 if (!AnyChildren) {
850 LinkModules.insert(Mod);
851 }
852 }
853
854 // Add link options for all of the imported modules in reverse topological
855 // order.
Daniel Dunbar69e47462013-01-17 01:35:06 +0000856 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000857 Visited.clear();
858 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
859 MEnd = LinkModules.end();
860 M != MEnd; ++M) {
861 if (Visited.insert(*M))
862 addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
863 }
Daniel Dunbar69e47462013-01-17 01:35:06 +0000864 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000865
Daniel Dunbar69e47462013-01-17 01:35:06 +0000866 // Add the linker options metadata flag.
867 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
868 llvm::MDNode::get(getLLVMContext(), MetadataArgs));
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000869}
870
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000871void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000872 // Emit code for any potentially referenced deferred decls. Since a
873 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000874 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000875
John McCall6bd2a892013-01-25 22:31:03 +0000876 while (true) {
Anders Carlsson11e51402010-04-17 20:15:18 +0000877 if (!DeferredVTables.empty()) {
John McCall6bd2a892013-01-25 22:31:03 +0000878 EmitDeferredVTables();
879
880 // Emitting a v-table doesn't directly cause more v-tables to
881 // become deferred, although it can cause functions to be
882 // emitted that then need those v-tables.
883 assert(DeferredVTables.empty());
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000884 }
885
John McCall6bd2a892013-01-25 22:31:03 +0000886 // Stop if we're out of both deferred v-tables and deferred declarations.
887 if (DeferredDeclsToEmit.empty()) break;
888
Anders Carlssondae1abc2009-05-05 04:44:02 +0000889 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000890 DeferredDeclsToEmit.pop_back();
891
John McCallc2af9392010-05-27 01:45:30 +0000892 // Check to see if we've already emitted this. This is necessary
893 // for a couple of reasons: first, decls can end up in the
894 // deferred-decls queue multiple times, and second, decls can end
895 // up with definitions in unusual ways (e.g. by an extern inline
896 // function acquiring a strong function redefinition). Just
897 // ignore these cases.
898 //
899 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000900 StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000901 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000902 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000903
Chris Lattner45470942009-03-21 09:44:56 +0000904 if (!CGRef->isDeclaration())
905 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000906
John McCallc2af9392010-05-27 01:45:30 +0000907 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
908 // purposes an alias counts as a definition.
909 if (isa<llvm::GlobalAlias>(CGRef))
910 continue;
911
Chris Lattner45470942009-03-21 09:44:56 +0000912 // Otherwise, emit the definition and move on to the next one.
913 EmitGlobalDefinition(D);
914 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000915}
Chris Lattner09153c02007-06-22 18:48:09 +0000916
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000917void CodeGenModule::EmitGlobalAnnotations() {
918 if (Annotations.empty())
919 return;
920
921 // Create a new global variable for the ConstantStruct in the Module.
922 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
923 Annotations[0]->getType(), Annotations.size()), Annotations);
924 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
925 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
926 "llvm.global.annotations");
927 gv->setSection(AnnotationSection);
928}
929
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000930llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000931 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
932 if (i != AnnotationStrings.end())
933 return i->second;
934
935 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +0000936 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000937 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
938 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
939 gv->setSection(AnnotationSection);
940 gv->setUnnamedAddr(true);
941 AnnotationStrings[Str] = gv;
942 return gv;
943}
944
945llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
946 SourceManager &SM = getContext().getSourceManager();
947 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
948 if (PLoc.isValid())
949 return EmitAnnotationString(PLoc.getFilename());
950 return EmitAnnotationString(SM.getBufferName(Loc));
951}
952
953llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
954 SourceManager &SM = getContext().getSourceManager();
955 PresumedLoc PLoc = SM.getPresumedLoc(L);
956 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
957 SM.getExpansionLineNumber(L);
958 return llvm::ConstantInt::get(Int32Ty, LineNo);
959}
960
Mike Stump11289f42009-09-09 15:08:12 +0000961llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000962 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000963 SourceLocation L) {
964 // Get the globals for file name, annotation, and the line number.
965 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
966 *UnitGV = EmitAnnotationUnit(L),
967 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +0000968
Daniel Dunbar346892a2009-04-14 22:41:13 +0000969 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000970 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000971 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
972 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
973 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
974 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +0000975 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000976 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +0000977}
978
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000979void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
980 llvm::GlobalValue *GV) {
981 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
982 // Get the struct elements for these annotations.
983 for (specific_attr_iterator<AnnotateAttr>
984 ai = D->specific_attr_begin<AnnotateAttr>(),
985 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
986 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
987}
988
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +0000989bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000990 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000991 if (LangOpts.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000992 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000993
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +0000994 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000995}
996
Nico Webercf4ff5862012-10-11 10:13:44 +0000997llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
998 const CXXUuidofExpr* E) {
999 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1000 // well-formed.
1001 StringRef Uuid;
1002 if (E->isTypeOperand())
1003 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
1004 else {
1005 // Special case: __uuidof(0) means an all-zero GUID.
1006 Expr *Op = E->getExprOperand();
1007 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1008 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
1009 else
1010 Uuid = "00000000-0000-0000-0000-000000000000";
1011 }
1012 std::string Name = "__uuid_" + Uuid.str();
1013
1014 // Look for an existing global.
1015 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1016 return GV;
1017
1018 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1019 assert(Init && "failed to initialize as constant");
1020
1021 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
1022 // first field is declared as "long", which for many targets is 8 bytes.
1023 // Those architectures are not supported. (With the MS abi, long is always 4
1024 // bytes.)
1025 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
1026 if (Init->getType() != GuidType) {
1027 DiagnosticsEngine &Diags = getDiags();
1028 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1029 "__uuidof codegen is not supported on this architecture");
1030 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
1031 Init = llvm::UndefValue::get(GuidType);
1032 }
1033
1034 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
1035 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
1036 GV->setUnnamedAddr(true);
1037 return GV;
1038}
1039
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001040llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1041 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1042 assert(AA && "No alias?");
1043
Chris Lattner2192fe52011-07-18 04:24:23 +00001044 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001045
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001046 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001047 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001048 if (Entry) {
1049 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1050 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1051 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001052
1053 llvm::Constant *Aliasee;
1054 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001055 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1056 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001057 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001058 else
John McCall7ec50432010-03-19 23:29:14 +00001059 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001060 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001061
1062 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1063 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1064 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001065
1066 return Aliasee;
1067}
1068
Chris Lattnere0be0df2009-05-12 21:21:08 +00001069void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001070 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001071
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001072 // Weak references don't produce any output by themselves.
1073 if (Global->hasAttr<WeakRefAttr>())
1074 return;
1075
Chris Lattner54041692009-03-22 21:47:11 +00001076 // If this is an alias definition (which otherwise looks like a declaration)
1077 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001078 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +00001079 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001080
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001081 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001082 if (LangOpts.CUDA) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001083 if (CodeGenOpts.CUDAIsDevice) {
1084 if (!Global->hasAttr<CUDADeviceAttr>() &&
1085 !Global->hasAttr<CUDAGlobalAttr>() &&
1086 !Global->hasAttr<CUDAConstantAttr>() &&
1087 !Global->hasAttr<CUDASharedAttr>())
1088 return;
1089 } else {
1090 if (!Global->hasAttr<CUDAHostAttr>() && (
1091 Global->hasAttr<CUDADeviceAttr>() ||
1092 Global->hasAttr<CUDAConstantAttr>() ||
1093 Global->hasAttr<CUDASharedAttr>()))
1094 return;
1095 }
1096 }
1097
Chris Lattner45470942009-03-21 09:44:56 +00001098 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +00001099 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001100 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001101 if (!FD->doesThisDeclarationHaveABody()) {
1102 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1103 return;
1104
1105 const FunctionDecl *InlineDefinition = 0;
1106 FD->getBody(InlineDefinition);
1107
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001108 StringRef MangledName = getMangledName(GD);
Benjamin Kramere894e092012-03-24 18:22:12 +00001109 DeferredDecls.erase(MangledName);
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001110 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001111 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001112 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001113 } else {
1114 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001115 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1116
Douglas Gregor61f6db52010-02-06 05:15:45 +00001117 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +00001118 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +00001119 }
1120
Chris Lattner45470942009-03-21 09:44:56 +00001121 // Defer code generation when possible if this is a static definition, inline
1122 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001123 if (!MayDeferGeneration(Global)) {
1124 // Emit the definition if it can't be deferred.
1125 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001126 return;
1127 }
John McCall70013b62010-07-15 23:40:35 +00001128
1129 // If we're deferring emission of a C++ variable with an
1130 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001131 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001132 cast<VarDecl>(Global)->hasInit()) {
1133 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1134 CXXGlobalInits.push_back(0);
1135 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001136
1137 // If the value has already been used, add it directly to the
1138 // DeferredDeclsToEmit list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001139 StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001140 if (GetGlobalValue(MangledName))
1141 DeferredDeclsToEmit.push_back(GD);
1142 else {
1143 // Otherwise, remember that we saw a deferred decl with this name. The
1144 // first use of the mangled name will cause it to move into
1145 // DeferredDeclsToEmit.
1146 DeferredDecls[MangledName] = GD;
1147 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001148}
1149
Rafael Espindolac5941352011-10-26 20:41:06 +00001150namespace {
1151 struct FunctionIsDirectlyRecursive :
1152 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1153 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001154 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001155 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001156 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1157 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001158 }
1159 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1160
1161 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001162 const FunctionDecl *FD = E->getDirectCallee();
1163 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001164 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001165 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1166 if (Attr && Name == Attr->getLabel()) {
1167 Result = true;
1168 return false;
1169 }
1170 unsigned BuiltinID = FD->getBuiltinID();
1171 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +00001172 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001173 StringRef BuiltinName = BI.GetName(BuiltinID);
1174 if (BuiltinName.startswith("__builtin_") &&
1175 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001176 Result = true;
1177 return false;
1178 }
1179 return true;
1180 }
1181 };
1182}
1183
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001184// isTriviallyRecursive - Check if this function calls another
1185// decl that, because of the asm attribute or the other decl being a builtin,
1186// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001187bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001188CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1189 StringRef Name;
1190 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001191 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001192 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1193 if (!Attr)
1194 return false;
1195 Name = Attr->getLabel();
1196 } else {
1197 Name = FD->getName();
1198 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001199
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001200 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1201 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001202 return Walker.Result;
1203}
1204
1205bool
1206CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1207 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1208 return true;
Rafael Espindolafffc1ce2011-10-28 20:43:56 +00001209 if (CodeGenOpts.OptimizationLevel == 0 &&
Michael J. Spencerf97bd8c2012-06-18 07:00:48 +00001210 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001211 return false;
1212 // PR9614. Avoid cases where the source code is lying to us. An available
1213 // externally function should have an equivalent function somewhere else,
1214 // but a function that calls itself is clearly not equivalent to the real
1215 // implementation.
1216 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001217 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001218}
1219
Chris Lattnere0be0df2009-05-12 21:21:08 +00001220void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001221 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001222
Dan Gohman145f3f12010-04-19 16:39:44 +00001223 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001224 Context.getSourceManager(),
1225 "Generating code for declaration");
1226
Douglas Gregora700f682010-07-13 06:02:28 +00001227 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1228 // At -O0, don't generate IR for functions with available_externally
1229 // linkage.
Rafael Espindolac5941352011-10-26 20:41:06 +00001230 if (!shouldEmitFunction(Function))
Douglas Gregora700f682010-07-13 06:02:28 +00001231 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001232
Douglas Gregora700f682010-07-13 06:02:28 +00001233 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00001234 // Make sure to emit the definition(s) before we emit the thunks.
1235 // This is necessary for the generation of certain thunks.
1236 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1237 EmitCXXConstructor(CD, GD.getCtorType());
1238 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1239 EmitCXXDestructor(DD, GD.getDtorType());
1240 else
1241 EmitGlobalFunctionDefinition(GD);
1242
Douglas Gregora700f682010-07-13 06:02:28 +00001243 if (Method->isVirtual())
1244 getVTables().EmitThunks(GD);
1245
Eli Friedman49a94b12011-05-06 17:27:27 +00001246 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001247 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001248
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001249 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +00001250 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001251
1252 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1253 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001254
David Blaikie83d382b2011-09-23 05:06:16 +00001255 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001256}
1257
Chris Lattnerd4808922009-03-22 21:03:39 +00001258/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1259/// module, create and return an llvm Function with the specified type. If there
1260/// is something in the module with the specified name, return it potentially
1261/// bitcasted to the right type.
1262///
1263/// If D is non-null, it specifies a decl that correspond to this. This is used
1264/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001265llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001266CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001267 llvm::Type *Ty,
John McCall31168b02011-06-15 23:02:42 +00001268 GlobalDecl D, bool ForVTable,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001269 llvm::AttributeSet ExtraAttrs) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00001270 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001271 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001272 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001273 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001274 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1275 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001276 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001277 }
1278
Chris Lattnera85d68e2009-03-21 09:25:43 +00001279 if (Entry->getType()->getElementType() == Ty)
1280 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattnera85d68e2009-03-21 09:25:43 +00001282 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001283 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Eli Friedmancc522d92009-11-09 05:07:37 +00001286 // This function doesn't have a complete type (for example, the return
1287 // type is an incomplete struct). Use a fake type instead, and make
1288 // sure not to try to set attributes.
1289 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001290
Chris Lattner2192fe52011-07-18 04:24:23 +00001291 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001292 if (isa<llvm::FunctionType>(Ty)) {
1293 FTy = cast<llvm::FunctionType>(Ty);
1294 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001295 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001296 IsIncompleteFunction = true;
1297 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001298
John McCalld06fb862010-04-28 00:00:30 +00001299 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001300 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001301 MangledName, &getModule());
1302 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +00001303 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +00001304 SetFunctionAttributes(D, F, IsIncompleteFunction);
Bill Wendling8594fcb2013-01-31 00:30:05 +00001305 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1306 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling9a677922013-01-23 00:21:06 +00001307 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1308 llvm::AttributeSet::get(VMContext,
1309 llvm::AttributeSet::FunctionIndex,
1310 B));
1311 }
Eli Friedmancc522d92009-11-09 05:07:37 +00001312
Chris Lattner45470942009-03-21 09:44:56 +00001313 // This is the first use or definition of a mangled name. If there is a
1314 // deferred decl with this name, remember that we need to emit it at the end
1315 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001316 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001317 if (DDI != DeferredDecls.end()) {
1318 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1319 // list, and remove it from DeferredDecls (since we don't need it anymore).
1320 DeferredDeclsToEmit.push_back(DDI->second);
1321 DeferredDecls.erase(DDI);
John McCall357d0f32010-12-15 04:00:32 +00001322
1323 // Otherwise, there are cases we have to worry about where we're
1324 // using a declaration for which we must emit a definition but where
1325 // we might not find a top-level definition:
1326 // - member functions defined inline in their classes
1327 // - friend functions defined inline in some class
1328 // - special member functions with implicit definitions
1329 // If we ever change our AST traversal to walk into class methods,
1330 // this will be unnecessary.
Anders Carlsson3c239482011-02-05 04:35:53 +00001331 //
1332 // We also don't emit a definition for a function if it's going to be an entry
1333 // in a vtable, unless it's already marked as used.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001334 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
John McCall357d0f32010-12-15 04:00:32 +00001335 // Look for a declaration that's lexically in a record.
1336 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
Eli Friedmanc9f43942012-07-02 21:05:30 +00001337 FD = FD->getMostRecentDecl();
John McCall357d0f32010-12-15 04:00:32 +00001338 do {
1339 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson3c239482011-02-05 04:35:53 +00001340 if (FD->isImplicit() && !ForVTable) {
John McCall357d0f32010-12-15 04:00:32 +00001341 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregor25756312011-02-09 02:03:05 +00001342 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCall357d0f32010-12-15 04:00:32 +00001343 break;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001344 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregor25756312011-02-09 02:03:05 +00001345 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCall357d0f32010-12-15 04:00:32 +00001346 break;
1347 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00001348 }
Douglas Gregorec9fd132012-01-14 16:38:05 +00001349 FD = FD->getPreviousDecl();
John McCall357d0f32010-12-15 04:00:32 +00001350 } while (FD);
Chris Lattner45470942009-03-21 09:44:56 +00001351 }
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCalld06fb862010-04-28 00:00:30 +00001353 // Make sure the result is of the requested type.
1354 if (!IsIncompleteFunction) {
1355 assert(F->getType()->getElementType() == Ty);
1356 return F;
1357 }
1358
Chris Lattnera5f58b02011-07-09 17:41:47 +00001359 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001360 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001361}
1362
Chris Lattnerd4808922009-03-22 21:03:39 +00001363/// GetAddrOfFunction - Return the address of the given function. If Ty is
1364/// non-null, then this function will use the specified type if it has to
1365/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001366llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001367 llvm::Type *Ty,
Anders Carlsson3c239482011-02-05 04:35:53 +00001368 bool ForVTable) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001369 // If there was no specific requested type, just convert it now.
1370 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001371 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001372
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001373 StringRef MangledName = getMangledName(GD);
Anders Carlsson3c239482011-02-05 04:35:53 +00001374 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattnerd4808922009-03-22 21:03:39 +00001375}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001376
Chris Lattnerd4808922009-03-22 21:03:39 +00001377/// CreateRuntimeFunction - Create a new runtime function with the specified
1378/// type and name.
1379llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001380CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001381 StringRef Name,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001382 llvm::AttributeSet ExtraAttrs) {
John McCall882987f2013-02-28 19:01:20 +00001383 llvm::Constant *C
1384 = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1385 ExtraAttrs);
1386 if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1387 if (F->empty())
1388 F->setCallingConv(getRuntimeCC());
1389 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00001390}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001391
Richard Smithe070fd22012-02-17 06:48:11 +00001392/// isTypeConstant - Determine whether an object of this type can be emitted
1393/// as a constant.
1394///
1395/// If ExcludeCtor is true, the duration when the object's constructor runs
1396/// will not be considered. The caller will need to verify that the object is
1397/// not written to during its construction.
1398bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1399 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001400 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001401
David Blaikiebbafb8a2012-03-11 07:00:24 +00001402 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001403 if (const CXXRecordDecl *Record
1404 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1405 return ExcludeCtor && !Record->hasMutableFields() &&
1406 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001407 }
Richard Smithe070fd22012-02-17 06:48:11 +00001408
Eli Friedmanb095e152009-12-11 21:23:03 +00001409 return true;
1410}
1411
Chris Lattnerd4808922009-03-22 21:03:39 +00001412/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1413/// create and return an llvm GlobalVariable with the specified type. If there
1414/// is something in the module with the specified name, return it potentially
1415/// bitcasted to the right type.
1416///
1417/// If D is non-null, it specifies a decl that correspond to this. This is used
1418/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001419llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001420CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001421 llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +00001422 const VarDecl *D,
1423 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001424 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001425 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001426 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001427 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001428 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001429 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001430 }
1431
Rafael Espindolad661a852011-01-18 21:07:57 +00001432 if (UnnamedAddr)
1433 Entry->setUnnamedAddr(true);
1434
Chris Lattnerd4808922009-03-22 21:03:39 +00001435 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001436 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001437
Chris Lattner3bfce182009-03-21 08:03:33 +00001438 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +00001439 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Chris Lattner45470942009-03-21 09:44:56 +00001442 // This is the first use or definition of a mangled name. If there is a
1443 // deferred decl with this name, remember that we need to emit it at the end
1444 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001445 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001446 if (DDI != DeferredDecls.end()) {
1447 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1448 // list, and remove it from DeferredDecls (since we don't need it anymore).
1449 DeferredDeclsToEmit.push_back(DDI->second);
1450 DeferredDecls.erase(DDI);
1451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001453 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Mike Stump11289f42009-09-09 15:08:12 +00001454 llvm::GlobalVariable *GV =
1455 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +00001456 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001457 0, MangledName, 0,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001458 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Chris Lattner3bfce182009-03-21 08:03:33 +00001459
1460 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001461 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001462 // FIXME: This code is overly simple and should be merged with other global
1463 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001464 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001465
John McCall37bb6c92010-10-29 22:22:43 +00001466 // Set linkage and visibility in case we never see a definition.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +00001467 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +00001468 if (LV.getLinkage() != ExternalLinkage) {
John McCall83779672011-02-19 02:53:41 +00001469 // Don't set internal linkage on declarations.
John McCall37bb6c92010-10-29 22:22:43 +00001470 } else {
1471 if (D->hasAttr<DLLImportAttr>())
1472 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001473 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall37bb6c92010-10-29 22:22:43 +00001474 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +00001475
John McCallc273f242010-10-30 11:50:40 +00001476 // Set visibility on a declaration only if it's explicit.
Rafael Espindola4a5da442013-02-27 02:56:45 +00001477 if (LV.isVisibilityExplicit())
1478 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
John McCall37bb6c92010-10-29 22:22:43 +00001479 }
Eli Friedman4f856742009-04-19 21:05:03 +00001480
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001481 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00001482 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1483 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001484 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001485 }
Chris Lattnerd4808922009-03-22 21:03:39 +00001486 }
Mike Stump11289f42009-09-09 15:08:12 +00001487
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001488 if (AddrSpace != Ty->getAddressSpace())
1489 return llvm::ConstantExpr::getBitCast(GV, Ty);
1490 else
1491 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001492}
1493
Chris Lattnerd4808922009-03-22 21:03:39 +00001494
Anders Carlssonda80af32011-01-29 18:20:20 +00001495llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001496CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001497 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001498 llvm::GlobalValue::LinkageTypes Linkage) {
1499 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1500 llvm::GlobalVariable *OldGV = 0;
1501
1502
1503 if (GV) {
1504 // Check if the variable has the right type.
1505 if (GV->getType()->getElementType() == Ty)
1506 return GV;
1507
1508 // Because C++ name mangling, the only way we can end up with an already
1509 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00001510 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001511 OldGV = GV;
1512 }
1513
1514 // Create a new variable.
1515 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1516 Linkage, 0, Name);
1517
1518 if (OldGV) {
1519 // Replace occurrences of the old variable if needed.
1520 GV->takeName(OldGV);
1521
1522 if (!OldGV->use_empty()) {
1523 llvm::Constant *NewPtrForOldDecl =
1524 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1525 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1526 }
1527
1528 OldGV->eraseFromParent();
1529 }
1530
1531 return GV;
1532}
1533
Chris Lattnerd4808922009-03-22 21:03:39 +00001534/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1535/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001536/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001537/// normal requested type would be.
1538llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001539 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001540 assert(D->hasGlobalStorage() && "Not a global variable");
1541 QualType ASTTy = D->getType();
1542 if (Ty == 0)
1543 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001544
Chris Lattner2192fe52011-07-18 04:24:23 +00001545 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001546 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001547
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001548 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001549 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001550}
1551
1552/// CreateRuntimeVariable - Create a new runtime global variable with the
1553/// specified type and name.
1554llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001555CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001556 StringRef Name) {
John McCall31996342011-04-07 08:22:57 +00001557 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolad661a852011-01-18 21:07:57 +00001558 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001559}
1560
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001561void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1562 assert(!D->getInit() && "Cannot emit definite definitions here!");
1563
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001564 if (MayDeferGeneration(D)) {
1565 // If we have not seen a reference to this variable yet, place it
1566 // into the deferred declarations table to be emitted if needed
1567 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001568 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001569 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001570 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001571 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001572 }
1573 }
1574
1575 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001576 EmitGlobalVarDefinition(D);
1577}
1578
Chris Lattner2192fe52011-07-18 04:24:23 +00001579CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001580 return Context.toCharUnitsFromBits(
Micah Villmowdd31ca12012-10-08 16:25:52 +00001581 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001582}
1583
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001584llvm::Constant *
1585CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1586 const Expr *rawInit) {
1587 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1588 if (const ExprWithCleanups *withCleanups =
1589 dyn_cast<ExprWithCleanups>(rawInit)) {
1590 cleanups = withCleanups->getObjects();
1591 rawInit = withCleanups->getSubExpr();
1592 }
1593
1594 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1595 if (!init || !init->initializesStdInitializerList() ||
1596 init->getNumInits() == 0)
1597 return 0;
1598
1599 ASTContext &ctx = getContext();
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001600 unsigned numInits = init->getNumInits();
Sebastian Redla235e2d2012-02-27 23:20:01 +00001601 // FIXME: This check is here because we would otherwise silently miscompile
1602 // nested global std::initializer_lists. Better would be to have a real
1603 // implementation.
1604 for (unsigned i = 0; i < numInits; ++i) {
1605 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1606 if (inner && inner->initializesStdInitializerList()) {
1607 ErrorUnsupported(inner, "nested global std::initializer_list");
1608 return 0;
1609 }
1610 }
1611
1612 // Synthesize a fake VarDecl for the array and initialize that.
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001613 QualType elementType = init->getInit(0)->getType();
1614 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1615 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1616 ArrayType::Normal, 0);
1617
1618 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1619 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1620 arrayType, D->getLocation());
1621 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1622 D->getDeclContext()),
1623 D->getLocStart(), D->getLocation(),
1624 name, arrayType, sourceInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001625 SC_Static);
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +00001626 backingArray->setTSCSpec(D->getTSCSpec());
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001627
1628 // Now clone the InitListExpr to initialize the array instead.
1629 // Incredible hack: we want to use the existing InitListExpr here, so we need
1630 // to tell it that it no longer initializes a std::initializer_list.
Benjamin Kramerc215e762012-08-24 11:54:20 +00001631 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1632 init->getNumInits());
1633 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1634 init->getRBraceLoc());
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001635 arrayInit->setType(arrayType);
1636
1637 if (!cleanups.empty())
1638 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1639
1640 backingArray->setInit(arrayInit);
1641
1642 // Emit the definition of the array.
1643 EmitGlobalVarDefinition(backingArray);
1644
1645 // Inspect the initializer list to validate it and determine its type.
1646 // FIXME: doing this every time is probably inefficient; caching would be nice
1647 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1648 RecordDecl::field_iterator field = record->field_begin();
1649 if (field == record->field_end()) {
1650 ErrorUnsupported(D, "weird std::initializer_list");
1651 return 0;
1652 }
1653 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1654 // Start pointer.
1655 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1656 ErrorUnsupported(D, "weird std::initializer_list");
1657 return 0;
1658 }
1659 ++field;
1660 if (field == record->field_end()) {
1661 ErrorUnsupported(D, "weird std::initializer_list");
1662 return 0;
1663 }
1664 bool isStartEnd = false;
1665 if (ctx.hasSameType(field->getType(), elementPtr)) {
1666 // End pointer.
1667 isStartEnd = true;
1668 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1669 ErrorUnsupported(D, "weird std::initializer_list");
1670 return 0;
1671 }
1672
1673 // Now build an APValue representing the std::initializer_list.
1674 APValue initListValue(APValue::UninitStruct(), 0, 2);
1675 APValue &startField = initListValue.getStructField(0);
1676 APValue::LValuePathEntry startOffsetPathEntry;
1677 startOffsetPathEntry.ArrayIndex = 0;
1678 startField = APValue(APValue::LValueBase(backingArray),
1679 CharUnits::fromQuantity(0),
1680 llvm::makeArrayRef(startOffsetPathEntry),
1681 /*IsOnePastTheEnd=*/false, 0);
1682
1683 if (isStartEnd) {
1684 APValue &endField = initListValue.getStructField(1);
1685 APValue::LValuePathEntry endOffsetPathEntry;
1686 endOffsetPathEntry.ArrayIndex = numInits;
1687 endField = APValue(APValue::LValueBase(backingArray),
1688 ctx.getTypeSizeInChars(elementType) * numInits,
1689 llvm::makeArrayRef(endOffsetPathEntry),
1690 /*IsOnePastTheEnd=*/true, 0);
1691 } else {
1692 APValue &sizeField = initListValue.getStructField(1);
1693 sizeField = APValue(llvm::APSInt(numElements));
1694 }
1695
1696 // Emit the constant for the initializer_list.
Richard Smithbc6387672012-03-02 23:27:11 +00001697 llvm::Constant *llvmInit =
1698 EmitConstantValueForMemory(initListValue, D->getType());
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001699 assert(llvmInit && "failed to initialize as constant");
1700 return llvmInit;
1701}
1702
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001703unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1704 unsigned AddrSpace) {
1705 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1706 if (D->hasAttr<CUDAConstantAttr>())
1707 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1708 else if (D->hasAttr<CUDASharedAttr>())
1709 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1710 else
1711 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1712 }
1713
1714 return AddrSpace;
1715}
1716
Richard Smithdf931ce2013-04-06 05:00:46 +00001717template<typename SomeDecl>
1718void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1719 llvm::GlobalValue *GV) {
1720 if (!getLangOpts().CPlusPlus)
1721 return;
1722
1723 // Must have 'used' attribute, or else inline assembly can't rely on
1724 // the name existing.
1725 if (!D->template hasAttr<UsedAttr>())
1726 return;
1727
1728 // Must have internal linkage and an ordinary name.
1729 if (!D->getIdentifier() || D->getLinkage() != InternalLinkage)
1730 return;
1731
1732 // Must be in an extern "C" context. Entities declared directly within
1733 // a record are not extern "C" even if the record is in such a context.
1734 const DeclContext *DC = D->getFirstDeclaration()->getDeclContext();
1735 if (DC->isRecord() || !DC->isExternCContext())
1736 return;
1737
1738 // OK, this is an internal linkage entity inside an extern "C" linkage
1739 // specification. Make a note of that so we can give it the "expected"
1740 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00001741 std::pair<StaticExternCMap::iterator, bool> R =
1742 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00001743
1744 // If we have multiple internal linkage entities with the same name
1745 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00001746 if (!R.second)
1747 R.first->second = 0;
Richard Smithdf931ce2013-04-06 05:00:46 +00001748}
1749
Daniel Dunbar9c426522008-07-29 23:18:29 +00001750void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001751 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001752 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001753 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1754 bool NeedsGlobalCtor = false;
1755 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001756
Richard Smithdafff942012-01-14 04:30:29 +00001757 const VarDecl *InitDecl;
1758 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001759
Anders Carlssonca4a5452010-01-26 17:43:42 +00001760 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001761 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001762 // implicitly initialized with { 0 }.
1763 //
1764 // Note that tentative definitions are only emitted at the end of
1765 // a translation unit, so they should never have incomplete
1766 // type. In addition, EmitTentativeDefinition makes sure that we
1767 // never attempt to emit a tentative definition if a real one
1768 // exists. A use may still exists, however, so we still may need
1769 // to do a RAUW.
1770 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001771 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001772 } else {
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001773 // If this is a std::initializer_list, emit the special initializer.
1774 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1775 // An empty init list will perform zero-initialization, which happens
1776 // to be exactly what we want.
1777 // FIXME: It does so in a global constructor, which is *not* what we
1778 // want.
1779
Fariborz Jahanian63628032012-06-26 16:06:38 +00001780 if (!Init) {
1781 initializedGlobalDecl = GlobalDecl(D);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001782 Init = EmitConstantInit(*InitDecl);
Fariborz Jahanian63628032012-06-26 16:06:38 +00001783 }
Eli Friedman719ed1a2009-02-20 01:18:21 +00001784 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001785 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001786 if (D->getType()->isReferenceType())
1787 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00001788
David Blaikiebbafb8a2012-03-11 07:00:24 +00001789 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001790 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00001791 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001792 } else {
1793 ErrorUnsupported(D, "static initializer");
1794 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1795 }
John McCall70013b62010-07-15 23:40:35 +00001796 } else {
1797 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00001798 // initializer position (just in case this entry was delayed) if we
1799 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001800 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00001801 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001802 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001803 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001804
Chris Lattner2192fe52011-07-18 04:24:23 +00001805 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001806 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001807
Chris Lattner149927c2009-03-21 09:16:30 +00001808 // Strip off a bitcast if we got one back.
1809 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001810 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1811 // all zero index gep.
1812 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001813 Entry = CE->getOperand(0);
1814 }
Mike Stump11289f42009-09-09 15:08:12 +00001815
Chris Lattner149927c2009-03-21 09:16:30 +00001816 // Entry is now either a Function or GlobalVariable.
1817 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001818
Chris Lattner149927c2009-03-21 09:16:30 +00001819 // We have a definition after a declaration with the wrong type.
1820 // We must make a new GlobalVariable* and update everything that used OldGV
1821 // (a declaration or tentative definition) with the new GlobalVariable*
1822 // (which will be a definition).
1823 //
1824 // This happens if there is a prototype for a global (e.g.
1825 // "extern int x[];") and then a definition of a different type (e.g.
1826 // "int x[10];"). This also happens when an initializer has a different type
1827 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001828 if (GV == 0 ||
1829 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001830 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001831 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00001832
John McCall7ec50432010-03-19 23:29:14 +00001833 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001834 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001835
Chris Lattner149927c2009-03-21 09:16:30 +00001836 // Make a new global with the correct type, this is now guaranteed to work.
1837 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001838
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001839 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001840 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001841 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001842 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001843
1844 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001845 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001846 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001847
Richard Smithdf931ce2013-04-06 05:00:46 +00001848 MaybeHandleStaticInExternC(D, GV);
1849
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001850 if (D->hasAttr<AnnotateAttr>())
1851 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00001852
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001853 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001854
1855 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00001856 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1857 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00001858
Ken Dyck160146e2010-01-27 17:10:57 +00001859 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00001860
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001861 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001862 llvm::GlobalValue::LinkageTypes Linkage =
1863 GetLLVMLinkageVarDefinition(D, GV);
1864 GV->setLinkage(Linkage);
1865 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001866 // common vars aren't constant even if declared const.
1867 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001868
Daniel Dunbar38932572009-04-14 08:05:55 +00001869 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001870
John McCallcdf7ef52010-11-06 09:44:32 +00001871 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00001872 if (NeedsGlobalCtor || NeedsGlobalDtor)
1873 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00001874
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001875 // If we are compiling with ASan, add metadata indicating dynamically
1876 // initialized globals.
Will Dietzf54319c2013-01-18 11:30:38 +00001877 if (SanOpts.Address && NeedsGlobalCtor) {
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001878 llvm::Module &M = getModule();
1879
1880 llvm::NamedMDNode *DynamicInitializers =
1881 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1882 llvm::Value *GlobalToAdd[] = { GV };
1883 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1884 DynamicInitializers->addOperand(ThisGlobal);
1885 }
1886
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001887 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00001888 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001889 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00001890 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001891}
Chris Lattner09153c02007-06-22 18:48:09 +00001892
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001893llvm::GlobalValue::LinkageTypes
1894CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1895 llvm::GlobalVariable *GV) {
1896 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1897 if (Linkage == GVA_Internal)
1898 return llvm::Function::InternalLinkage;
1899 else if (D->hasAttr<DLLImportAttr>())
1900 return llvm::Function::DLLImportLinkage;
1901 else if (D->hasAttr<DLLExportAttr>())
1902 return llvm::Function::DLLExportLinkage;
1903 else if (D->hasAttr<WeakAttr>()) {
1904 if (GV->isConstant())
1905 return llvm::GlobalVariable::WeakODRLinkage;
1906 else
1907 return llvm::GlobalVariable::WeakAnyLinkage;
1908 } else if (Linkage == GVA_TemplateInstantiation ||
1909 Linkage == GVA_ExplicitTemplateInstantiation)
John McCalla97f3292011-04-12 01:46:54 +00001910 return llvm::GlobalVariable::WeakODRLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001911 else if (!getLangOpts().CPlusPlus &&
Eric Christopher8a2ee392010-12-02 02:45:55 +00001912 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1913 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001914 !D->hasExternalStorage() && !D->getInit() &&
Richard Smithfd3834f2013-04-13 02:43:54 +00001915 !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
Fariborz Jahanianab578bf2011-06-20 17:50:03 +00001916 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001917 // Thread local vars aren't considered common linkage.
1918 return llvm::GlobalVariable::CommonLinkage;
Bill Wendling95cae882013-05-02 19:18:03 +00001919 } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1920 getTarget().getTriple().isMacOSX())
1921 // On Darwin, the backing variable for a C++11 thread_local variable always
1922 // has internal linkage; all accesses should just be calls to the
1923 // Itanium-specified entry point, which has the normal linkage of the
1924 // variable.
1925 return llvm::GlobalValue::InternalLinkage;
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001926 return llvm::GlobalVariable::ExternalLinkage;
1927}
1928
John McCall49954ca2012-12-12 22:21:47 +00001929/// Replace the uses of a function that was declared with a non-proto type.
1930/// We want to silently drop extra arguments from call sites
1931static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1932 llvm::Function *newFn) {
1933 // Fast path.
1934 if (old->use_empty()) return;
1935
1936 llvm::Type *newRetTy = newFn->getReturnType();
1937 SmallVector<llvm::Value*, 4> newArgs;
1938
1939 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1940 ui != ue; ) {
1941 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1942 llvm::User *user = *use;
1943
1944 // Recognize and replace uses of bitcasts. Most calls to
1945 // unprototyped functions will use bitcasts.
1946 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1947 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1948 replaceUsesOfNonProtoConstant(bitcast, newFn);
1949 continue;
1950 }
1951
1952 // Recognize calls to the function.
1953 llvm::CallSite callSite(user);
1954 if (!callSite) continue;
1955 if (!callSite.isCallee(use)) continue;
1956
1957 // If the return types don't match exactly, then we can't
1958 // transform this call unless it's dead.
1959 if (callSite->getType() != newRetTy && !callSite->use_empty())
1960 continue;
1961
1962 // Get the call site's attribute list.
Bill Wendling290d9522013-01-27 02:46:53 +00001963 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCall49954ca2012-12-12 22:21:47 +00001964 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1965
1966 // Collect any return attributes from the call.
Bill Wendling304f6f02013-01-21 21:57:40 +00001967 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlingb7abb302013-01-21 22:45:00 +00001968 newAttrs.push_back(
Bill Wendling290d9522013-01-27 02:46:53 +00001969 llvm::AttributeSet::get(newFn->getContext(),
1970 oldAttrs.getRetAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00001971
1972 // If the function was passed too few arguments, don't transform.
1973 unsigned newNumArgs = newFn->arg_size();
1974 if (callSite.arg_size() < newNumArgs) continue;
1975
1976 // If extra arguments were passed, we silently drop them.
1977 // If any of the types mismatch, we don't transform.
1978 unsigned argNo = 0;
1979 bool dontTransform = false;
1980 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1981 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1982 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1983 dontTransform = true;
1984 break;
1985 }
1986
1987 // Add any parameter attributes.
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001988 if (oldAttrs.hasAttributes(argNo + 1))
1989 newAttrs.
Bill Wendling290d9522013-01-27 02:46:53 +00001990 push_back(llvm::
1991 AttributeSet::get(newFn->getContext(),
1992 oldAttrs.getParamAttributes(argNo + 1)));
John McCall49954ca2012-12-12 22:21:47 +00001993 }
1994 if (dontTransform)
1995 continue;
1996
Bill Wendling63ffde52013-01-18 21:26:07 +00001997 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendling290d9522013-01-27 02:46:53 +00001998 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1999 oldAttrs.getFnAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002000
2001 // Okay, we can transform this. Create the new call instruction and copy
2002 // over the required information.
2003 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2004
2005 llvm::CallSite newCall;
2006 if (callSite.isCall()) {
2007 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2008 callSite.getInstruction());
2009 } else {
2010 llvm::InvokeInst *oldInvoke =
2011 cast<llvm::InvokeInst>(callSite.getInstruction());
2012 newCall = llvm::InvokeInst::Create(newFn,
2013 oldInvoke->getNormalDest(),
2014 oldInvoke->getUnwindDest(),
2015 newArgs, "",
2016 callSite.getInstruction());
2017 }
2018 newArgs.clear(); // for the next iteration
2019
2020 if (!newCall->getType()->isVoidTy())
2021 newCall->takeName(callSite.getInstruction());
2022 newCall.setAttributes(
2023 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2024 newCall.setCallingConv(callSite.getCallingConv());
2025
2026 // Finally, remove the old call, replacing any uses with the new one.
2027 if (!callSite->use_empty())
2028 callSite->replaceAllUsesWith(newCall.getInstruction());
2029
2030 // Copy debug location attached to CI.
2031 if (!callSite->getDebugLoc().isUnknown())
2032 newCall->setDebugLoc(callSite->getDebugLoc());
2033 callSite->eraseFromParent();
2034 }
2035}
2036
Chris Lattner36797ab2009-05-05 06:16:31 +00002037/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2038/// implement a function with no prototype, e.g. "int foo() {}". If there are
2039/// existing call uses of the old function in the module, this adjusts them to
2040/// call the new function directly.
2041///
2042/// This is not just a cleanup: the always_inline pass requires direct calls to
2043/// functions to be able to inline them. If there is a bitcast in the way, it
2044/// won't inline them. Instcombine normally deletes these calls, but it isn't
2045/// run at -O0.
2046static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2047 llvm::Function *NewFn) {
2048 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00002049 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00002050
John McCall49954ca2012-12-12 22:21:47 +00002051 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00002052}
2053
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00002054void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2055 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2056 // If we have a definition, this might be a deferred decl. If the
2057 // instantiation is explicit, make sure we emit it at the end.
2058 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2059 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00002060
2061 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00002062}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002063
Chris Lattnere0be0df2009-05-12 21:21:08 +00002064void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00002065 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00002066
John McCall46288ef2011-03-09 08:12:35 +00002067 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00002068 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2069 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00002070
Chris Lattnereb7466d2009-05-12 20:58:15 +00002071 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00002072 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattnera85d68e2009-03-21 09:25:43 +00002074 // Strip off a bitcast if we got one back.
2075 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2076 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2077 Entry = CE->getOperand(0);
2078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
2080
Chris Lattnera85d68e2009-03-21 09:25:43 +00002081 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00002082 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002083
Daniel Dunbar99d28352009-03-09 23:53:08 +00002084 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00002085 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00002086 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00002087
Chris Lattner5eaee562009-03-21 08:38:50 +00002088 // F is the Function* for the one with the wrong type, we must make a new
2089 // Function* and update everything that used F (a declaration) with the new
2090 // Function* (which will be a definition).
2091 //
2092 // This happens if there is a prototype for a function
2093 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00002094 // (e.g. "int f(int x)"). Move the old function aside so that it
2095 // doesn't interfere with GetAddrOfFunction.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002096 OldFn->setName(StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00002097 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00002098
John McCall49954ca2012-12-12 22:21:47 +00002099 // This might be an implementation of a function without a
2100 // prototype, in which case, try to do special replacement of
2101 // calls which match the new prototype. The really key thing here
2102 // is that we also potentially drop arguments from the call site
2103 // so as to make a direct call, which makes the inliner happier
2104 // and suppresses a number of optimizer warnings (!) about
2105 // dropping arguments.
2106 if (!OldFn->use_empty()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00002107 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00002108 OldFn->removeDeadConstantUsers();
2109 }
Mike Stump11289f42009-09-09 15:08:12 +00002110
Chris Lattner5eaee562009-03-21 08:38:50 +00002111 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00002112 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00002113 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00002114 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00002115 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2116 }
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattner5eaee562009-03-21 08:38:50 +00002118 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00002119 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00002120
Chris Lattnera85d68e2009-03-21 09:25:43 +00002121 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002122 }
Mike Stump11289f42009-09-09 15:08:12 +00002123
John McCall8e7cb6d2010-11-02 21:04:24 +00002124 // We need to set linkage and visibility on the function before
2125 // generating code for it because various parts of IR generation
2126 // want to propagate this information down (e.g. to local static
2127 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00002128 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00002129 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002130
John McCall8e7cb6d2010-11-02 21:04:24 +00002131 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00002132 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00002133
Richard Smithdf931ce2013-04-06 05:00:46 +00002134 MaybeHandleStaticInExternC(D, Fn);
2135
John McCalla738c252011-03-09 04:27:21 +00002136 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00002137
Daniel Dunbar38932572009-04-14 08:05:55 +00002138 SetFunctionDefinitionAttributes(D, Fn);
2139 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00002140
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002141 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002142 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002143 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002144 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002145 if (D->hasAttr<AnnotateAttr>())
2146 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002147}
2148
John McCall7ec50432010-03-19 23:29:14 +00002149void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2150 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002151 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00002152 assert(AA && "Not an alias?");
2153
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002154 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00002155
John McCall7ec50432010-03-19 23:29:14 +00002156 // If there is a definition in the module, then it wins over the alias.
2157 // This is dubious, but allow it to be safe. Just ignore the alias.
2158 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2159 if (Entry && !Entry->isDeclaration())
2160 return;
2161
Chris Lattner2192fe52011-07-18 04:24:23 +00002162 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00002163
2164 // Create a reference to the named value. This ensures that it is emitted
2165 // if a deferred decl.
2166 llvm::Constant *Aliasee;
2167 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002168 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00002169 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00002170 else
John McCall7ec50432010-03-19 23:29:14 +00002171 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00002172 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00002173
2174 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00002175 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00002176 new llvm::GlobalAlias(Aliasee->getType(),
2177 llvm::Function::ExternalLinkage,
2178 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00002179
Chris Lattner54041692009-03-22 21:47:11 +00002180 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00002181 assert(Entry->isDeclaration());
2182
Chris Lattner54041692009-03-22 21:47:11 +00002183 // If there is a declaration in the module, then we had an extern followed
2184 // by the alias, as in:
2185 // extern int test6();
2186 // ...
2187 // int test6() __attribute__((alias("test7")));
2188 //
2189 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00002190 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002191
Owen Andersonade90fd2009-07-29 18:54:39 +00002192 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00002193 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00002194 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00002195 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00002196 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00002197 }
Mike Stump11289f42009-09-09 15:08:12 +00002198
Daniel Dunbar38932572009-04-14 08:05:55 +00002199 // Set attributes which are particular to an alias; this is a
2200 // specialization of the attributes which may be set on a global
2201 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002202 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2204 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002205 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00002206 GA->setLinkage(llvm::Function::DLLExportLinkage);
2207 } else {
2208 GA->setLinkage(llvm::Function::DLLExportLinkage);
2209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00002211 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002212 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002213 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2214 }
2215
2216 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00002217}
2218
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002219llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00002220 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00002221 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002222 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00002223}
Chris Lattner1eec6602007-08-31 04:31:45 +00002224
Daniel Dunbar64509b22009-07-23 22:52:48 +00002225static llvm::StringMapEntry<llvm::Constant*> &
2226GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2227 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00002228 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00002229 bool &IsUTF16,
2230 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002231 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002232 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002233
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002234 // Check for simple case.
2235 if (!Literal->containsNonAsciiOrNull()) {
2236 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002237 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002238 }
2239
Bill Wendling82b87f12012-03-30 00:26:17 +00002240 // Otherwise, convert the UTF8 literals into a string of shorts.
2241 IsUTF16 = true;
2242
2243 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divackye6377112012-09-06 15:59:27 +00002244 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002245 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00002246
Fariborz Jahanian535618b2010-09-07 19:57:04 +00002247 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2248 &ToPtr, ToPtr + NumBytes,
2249 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00002250
Daniel Dunbar91ade142009-07-23 23:41:22 +00002251 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00002252 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00002253
Bill Wendling82b87f12012-03-30 00:26:17 +00002254 // Add an explicit null.
2255 *ToPtr = 0;
2256 return Map.
2257 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2258 (StringLength + 1) * 2));
Daniel Dunbar64509b22009-07-23 22:52:48 +00002259}
2260
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002261static llvm::StringMapEntry<llvm::Constant*> &
2262GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00002263 const StringLiteral *Literal,
2264 unsigned &StringLength) {
2265 StringRef String = Literal->getString();
2266 StringLength = String.size();
2267 return Map.GetOrCreateValue(String);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002268}
2269
Daniel Dunbar64509b22009-07-23 22:52:48 +00002270llvm::Constant *
2271CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2272 unsigned StringLength = 0;
2273 bool isUTF16 = false;
2274 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00002275 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002276 getDataLayout().isLittleEndian(),
Daniel Dunbar91ade142009-07-23 23:41:22 +00002277 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002278
Daniel Dunbar64509b22009-07-23 22:52:48 +00002279 if (llvm::Constant *C = Entry.getValue())
2280 return C;
Mike Stump11289f42009-09-09 15:08:12 +00002281
Chris Lattnerece04092012-02-07 00:39:47 +00002282 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00002283 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002284 llvm::Value *V;
2285
Chris Lattneraa64ca22009-07-16 16:48:25 +00002286 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00002287 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002288 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002289 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002290 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00002291 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00002292 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002293 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2294 CFConstantStringClassRef = V;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002295 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002296 else
2297 V = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00002298
Anders Carlssonc2480a52008-11-15 18:54:24 +00002299 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00002300
Chris Lattner2192fe52011-07-18 04:24:23 +00002301 llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00002302 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2303
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002304 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00002305
Anders Carlssonb04ea612007-08-21 00:21:21 +00002306 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002307 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump11289f42009-09-09 15:08:12 +00002308
Anders Carlssonb04ea612007-08-21 00:21:21 +00002309 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00002310 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00002311 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00002312 llvm::ConstantInt::get(Ty, 0x07C8);
2313
Anders Carlssonb04ea612007-08-21 00:21:21 +00002314 // String pointer.
Bill Wendling82b87f12012-03-30 00:26:17 +00002315 llvm::Constant *C = 0;
2316 if (isUTF16) {
2317 ArrayRef<uint16_t> Arr =
David Greene0a528db2013-01-15 22:09:41 +00002318 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2319 const_cast<char *>(Entry.getKey().data())),
Bill Wendling82b87f12012-03-30 00:26:17 +00002320 Entry.getKey().size() / 2);
2321 C = llvm::ConstantDataArray::get(VMContext, Arr);
2322 } else {
2323 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2324 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002325
Chris Lattner3afa3e12009-07-16 05:03:48 +00002326 llvm::GlobalValue::LinkageTypes Linkage;
Bill Wendling86131f22012-01-10 08:46:39 +00002327 if (isUTF16)
Chris Lattner4f8a2e22009-10-14 05:55:45 +00002328 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00002329 Linkage = llvm::GlobalValue::InternalLinkage;
Bill Wendling86131f22012-01-10 08:46:39 +00002330 else
Rafael Espindola7a6cf012011-03-14 17:55:00 +00002331 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2332 // when using private linkage. It is not clear if this is a bug in ld
2333 // or a reasonable new restriction.
Rafael Espindola0c1f0982011-03-14 21:08:19 +00002334 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00002335
Bill Wendling86131f22012-01-10 08:46:39 +00002336 // Note: -fwritable-strings doesn't make the backing store strings of
2337 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump11289f42009-09-09 15:08:12 +00002338 llvm::GlobalVariable *GV =
Bill Wendling86131f22012-01-10 08:46:39 +00002339 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2340 Linkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002341 GV->setUnnamedAddr(true);
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002342 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002343 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2344 GV->setAlignment(Align.getQuantity());
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002345 } else {
2346 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2347 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002348 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002349
2350 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002351 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002352
Bill Wendling82b87f12012-03-30 00:26:17 +00002353 if (isUTF16)
2354 // Cast the UTF16 string to the correct type.
2355 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2356
Anders Carlssonb04ea612007-08-21 00:21:21 +00002357 // String length.
2358 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002359 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002360
Anders Carlssonb04ea612007-08-21 00:21:21 +00002361 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002362 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002363 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2364 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002365 "_unnamed_cfstring_");
John McCallc8e01702013-04-16 22:48:15 +00002366 if (const char *Sect = getTarget().getCFStringSection())
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002367 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00002368 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00002369
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002370 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002371}
Chris Lattnerfb300092007-11-28 05:34:05 +00002372
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002373static RecordDecl *
2374CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2375 DeclContext *DC, IdentifierInfo *Id) {
2376 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002377 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002378 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2379 else
2380 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2381}
2382
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002383llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002384CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002385 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002386 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002387 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002388
2389 if (llvm::Constant *C = Entry.getValue())
2390 return C;
2391
Chris Lattner00a10ca2012-02-06 22:47:00 +00002392 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002393 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002394 llvm::Value *V;
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002395 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002396 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002397 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002398 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002399 llvm::Constant *GV;
John McCall5fb5df92012-06-20 06:18:46 +00002400 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002401 std::string str =
2402 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2403 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002404 GV = getObjCRuntime().GetClassGlobal(str);
2405 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002406 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002407 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2408 ConstantStringClassRef = V;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002409 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002410 std::string str =
2411 StringClass.empty() ? "_NSConstantStringClassReference"
2412 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002413 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002414 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002415 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002416 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2417 ConstantStringClassRef = V;
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002418 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002419 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002420 else
2421 V = ConstantStringClassRef;
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002422
2423 if (!NSConstantStringType) {
2424 // Construct the type for a constant NSString.
2425 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2426 Context.getTranslationUnitDecl(),
2427 &Context.Idents.get("__builtin_NSString"));
2428 D->startDefinition();
2429
2430 QualType FieldTypes[3];
2431
2432 // const int *isa;
2433 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2434 // const char *str;
2435 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2436 // unsigned int length;
2437 FieldTypes[2] = Context.UnsignedIntTy;
2438
2439 // Create fields
2440 for (unsigned i = 0; i < 3; ++i) {
2441 FieldDecl *Field = FieldDecl::Create(Context, D,
2442 SourceLocation(),
2443 SourceLocation(), 0,
2444 FieldTypes[i], /*TInfo=*/0,
2445 /*BitWidth=*/0,
2446 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002447 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002448 Field->setAccess(AS_public);
2449 D->addDecl(Field);
2450 }
2451
2452 D->completeDefinition();
2453 QualType NSTy = Context.getTagDeclType(D);
2454 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2455 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002456
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002457 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002458
2459 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002460 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002461
2462 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002463 llvm::Constant *C =
2464 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002465
2466 llvm::GlobalValue::LinkageTypes Linkage;
2467 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002468 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002469 isConstant = !LangOpts.WritableStrings;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002470
2471 llvm::GlobalVariable *GV =
2472 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2473 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002474 GV->setUnnamedAddr(true);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002475 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2476 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002477 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002478
2479 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002480 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002481 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2482
2483 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002484 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002485 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2486 llvm::GlobalVariable::PrivateLinkage, C,
2487 "_unnamed_nsstring_");
2488 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002489 if (const char *Sect =
John McCall5fb5df92012-06-20 06:18:46 +00002490 LangOpts.ObjCRuntime.isNonFragile()
John McCallc8e01702013-04-16 22:48:15 +00002491 ? getTarget().getNSStringNonFragileABISection()
2492 : getTarget().getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002493 GV->setSection(Sect);
2494 Entry.setValue(GV);
2495
2496 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002497}
2498
Douglas Gregor636e2002011-08-09 17:23:49 +00002499QualType CodeGenModule::getObjCFastEnumerationStateType() {
2500 if (ObjCFastEnumerationStateType.isNull()) {
2501 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2502 Context.getTranslationUnitDecl(),
2503 &Context.Idents.get("__objcFastEnumerationState"));
2504 D->startDefinition();
2505
2506 QualType FieldTypes[] = {
2507 Context.UnsignedLongTy,
2508 Context.getPointerType(Context.getObjCIdType()),
2509 Context.getPointerType(Context.UnsignedLongTy),
2510 Context.getConstantArrayType(Context.UnsignedLongTy,
2511 llvm::APInt(32, 5), ArrayType::Normal, 0)
2512 };
2513
2514 for (size_t i = 0; i < 4; ++i) {
2515 FieldDecl *Field = FieldDecl::Create(Context,
2516 D,
2517 SourceLocation(),
2518 SourceLocation(), 0,
2519 FieldTypes[i], /*TInfo=*/0,
2520 /*BitWidth=*/0,
2521 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002522 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002523 Field->setAccess(AS_public);
2524 D->addDecl(Field);
2525 }
2526
2527 D->completeDefinition();
2528 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2529 }
2530
2531 return ObjCFastEnumerationStateType;
2532}
2533
Eli Friedmanfcec6302011-11-01 02:23:42 +00002534llvm::Constant *
2535CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2536 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2537
2538 // Don't emit it as the address of the string, emit the string data itself
2539 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002540 if (E->getCharByteWidth() == 1) {
2541 SmallString<64> Str(E->getString());
2542
2543 // Resize the string to the right size, which is indicated by its type.
2544 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2545 Str.resize(CAT->getSize().getZExtValue());
2546 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2547 }
Chris Lattner9c818332012-02-05 02:30:40 +00002548
2549 llvm::ArrayType *AType =
2550 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2551 llvm::Type *ElemTy = AType->getElementType();
2552 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002553
2554 // Wide strings have either 2-byte or 4-byte elements.
2555 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2556 SmallVector<uint16_t, 32> Elements;
2557 Elements.reserve(NumElements);
2558
2559 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2560 Elements.push_back(E->getCodeUnit(i));
2561 Elements.resize(NumElements);
2562 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002563 }
2564
Chris Lattner02cb1712012-02-06 22:52:04 +00002565 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2566 SmallVector<uint32_t, 32> Elements;
2567 Elements.reserve(NumElements);
2568
2569 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2570 Elements.push_back(E->getCodeUnit(i));
2571 Elements.resize(NumElements);
2572 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002573}
2574
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002575/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2576/// constant array for the given string literal.
2577llvm::Constant *
2578CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
John McCall9b24df42011-08-04 01:03:22 +00002579 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
Eli Friedmanfcec6302011-11-01 02:23:42 +00002580 if (S->isAscii() || S->isUTF8()) {
Chris Lattner00a10ca2012-02-06 22:47:00 +00002581 SmallString<64> Str(S->getString());
2582
2583 // Resize the string to the right size, which is indicated by its type.
2584 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2585 Str.resize(CAT->getSize().getZExtValue());
2586 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002587 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002588
Chris Lattner00a10ca2012-02-06 22:47:00 +00002589 // FIXME: the following does not memoize wide strings.
Eli Friedmanfcec6302011-11-01 02:23:42 +00002590 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2591 llvm::GlobalVariable *GV =
2592 new llvm::GlobalVariable(getModule(),C->getType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002593 !LangOpts.WritableStrings,
Eli Friedmanfcec6302011-11-01 02:23:42 +00002594 llvm::GlobalValue::PrivateLinkage,
2595 C,".str");
Seth Cantrellc9196652012-01-18 12:11:32 +00002596
Eli Friedmanfcec6302011-11-01 02:23:42 +00002597 GV->setAlignment(Align.getQuantity());
2598 GV->setUnnamedAddr(true);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002599 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002600}
2601
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002602/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2603/// array for the given ObjCEncodeExpr node.
2604llvm::Constant *
2605CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2606 std::string Str;
2607 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002608
2609 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002610}
2611
2612
Chris Lattner36fc8792008-02-11 00:02:17 +00002613/// GenerateWritableString -- Creates storage for a string literal.
John McCall9b24df42011-08-04 01:03:22 +00002614static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattnerfb300092007-11-28 05:34:05 +00002615 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00002616 CodeGenModule &CGM,
John McCall9b24df42011-08-04 01:03:22 +00002617 const char *GlobalName,
2618 unsigned Alignment) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002619 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00002620 llvm::Constant *C =
Chris Lattner9c818332012-02-05 02:30:40 +00002621 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00002622
Chris Lattnerfb300092007-11-28 05:34:05 +00002623 // Create a global variable for this string
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002624 llvm::GlobalVariable *GV =
2625 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2626 llvm::GlobalValue::PrivateLinkage,
2627 C, GlobalName);
John McCall9b24df42011-08-04 01:03:22 +00002628 GV->setAlignment(Alignment);
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002629 GV->setUnnamedAddr(true);
2630 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002631}
2632
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002633/// GetAddrOfConstantString - Returns a pointer to a character array
2634/// containing the literal. This contents are exactly that of the
2635/// given string, i.e. it will not be null terminated automatically;
2636/// see GetAddrOfConstantCString. Note that whether the result is
2637/// actually a pointer to an LLVM constant depends on
2638/// Feature.WriteableStrings.
2639///
2640/// The result has pointer to array type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002641llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCall9b24df42011-08-04 01:03:22 +00002642 const char *GlobalName,
2643 unsigned Alignment) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002644 // Get the default prefix if a name wasn't specified.
2645 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00002646 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002647
2648 // Don't share any string literals if strings aren't constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002649 if (LangOpts.WritableStrings)
John McCall9b24df42011-08-04 01:03:22 +00002650 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump11289f42009-09-09 15:08:12 +00002651
John McCall9b24df42011-08-04 01:03:22 +00002652 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002653 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattnerfb300092007-11-28 05:34:05 +00002654
John McCall9b24df42011-08-04 01:03:22 +00002655 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2656 if (Alignment > GV->getAlignment()) {
2657 GV->setAlignment(Alignment);
2658 }
2659 return GV;
2660 }
Chris Lattnerfb300092007-11-28 05:34:05 +00002661
2662 // Create a global variable for this.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002663 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2664 Alignment);
John McCall9b24df42011-08-04 01:03:22 +00002665 Entry.setValue(GV);
2666 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002667}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002668
2669/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002670/// array containing the literal and a terminating '\0'
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002671/// character. The result has pointer to array type.
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002672llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCall9b24df42011-08-04 01:03:22 +00002673 const char *GlobalName,
2674 unsigned Alignment) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002675 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall9b24df42011-08-04 01:03:22 +00002676 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002677}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002678
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002679/// EmitObjCPropertyImplementations - Emit information for synthesized
2680/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00002681void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002682 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00002683 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002684 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002685 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00002686
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002687 // Dynamic is just for type-checking.
2688 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2689 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2690
2691 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00002692 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002693 // we want, that just indicates if the decl came from a
2694 // property. What we want to know is if the method is defined in
2695 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002696 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002697 CodeGenFunction(*this).GenerateObjCGetter(
2698 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002699 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002700 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002701 CodeGenFunction(*this).GenerateObjCSetter(
2702 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002703 }
2704 }
2705}
2706
John McCall6a4fa522011-03-22 07:05:39 +00002707static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002708 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2709 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00002710 ivar; ivar = ivar->getNextIvar())
2711 if (ivar->getType().isDestructedType())
2712 return true;
2713
2714 return false;
2715}
2716
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002717/// EmitObjCIvarInitializations - Emit information for ivar initialization
2718/// for an implementation.
2719void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00002720 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2721 if (needsDestructMethod(D)) {
2722 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2723 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2724 ObjCMethodDecl *DTORMethod =
2725 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002726 cxxSelector, getContext().VoidTy, 0, D,
2727 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002728 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002729 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00002730 D->addInstanceMethod(DTORMethod);
2731 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00002732 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00002733 }
2734
2735 // If the implementation doesn't have any ivar initializers, we don't need
2736 // a .cxx_construct.
David Chisnalla9e54602011-03-17 14:19:08 +00002737 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002738 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002739
John McCall6a4fa522011-03-22 07:05:39 +00002740 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2741 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002742 // The constructor returns 'self'.
2743 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2744 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002745 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002746 cxxSelector,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002747 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002748 D, /*isInstance=*/true,
2749 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002750 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002751 /*isImplicitlyDeclared=*/true,
2752 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002753 ObjCMethodDecl::Required);
2754 D->addInstanceMethod(CTORMethod);
2755 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00002756 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002757}
2758
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002759/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00002760void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002761 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00002762 I != E; ++I)
2763 EmitTopLevelDecl(*I);
2764}
2765
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002766// EmitLinkageSpec - Emit all declarations in a linkage spec.
2767void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00002768 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2769 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002770 ErrorUnsupported(LSD, "linkage spec");
2771 return;
2772 }
2773
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002774 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002775 I != E; ++I) {
Fariborz Jahanian9dd2e082012-10-26 22:20:25 +00002776 // Meta-data for ObjC class includes references to implemented methods.
2777 // Generate class's method definitions first.
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002778 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2779 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2780 MEnd = OID->meth_end();
2781 M != MEnd; ++M)
2782 EmitTopLevelDecl(*M);
2783 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002784 EmitTopLevelDecl(*I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002785 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002786}
2787
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002788/// EmitTopLevelDecl - Emit code for a single top level declaration.
2789void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2790 // If an error has occurred, stop code generation, but continue
2791 // parsing and semantic analysis (to ensure all warnings and errors
2792 // are emitted).
2793 if (Diags.hasErrorOccurred())
2794 return;
2795
Douglas Gregor70d83e22009-06-29 17:30:29 +00002796 // Ignore dependent declarations.
2797 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2798 return;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002800 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00002801 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00002802 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002803 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00002804 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002805 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2806 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00002807 return;
Mike Stump11289f42009-09-09 15:08:12 +00002808
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002809 EmitGlobal(cast<FunctionDecl>(D));
2810 break;
2811
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002812 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002813 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002814 break;
2815
John McCall32f44bd2011-04-12 01:01:22 +00002816 // Indirect fields from global anonymous structs and unions can be
2817 // ignored; only the actual variable requires IR gen support.
2818 case Decl::IndirectField:
2819 break;
2820
Anders Carlssonf7475242009-04-15 15:55:24 +00002821 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002822 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00002823 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002824 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00002825 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00002826 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00002827 case Decl::Using:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002828 case Decl::ClassTemplate:
2829 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002830 case Decl::TypeAliasTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00002831 case Decl::NamespaceAlias:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002832 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00002833 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00002834 break;
David Blaikie60a9fbf2013-04-26 05:41:06 +00002835 case Decl::UsingDirective: // using namespace X; [C++]
2836 if (CGDebugInfo *DI = getModuleDebugInfo())
2837 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2838 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00002839 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00002840 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002841 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2842 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00002843 return;
2844
Anders Carlssonf7475242009-04-15 15:55:24 +00002845 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2846 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002847 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00002848 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2849 return;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002850 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2851 break;
Anders Carlsson87835432009-06-11 21:22:55 +00002852
2853 case Decl::StaticAssert:
2854 // Nothing to do.
2855 break;
2856
Anders Carlssonf7475242009-04-15 15:55:24 +00002857 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00002858
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002859 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00002860 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00002861 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002862 break;
2863
Douglas Gregorf6102672012-01-01 21:23:57 +00002864 case Decl::ObjCProtocol: {
2865 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2866 if (Proto->isThisDeclarationADefinition())
2867 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002868 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00002869 }
2870
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002871 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002872 // Categories have properties but don't support synthesize so we
2873 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00002874 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002875 break;
2876
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002877 case Decl::ObjCImplementation: {
2878 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2879 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002880 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00002881 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00002882 // Emit global variable debug information.
2883 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00002884 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2885 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2886 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002887 break;
Mike Stump11289f42009-09-09 15:08:12 +00002888 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002889 case Decl::ObjCMethod: {
2890 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2891 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002892 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002893 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2894 break;
2895 }
Mike Stump11289f42009-09-09 15:08:12 +00002896 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00002897 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002898 break;
2899
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002900 case Decl::LinkageSpec:
2901 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002902 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002903
2904 case Decl::FileScopeAsm: {
2905 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002906 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002907
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002908 const std::string &S = getModule().getModuleInlineAsm();
2909 if (S.empty())
2910 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8c02a242012-08-10 10:57:52 +00002911 else if (S.end()[-1] == '\n')
Chris Lattner84037d32011-07-23 20:04:25 +00002912 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002913 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002914 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002915 break;
2916 }
Mike Stump11289f42009-09-09 15:08:12 +00002917
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002918 case Decl::Import: {
2919 ImportDecl *Import = cast<ImportDecl>(D);
2920
2921 // Ignore import declarations that come from imported modules.
2922 if (clang::Module *Owner = Import->getOwningModule()) {
2923 if (getLangOpts().CurrentModule.empty() ||
2924 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2925 break;
2926 }
2927
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002928 ImportedModules.insert(Import->getImportedModule());
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002929 break;
2930 }
2931
Mike Stump11289f42009-09-09 15:08:12 +00002932 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002933 // Make sure we handled everything we should, every other kind is a
2934 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2935 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002936 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2937 }
2938}
John McCall09ae0322010-07-06 23:57:41 +00002939
2940/// Turns the given pointer into a constant.
2941static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2942 const void *Ptr) {
2943 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00002944 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00002945 return llvm::ConstantInt::get(i64, PtrInt);
2946}
2947
2948static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2949 llvm::NamedMDNode *&GlobalMetadata,
2950 GlobalDecl D,
2951 llvm::GlobalValue *Addr) {
2952 if (!GlobalMetadata)
2953 GlobalMetadata =
2954 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2955
2956 // TODO: should we report variant information for ctors/dtors?
2957 llvm::Value *Ops[] = {
2958 Addr,
2959 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2960 };
Jay Foadea324f12011-04-21 19:59:12 +00002961 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00002962}
2963
Richard Smithdf931ce2013-04-06 05:00:46 +00002964/// For each function which is declared within an extern "C" region and marked
2965/// as 'used', but has internal linkage, create an alias from the unmangled
2966/// name to the mangled name if possible. People expect to be able to refer
2967/// to such functions with an unmangled name from inline assembly within the
2968/// same translation unit.
2969void CodeGenModule::EmitStaticExternCAliases() {
Richard Smithf21c9612013-04-13 01:28:18 +00002970 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
2971 E = StaticExternCValues.end();
2972 I != E; ++I) {
2973 IdentifierInfo *Name = I->first;
2974 llvm::GlobalValue *Val = I->second;
Richard Smith85465e62013-04-06 07:07:44 +00002975 if (Val && !getModule().getNamedValue(Name->getName()))
2976 AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
2977 Name->getName(), Val, &getModule()));
2978 }
Richard Smithdf931ce2013-04-06 05:00:46 +00002979}
2980
John McCall09ae0322010-07-06 23:57:41 +00002981/// Emits metadata nodes associating all the global values in the
2982/// current module with the Decls they came from. This is useful for
2983/// projects using IR gen as a subroutine.
2984///
2985/// Since there's currently no way to associate an MDNode directly
2986/// with an llvm::GlobalValue, we create a global named metadata
2987/// with the name 'clang.global.decl.ptrs'.
2988void CodeGenModule::EmitDeclMetadata() {
2989 llvm::NamedMDNode *GlobalMetadata = 0;
2990
2991 // StaticLocalDeclMap
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002992 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall09ae0322010-07-06 23:57:41 +00002993 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2994 I != E; ++I) {
2995 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2996 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2997 }
2998}
2999
3000/// Emits metadata nodes for all the local variables in the current
3001/// function.
3002void CodeGenFunction::EmitDeclMetadata() {
3003 if (LocalDeclMap.empty()) return;
3004
3005 llvm::LLVMContext &Context = getLLVMContext();
3006
3007 // Find the unique metadata ID for this name.
3008 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3009
3010 llvm::NamedMDNode *GlobalMetadata = 0;
3011
3012 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3013 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3014 const Decl *D = I->first;
3015 llvm::Value *Addr = I->second;
3016
3017 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3018 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foadea324f12011-04-21 19:59:12 +00003019 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall09ae0322010-07-06 23:57:41 +00003020 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3021 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3022 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3023 }
3024 }
3025}
Daniel Dunbar900546d2010-07-16 00:00:15 +00003026
Nick Lewycky85c011d2011-05-05 00:08:20 +00003027void CodeGenModule::EmitCoverageFile() {
3028 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00003029 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3030 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3031 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00003032 llvm::MDString *CoverageFile =
3033 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00003034 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3035 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky85c011d2011-05-05 00:08:20 +00003036 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky480cb992011-05-04 20:46:58 +00003037 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3038 GCov->addOperand(N);
3039 }
3040 }
3041 }
3042}
Nico Webercf4ff5862012-10-11 10:13:44 +00003043
3044llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3045 QualType GuidType) {
3046 // Sema has checked that all uuid strings are of the form
3047 // "12345678-1234-1234-1234-1234567890ab".
3048 assert(Uuid.size() == 36);
3049 const char *Uuidstr = Uuid.data();
3050 for (int i = 0; i < 36; ++i) {
3051 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
Jordan Rosea7d03842013-02-08 22:30:41 +00003052 else assert(isHexDigit(Uuidstr[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00003053 }
3054
3055 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
3056 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
3057 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
Nico Weber92724072012-10-17 00:34:34 +00003058 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00003059
3060 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3061 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3062 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3063 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3064 APValue& Arr = InitStruct.getStructField(3);
3065 Arr = APValue(APValue::UninitArray(), 8, 8);
3066 for (int t = 0; t < 8; ++t)
Nico Webercc51c2f2012-10-13 21:56:05 +00003067 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3068 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
Nico Webercf4ff5862012-10-11 10:13:44 +00003069
3070 return EmitConstantValue(InitStruct, GuidType);
3071}