blob: 83e927fcadbc2190e049b1fec2cba1b98bafc771 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Dan Gohman3d5aff52010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000018#include "CGCall.h"
John McCall4c40d982010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000021#include "TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000036#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/Intrinsics.h"
Chris Lattnerd5b89022009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCall6374c332010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Rafael Espindolac4850c22011-02-10 23:59:36 +000040#include "llvm/Target/Mangler.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000041#include "llvm/Target/TargetData.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000042#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000043#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000044using namespace clang;
45using namespace CodeGen;
46
John McCallf16aa102010-08-22 21:01:12 +000047static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48 switch (CGM.getContext().Target.getCXXABI()) {
49 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
52 }
53
54 llvm_unreachable("invalid C++ ABI kind");
55 return *CreateItaniumCXXABI(CGM);
56}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058
Chandler Carruth2811ccf2009-11-12 17:24:48 +000059CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall468ec6c2010-03-04 04:29:44 +000060 llvm::Module &M, const llvm::TargetData &TD,
61 Diagnostic &diags)
John McCalld16c2cf2011-02-08 08:22:06 +000062 : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall468ec6c2010-03-04 04:29:44 +000063 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000064 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman3d5aff52010-10-14 23:06:10 +000066 TBAA(0),
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000067 VTables(*this), Runtime(0), DebugInfo(0),
Fariborz Jahanian4c733072010-10-19 17:19:29 +000068 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000069 VMContext(M.getContext()),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000070 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000071 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar754b9fb2010-07-16 00:00:19 +000072 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
John McCalld16c2cf2011-02-08 08:22:06 +000073 BlockObjectAssign(0), BlockObjectDispose(0),
74 BlockDescriptorType(0), GenericBlockLiteralType(0) {
David Chisnall60be6072011-03-22 21:21:24 +000075 if (Features.ObjC1)
76 createObjCRuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000077
Dan Gohman3d5aff52010-10-14 23:06:10 +000078 // Enable TBAA unless it's suppressed.
79 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman0b5c4fc2010-10-15 20:23:12 +000080 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
81 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +000082
Nick Lewyckye8ba8d72011-04-21 23:44:07 +000083 // If debug info or coverage generation is enabled, create the CGDebugInfo
84 // object.
85 if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
86 CodeGenOpts.EmitGcovNotes)
87 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +000088
89 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +000090
91 // Initialize the type cache.
92 llvm::LLVMContext &LLVMContext = M.getContext();
93 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
95 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
96 PointerWidthInBits = C.Target.getPointerWidth(0);
John McCall34695852011-02-22 06:44:22 +000097 PointerAlignInBytes =
98 C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
John McCall5936e332011-02-15 09:22:45 +000099 IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
100 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
101 Int8PtrTy = Int8Ty->getPointerTo(0);
102 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Chris Lattner2b94fe32008-03-01 08:45:05 +0000103}
104
105CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +0000106 delete Runtime;
John McCallf16aa102010-08-22 21:01:12 +0000107 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000108 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000109 delete DebugInfo;
110}
111
David Chisnall0d13f6f2010-01-23 02:40:42 +0000112void CodeGenModule::createObjCRuntime() {
113 if (!Features.NeXTRuntime)
114 Runtime = CreateGNUObjCRuntime(*this);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000115 else
116 Runtime = CreateMacObjCRuntime(*this);
117}
118
Ted Kremenek815c78f2008-08-05 18:50:11 +0000119void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000120 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000121 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000122 EmitCXXGlobalDtorFunc();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000123 if (Runtime)
124 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
125 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000126 EmitCtorList(GlobalCtors, "llvm.global_ctors");
127 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +0000128 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000129 EmitLLVMUsed();
John McCall744016d2010-07-06 23:57:41 +0000130
John McCallb2593832010-09-16 06:16:50 +0000131 SimplifyPersonality();
132
John McCall744016d2010-07-06 23:57:41 +0000133 if (getCodeGenOpts().EmitDeclMetadata)
134 EmitDeclMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000135}
136
Devang Patele80d5672011-03-23 16:29:39 +0000137void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
138 // Make sure that this type is translated.
139 Types.UpdateCompletedType(TD);
140 if (DebugInfo)
141 DebugInfo->UpdateCompletedType(TD);
142}
143
Dan Gohman3d5aff52010-10-14 23:06:10 +0000144llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
145 if (!TBAA)
146 return 0;
147 return TBAA->getTBAAInfo(QTy);
148}
149
150void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
151 llvm::MDNode *TBAAInfo) {
152 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
153}
154
John McCall6374c332010-03-06 00:35:14 +0000155bool CodeGenModule::isTargetDarwin() const {
Daniel Dunbardb57a4c2011-04-19 21:43:27 +0000156 return getContext().Target.getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000157}
158
John McCall32096692011-03-18 02:56:14 +0000159void CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
160 unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
161 getDiags().Report(Context.getFullLoc(loc), diagID);
162}
163
Daniel Dunbar488e9932008-08-16 00:56:44 +0000164/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000165/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000166void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
167 bool OmitOnError) {
168 if (OmitOnError && getDiags().hasErrorOccurred())
169 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000170 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000171 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000172 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000173 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
174 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000175}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000176
Daniel Dunbar488e9932008-08-16 00:56:44 +0000177/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000178/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000179void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
180 bool OmitOnError) {
181 if (OmitOnError && getDiags().hasErrorOccurred())
182 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000183 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000184 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000185 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000186 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000187}
188
Mike Stump1eb44332009-09-09 15:08:12 +0000189void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000190 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000191 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000192 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000193 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000194 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000195 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000196
John McCallaf146032010-10-30 11:50:40 +0000197 // Set visibility for definitions.
198 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola071d3af2011-02-01 05:45:26 +0000199 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
200 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000201}
202
John McCallcbfe5022010-08-04 08:34:44 +0000203/// Set the symbol visibility of type information (vtable and RTTI)
204/// associated with the given type.
205void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
206 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000207 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000208 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000209
John McCall279b5eb2010-08-12 23:36:15 +0000210 if (!CodeGenOpts.HiddenWeakVTables)
211 return;
212
Anders Carlsson9a86a132011-01-29 20:36:11 +0000213 // We never want to drop the visibility for RTTI names.
214 if (TVK == TVK_ForRTTIName)
215 return;
216
John McCallcbfe5022010-08-04 08:34:44 +0000217 // We want to drop the visibility to hidden for weak type symbols.
218 // This isn't possible if there might be unresolved references
219 // elsewhere that rely on this symbol being visible.
220
John McCall7a536902010-08-05 20:39:18 +0000221 // This should be kept roughly in sync with setThunkVisibility
222 // in CGVTables.cpp.
223
John McCallcbfe5022010-08-04 08:34:44 +0000224 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000225 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000226 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
227 return;
228
229 // Don't override an explicit visibility attribute.
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000230 if (RD->getExplicitVisibility())
John McCallcbfe5022010-08-04 08:34:44 +0000231 return;
232
233 switch (RD->getTemplateSpecializationKind()) {
234 // We have to disable the optimization if this is an EI definition
235 // because there might be EI declarations in other shared objects.
236 case TSK_ExplicitInstantiationDefinition:
237 case TSK_ExplicitInstantiationDeclaration:
238 return;
239
John McCall7a536902010-08-05 20:39:18 +0000240 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000241 case TSK_Undeclared:
242 break;
243
John McCall7a536902010-08-05 20:39:18 +0000244 // In theory, implicit instantiations can ignore the possibility of
245 // an explicit instantiation declaration because there necessarily
246 // must be an EI definition somewhere with default visibility. In
247 // practice, it's possible to have an explicit instantiation for
248 // an arbitrary template class, and linkers aren't necessarily able
249 // to deal with mixed-visibility symbols.
250 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000251 case TSK_ImplicitInstantiation:
John McCall279b5eb2010-08-12 23:36:15 +0000252 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall7a536902010-08-05 20:39:18 +0000253 return;
John McCallcbfe5022010-08-04 08:34:44 +0000254 break;
255 }
256
257 // If there's a key function, there may be translation units
258 // that don't have the key function's definition. But ignore
259 // this if we're emitting RTTI under -fno-rtti.
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000260 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000261 if (Context.getKeyFunction(RD))
262 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000263 }
John McCallcbfe5022010-08-04 08:34:44 +0000264
265 // Otherwise, drop the visibility to hidden.
266 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000267 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000268}
269
Anders Carlsson793a9902010-06-22 16:05:32 +0000270llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
271 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
272
273 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
274 if (!Str.empty())
275 return Str;
276
John McCall4c40d982010-08-31 07:33:07 +0000277 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000278 IdentifierInfo *II = ND->getIdentifier();
279 assert(II && "Attempt to mangle unnamed decl.");
280
281 Str = II->getName();
282 return Str;
283 }
284
285 llvm::SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000286 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000287 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000288 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000289 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000290 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000291 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000292 getCXXABI().getMangleContext().mangleBlock(BD, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000293 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000294 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000295
296 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000297 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000298 size_t Length = Buffer.size();
299 char *Name = MangledNamesAllocator.Allocate<char>(Length);
300 std::copy(Buffer.begin(), Buffer.end(), Name);
301
302 Str = llvm::StringRef(Name, Length);
303
304 return Str;
305}
306
Peter Collingbourne14110472011-01-13 18:57:25 +0000307void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
308 const BlockDecl *BD) {
309 MangleContext &MangleCtx = getCXXABI().getMangleContext();
310 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000311 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000312 if (D == 0)
Rafael Espindolac4850c22011-02-10 23:59:36 +0000313 MangleCtx.mangleGlobalBlock(BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000314 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000315 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000316 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000317 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000318 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000319 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000320}
321
John McCallf746aa62010-03-19 23:29:14 +0000322llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
323 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000324}
325
Chris Lattner6d397602008-03-14 17:18:18 +0000326/// AddGlobalCtor - Add a function to the list that will be called before
327/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000328void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000329 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000330 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000331}
332
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000333/// AddGlobalDtor - Add a function to the list that will be called
334/// when the module is unloaded.
335void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000336 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000337 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
338}
339
340void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
341 // Ctor function type is void()*.
342 llvm::FunctionType* CtorFTy =
Benjamin Kramer15f67652011-01-22 12:15:57 +0000343 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000344 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000345
346 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump1eb44332009-09-09 15:08:12 +0000347 llvm::StructType* CtorStructTy =
348 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson96e0fc72009-07-29 22:16:19 +0000349 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000350
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000351 // Construct the constructor and destructor arrays.
352 std::vector<llvm::Constant*> Ctors;
353 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
354 std::vector<llvm::Constant*> S;
Mike Stump1eb44332009-09-09 15:08:12 +0000355 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson0032b272009-08-13 21:57:51 +0000356 I->second, false));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000357 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson08e25242009-07-27 22:29:56 +0000358 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000359 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000360
361 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000362 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000363 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000364 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000365 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000366 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000367 }
Chris Lattner6d397602008-03-14 17:18:18 +0000368}
369
Nate Begeman532485c2008-04-18 23:43:57 +0000370void CodeGenModule::EmitAnnotations() {
371 if (Annotations.empty())
372 return;
373
374 // Create a new global variable for the ConstantStruct in the Module.
375 llvm::Constant *Array =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000376 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman532485c2008-04-18 23:43:57 +0000377 Annotations.size()),
378 Annotations);
Mike Stump1eb44332009-09-09 15:08:12 +0000379 llvm::GlobalValue *gv =
380 new llvm::GlobalVariable(TheModule, Array->getType(), false,
381 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000382 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000383 gv->setSection("llvm.metadata");
384}
385
John McCalld46f9852010-02-19 01:32:20 +0000386llvm::GlobalValue::LinkageTypes
387CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000388 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000389
Chris Lattnerf81530652010-06-30 16:58:07 +0000390 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000391 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000392
393 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000394 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000395
396 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000397 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000398
399 // In C99 mode, 'inline' functions are guaranteed to have a strong
400 // definition somewhere else, so we can use available_externally linkage.
401 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000402 return llvm::Function::AvailableExternallyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000403
404 // In C++, the compiler has to emit a definition in every translation unit
405 // that references the function. We should use linkonce_odr because
406 // a) if all references in this translation unit are optimized away, we
407 // don't need to codegen it. b) if the function persists, it needs to be
408 // merged with other definitions. c) C++ has the ODR, so we know the
409 // definition is dependable.
410 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000411 return !Context.getLangOptions().AppleKext
412 ? llvm::Function::LinkOnceODRLinkage
413 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000414
415 // An explicit instantiation of a template has weak linkage, since
416 // explicit instantiations can occur in multiple translation units
417 // and must all be equivalent. However, we are not allowed to
418 // throw away these explicit instantiations.
419 if (Linkage == GVA_ExplicitTemplateInstantiation)
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000420 return !Context.getLangOptions().AppleKext
421 ? llvm::Function::WeakODRLinkage
422 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000423
424 // Otherwise, we have strong external linkage.
425 assert(Linkage == GVA_StrongExternal);
426 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000427}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000428
John McCalld46f9852010-02-19 01:32:20 +0000429
430/// SetFunctionDefinitionAttributes - Set attributes for a global.
431///
432/// FIXME: This is currently only done for aliases and functions, but not for
433/// variables (these details are set in EmitGlobalVarDefinition for variables).
434void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
435 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000436 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000437}
438
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000439void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000440 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000441 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000442 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000443 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000444 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel761d7f72008-09-25 21:02:23 +0000445 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000446 AttributeList.size()));
447 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000448}
449
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000450void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
451 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000452 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump1eb44332009-09-09 15:08:12 +0000453 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000454
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000455 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000456 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000458 if (D->hasAttr<NakedAttr>())
459 F->addFnAttr(llvm::Attribute::Naked);
460
Mike Stump1feade82009-08-26 22:31:08 +0000461 if (D->hasAttr<NoInlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000462 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000463
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000464 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
465 F->setUnnamedAddr(true);
466
Anders Carlssonfd015352009-11-16 16:56:03 +0000467 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
468 F->addFnAttr(llvm::Attribute::StackProtect);
469 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
470 F->addFnAttr(llvm::Attribute::StackProtectReq);
471
Sean Huntcf807c42010-08-18 23:23:40 +0000472 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
473 if (alignment)
474 F->setAlignment(alignment);
475
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000476 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000477 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
478 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000479}
480
Mike Stump1eb44332009-09-09 15:08:12 +0000481void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000482 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000483 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
484 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000485 else
486 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000487
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000488 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000489 AddUsedGlobal(GV);
490
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000491 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000492 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000493
494 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000495}
496
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000497void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
498 llvm::Function *F,
499 const CGFunctionInfo &FI) {
500 SetLLVMFunctionAttributes(D, FI, F);
501 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000502
503 F->setLinkage(llvm::Function::InternalLinkage);
504
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000505 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000506}
507
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000508void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000509 llvm::Function *F,
510 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000511 if (unsigned IID = F->getIntrinsicID()) {
512 // If this is an intrinsic function, set the function's attributes
513 // to the intrinsic's attributes.
514 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
515 return;
516 }
517
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000518 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
519
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000520 if (!IsIncompleteFunction)
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000521 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000523 // Only a few attributes are set on declarations; these may later be
524 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000526 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000527 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000528 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000529 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000530 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000531 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000532 F->setLinkage(llvm::Function::ExternalWeakLinkage);
533 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000534 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000535
536 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
537 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
538 F->setVisibility(GetLLVMVisibility(LV.visibility()));
539 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000540 }
541
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000542 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000543 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000544}
545
Daniel Dunbar02698712009-02-13 20:29:50 +0000546void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000547 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000548 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000549 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000550}
551
552void CodeGenModule::EmitLLVMUsed() {
553 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000554 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000555 return;
556
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000557 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner35f38a22009-03-31 22:37:52 +0000559 // Convert LLVMUsed to what ConstantArray needs.
560 std::vector<llvm::Constant*> UsedArray;
561 UsedArray.resize(LLVMUsed.size());
562 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000563 UsedArray[i] =
564 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Andersona1cf15f2009-07-14 23:10:40 +0000565 i8PTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000568 if (UsedArray.empty())
569 return;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000570 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000571
572 llvm::GlobalVariable *GV =
573 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000574 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000575 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000576 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000577
578 GV->setSection("llvm.metadata");
579}
580
581void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000582 // Emit code for any potentially referenced deferred decls. Since a
583 // previously unused static decl may become used during the generation of code
584 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000585
Anders Carlsson046c2942010-04-17 20:15:18 +0000586 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
587 if (!DeferredVTables.empty()) {
588 const CXXRecordDecl *RD = DeferredVTables.back();
589 DeferredVTables.pop_back();
590 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000591 continue;
592 }
593
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000594 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000595 DeferredDeclsToEmit.pop_back();
596
John McCallc76702c2010-05-27 01:45:30 +0000597 // Check to see if we've already emitted this. This is necessary
598 // for a couple of reasons: first, decls can end up in the
599 // deferred-decls queue multiple times, and second, decls can end
600 // up with definitions in unusual ways (e.g. by an extern inline
601 // function acquiring a strong function redefinition). Just
602 // ignore these cases.
603 //
604 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000605 llvm::StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000606 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000607 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Chris Lattner67b00522009-03-21 09:44:56 +0000609 if (!CGRef->isDeclaration())
610 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
John McCallc76702c2010-05-27 01:45:30 +0000612 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
613 // purposes an alias counts as a definition.
614 if (isa<llvm::GlobalAlias>(CGRef))
615 continue;
616
Chris Lattner67b00522009-03-21 09:44:56 +0000617 // Otherwise, emit the definition and move on to the next one.
618 EmitGlobalDefinition(D);
619 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000620}
621
Mike Stump1eb44332009-09-09 15:08:12 +0000622/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000623/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump1eb44332009-09-09 15:08:12 +0000624/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
625/// GlobalValue being annotated. The second field is the constant string
626/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000627/// string containing the name of the translation unit. The fourth field is
628/// the line number in the file of the annotated value declaration.
629///
630/// FIXME: this does not unique the annotation string constants, as llvm-gcc
631/// appears to.
632///
Mike Stump1eb44332009-09-09 15:08:12 +0000633llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000634 const AnnotateAttr *AA,
635 unsigned LineNo) {
636 llvm::Module *M = &getModule();
637
638 // get [N x i8] constants for the annotation string, and the filename string
639 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000640 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump1eb44332009-09-09 15:08:12 +0000641 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson0032b272009-08-13 21:57:51 +0000642 AA->getAnnotation(), true);
643 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
644 M->getModuleIdentifier(),
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000645 true);
646
647 // Get the two global values corresponding to the ConstantArrays we just
648 // created to hold the bytes of the strings.
Mike Stump1eb44332009-09-09 15:08:12 +0000649 llvm::GlobalValue *annoGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000650 new llvm::GlobalVariable(*M, anno->getType(), false,
651 llvm::GlobalValue::PrivateLinkage, anno,
652 GV->getName());
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000653 // translation unit name string, emitted into the llvm.metadata section.
654 llvm::GlobalValue *unitGV =
Chris Lattner95b851e2009-07-16 05:03:48 +0000655 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump1eb44332009-09-09 15:08:12 +0000656 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner95b851e2009-07-16 05:03:48 +0000657 ".str");
Rafael Espindolad3d4e1e2011-01-17 22:22:52 +0000658 unitGV->setUnnamedAddr(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000659
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000660 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000661 llvm::Constant *Fields[4] = {
Owen Anderson3c4972d2009-07-29 18:54:39 +0000662 llvm::ConstantExpr::getBitCast(GV, SBP),
663 llvm::ConstantExpr::getBitCast(annoGV, SBP),
664 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson0032b272009-08-13 21:57:51 +0000665 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000666 };
Owen Anderson47a434f2009-08-05 23:18:46 +0000667 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000668}
669
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000670bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000671 // Never defer when EmitAllDecls is specified.
672 if (Features.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000673 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000674
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000675 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000676}
677
Rafael Espindola6a836702010-03-04 18:17:24 +0000678llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
679 const AliasAttr *AA = VD->getAttr<AliasAttr>();
680 assert(AA && "No alias?");
681
682 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
683
Rafael Espindola6a836702010-03-04 18:17:24 +0000684 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000685 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola6a836702010-03-04 18:17:24 +0000686
687 llvm::Constant *Aliasee;
688 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000689 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
690 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +0000691 else
John McCallf746aa62010-03-19 23:29:14 +0000692 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000693 llvm::PointerType::getUnqual(DeclTy), 0);
694 if (!Entry) {
695 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
696 F->setLinkage(llvm::Function::ExternalWeakLinkage);
697 WeakRefReferences.insert(F);
698 }
699
700 return Aliasee;
701}
702
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000703void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000704 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Rafael Espindola6a836702010-03-04 18:17:24 +0000706 // Weak references don't produce any output by themselves.
707 if (Global->hasAttr<WeakRefAttr>())
708 return;
709
Chris Lattnerbd532712009-03-22 21:47:11 +0000710 // If this is an alias definition (which otherwise looks like a declaration)
711 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000712 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000713 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000714
Chris Lattner67b00522009-03-21 09:44:56 +0000715 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000716 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000717 if (FD->getIdentifier()) {
718 llvm::StringRef Name = FD->getName();
719 if (Name == "_Block_object_assign") {
720 BlockObjectAssignDecl = FD;
721 } else if (Name == "_Block_object_dispose") {
722 BlockObjectDisposeDecl = FD;
723 }
724 }
725
Daniel Dunbar73241df2009-02-13 21:18:01 +0000726 // Forward declarations are emitted lazily on first use.
727 if (!FD->isThisDeclarationADefinition())
728 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000729 } else {
730 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000731 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
732
Daniel Dunbar754b9fb2010-07-16 00:00:19 +0000733 if (VD->getIdentifier()) {
734 llvm::StringRef Name = VD->getName();
735 if (Name == "_NSConcreteGlobalBlock") {
736 NSConcreteGlobalBlockDecl = VD;
737 } else if (Name == "_NSConcreteStackBlock") {
738 NSConcreteStackBlockDecl = VD;
739 }
740 }
741
742
Douglas Gregora9a55c02010-02-06 05:15:45 +0000743 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000744 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000745 }
746
Chris Lattner67b00522009-03-21 09:44:56 +0000747 // Defer code generation when possible if this is a static definition, inline
748 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000749 if (!MayDeferGeneration(Global)) {
750 // Emit the definition if it can't be deferred.
751 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000752 return;
753 }
John McCallbf40cb52010-07-15 23:40:35 +0000754
755 // If we're deferring emission of a C++ variable with an
756 // initializer, remember the order in which it appeared in the file.
757 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
758 cast<VarDecl>(Global)->hasInit()) {
759 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
760 CXXGlobalInits.push_back(0);
761 }
Chris Lattner4357a822010-04-13 17:39:09 +0000762
763 // If the value has already been used, add it directly to the
764 // DeferredDeclsToEmit list.
Anders Carlsson9a20d552010-06-22 16:16:50 +0000765 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000766 if (GetGlobalValue(MangledName))
767 DeferredDeclsToEmit.push_back(GD);
768 else {
769 // Otherwise, remember that we saw a deferred decl with this name. The
770 // first use of the mangled name will cause it to move into
771 // DeferredDeclsToEmit.
772 DeferredDecls[MangledName] = GD;
773 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000774}
775
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000776void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000777 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Dan Gohmancb421fa2010-04-19 16:39:44 +0000779 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +0000780 Context.getSourceManager(),
781 "Generating code for declaration");
782
Douglas Gregor44eac332010-07-13 06:02:28 +0000783 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
784 // At -O0, don't generate IR for functions with available_externally
785 // linkage.
Douglas Gregor7feaeee2010-07-15 22:58:18 +0000786 if (CodeGenOpts.OptimizationLevel == 0 &&
787 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregor44eac332010-07-13 06:02:28 +0000788 getFunctionLinkage(Function)
789 == llvm::Function::AvailableExternallyLinkage)
790 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +0000791
Douglas Gregor44eac332010-07-13 06:02:28 +0000792 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
793 if (Method->isVirtual())
794 getVTables().EmitThunks(GD);
795
796 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
797 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner4357a822010-04-13 17:39:09 +0000798
Douglas Gregor44eac332010-07-13 06:02:28 +0000799 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
800 return EmitCXXDestructor(DD, GD.getDtorType());
801 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000802
Chris Lattnerb5e81562010-04-13 17:57:11 +0000803 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +0000804 }
Chris Lattnerb5e81562010-04-13 17:57:11 +0000805
806 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
807 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +0000808
809 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000810}
811
Chris Lattner74391b42009-03-22 21:03:39 +0000812/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
813/// module, create and return an llvm Function with the specified type. If there
814/// is something in the module with the specified name, return it potentially
815/// bitcasted to the right type.
816///
817/// If D is non-null, it specifies a decl that correspond to this. This is used
818/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000819llvm::Constant *
820CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
821 const llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000822 GlobalDecl D, bool ForVTable) {
Chris Lattner0558e792009-03-21 09:25:43 +0000823 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000824 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +0000825 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000826 if (WeakRefReferences.count(Entry)) {
827 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
828 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000829 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000830
831 WeakRefReferences.erase(Entry);
832 }
833
Chris Lattner0558e792009-03-21 09:25:43 +0000834 if (Entry->getType()->getElementType() == Ty)
835 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Chris Lattner0558e792009-03-21 09:25:43 +0000837 // Make sure the result is of the correct type.
Owen Anderson96e0fc72009-07-29 22:16:19 +0000838 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000839 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000840 }
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Eli Friedman654ad402009-11-09 05:07:37 +0000842 // This function doesn't have a complete type (for example, the return
843 // type is an incomplete struct). Use a fake type instead, and make
844 // sure not to try to set attributes.
845 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +0000846
847 const llvm::FunctionType *FTy;
848 if (isa<llvm::FunctionType>(Ty)) {
849 FTy = cast<llvm::FunctionType>(Ty);
850 } else {
Benjamin Kramer15f67652011-01-22 12:15:57 +0000851 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Eli Friedman654ad402009-11-09 05:07:37 +0000852 IsIncompleteFunction = true;
853 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000854
John McCall784f2112010-04-28 00:00:30 +0000855 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +0000856 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000857 MangledName, &getModule());
858 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +0000859 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000860 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedman654ad402009-11-09 05:07:37 +0000861
Chris Lattner67b00522009-03-21 09:44:56 +0000862 // This is the first use or definition of a mangled name. If there is a
863 // deferred decl with this name, remember that we need to emit it at the end
864 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000865 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000866 if (DDI != DeferredDecls.end()) {
867 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
868 // list, and remove it from DeferredDecls (since we don't need it anymore).
869 DeferredDeclsToEmit.push_back(DDI->second);
870 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +0000871
872 // Otherwise, there are cases we have to worry about where we're
873 // using a declaration for which we must emit a definition but where
874 // we might not find a top-level definition:
875 // - member functions defined inline in their classes
876 // - friend functions defined inline in some class
877 // - special member functions with implicit definitions
878 // If we ever change our AST traversal to walk into class methods,
879 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000880 //
881 // We also don't emit a definition for a function if it's going to be an entry
882 // in a vtable, unless it's already marked as used.
Rafael Espindola01de7a42011-02-03 06:30:58 +0000883 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +0000884 // Look for a declaration that's lexically in a record.
885 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
886 do {
887 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000888 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +0000889 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +0000890 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000891 break;
892 } else if (FD->isThisDeclarationADefinition()) {
Douglas Gregora29bf412011-02-09 02:03:05 +0000893 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +0000894 break;
895 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000896 }
John McCallbfdcdc82010-12-15 04:00:32 +0000897 FD = FD->getPreviousDeclaration();
898 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +0000899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
John McCall784f2112010-04-28 00:00:30 +0000901 // Make sure the result is of the requested type.
902 if (!IsIncompleteFunction) {
903 assert(F->getType()->getElementType() == Ty);
904 return F;
905 }
906
907 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
908 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +0000909}
910
Chris Lattner74391b42009-03-22 21:03:39 +0000911/// GetAddrOfFunction - Return the address of the given function. If Ty is
912/// non-null, then this function will use the specified type if it has to
913/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000914llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000915 const llvm::Type *Ty,
916 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +0000917 // If there was no specific requested type, just convert it now.
918 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000919 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +0000920
Anders Carlsson9a20d552010-06-22 16:16:50 +0000921 llvm::StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000922 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +0000923}
Eli Friedman77ba7082008-05-30 19:50:47 +0000924
Chris Lattner74391b42009-03-22 21:03:39 +0000925/// CreateRuntimeFunction - Create a new runtime function with the specified
926/// type and name.
927llvm::Constant *
928CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCallf746aa62010-03-19 23:29:14 +0000929 llvm::StringRef Name) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000930 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
Chris Lattner74391b42009-03-22 21:03:39 +0000931}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000932
Eli Friedman20e098b2009-12-11 21:23:03 +0000933static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall88786862010-02-08 21:46:50 +0000934 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +0000935 return false;
936 if (Context.getLangOptions().CPlusPlus &&
937 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
938 // FIXME: We should do something fancier here!
939 return false;
940 }
941 return true;
942}
943
Chris Lattner74391b42009-03-22 21:03:39 +0000944/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
945/// create and return an llvm GlobalVariable with the specified type. If there
946/// is something in the module with the specified name, return it potentially
947/// bitcasted to the right type.
948///
949/// If D is non-null, it specifies a decl that correspond to this. This is used
950/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +0000951llvm::Constant *
952CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
953 const llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +0000954 const VarDecl *D,
955 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000956 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +0000957 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000958 if (Entry) {
Rafael Espindola6a836702010-03-04 18:17:24 +0000959 if (WeakRefReferences.count(Entry)) {
960 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +0000961 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +0000962
963 WeakRefReferences.erase(Entry);
964 }
965
Rafael Espindolac532b502011-01-18 21:07:57 +0000966 if (UnnamedAddr)
967 Entry->setUnnamedAddr(true);
968
Chris Lattner74391b42009-03-22 21:03:39 +0000969 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000970 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Chris Lattner99b53612009-03-21 08:03:33 +0000972 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +0000973 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000974 }
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Chris Lattner67b00522009-03-21 09:44:56 +0000976 // This is the first use or definition of a mangled name. If there is a
977 // deferred decl with this name, remember that we need to emit it at the end
978 // of the file.
John McCallf746aa62010-03-19 23:29:14 +0000979 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000980 if (DDI != DeferredDecls.end()) {
981 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
982 // list, and remove it from DeferredDecls (since we don't need it anymore).
983 DeferredDeclsToEmit.push_back(DDI->second);
984 DeferredDecls.erase(DDI);
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
987 llvm::GlobalVariable *GV =
988 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000989 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +0000990 0, MangledName, 0,
Eli Friedman56ebe502009-04-19 21:05:03 +0000991 false, Ty->getAddressSpace());
Chris Lattner99b53612009-03-21 08:03:33 +0000992
993 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000994 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000995 // FIXME: This code is overly simple and should be merged with other global
996 // handling.
Eli Friedman20e098b2009-12-11 21:23:03 +0000997 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner99b53612009-03-21 08:03:33 +0000998
John McCall110e8e52010-10-29 22:22:43 +0000999 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001000 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1001 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001002 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001003 } else {
1004 if (D->hasAttr<DLLImportAttr>())
1005 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001006 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001007 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001008
John McCallaf146032010-10-30 11:50:40 +00001009 // Set visibility on a declaration only if it's explicit.
1010 if (LV.visibilityExplicit())
1011 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001012 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001013
1014 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +00001015 }
Mike Stump1eb44332009-09-09 15:08:12 +00001016
John McCallf746aa62010-03-19 23:29:14 +00001017 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001018}
1019
Chris Lattner74391b42009-03-22 21:03:39 +00001020
Anders Carlsson3bd62022011-01-29 18:20:20 +00001021llvm::GlobalVariable *
1022CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1023 const llvm::Type *Ty,
1024 llvm::GlobalValue::LinkageTypes Linkage) {
1025 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1026 llvm::GlobalVariable *OldGV = 0;
1027
1028
1029 if (GV) {
1030 // Check if the variable has the right type.
1031 if (GV->getType()->getElementType() == Ty)
1032 return GV;
1033
1034 // Because C++ name mangling, the only way we can end up with an already
1035 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson96eaf292011-01-29 18:25:07 +00001036 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001037 OldGV = GV;
1038 }
1039
1040 // Create a new variable.
1041 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1042 Linkage, 0, Name);
1043
1044 if (OldGV) {
1045 // Replace occurrences of the old variable if needed.
1046 GV->takeName(OldGV);
1047
1048 if (!OldGV->use_empty()) {
1049 llvm::Constant *NewPtrForOldDecl =
1050 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1051 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1052 }
1053
1054 OldGV->eraseFromParent();
1055 }
1056
1057 return GV;
1058}
1059
Chris Lattner74391b42009-03-22 21:03:39 +00001060/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1061/// given global variable. If Ty is non-null and if the global doesn't exist,
1062/// then it will be greated with the specified type instead of whatever the
1063/// normal requested type would be.
1064llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1065 const llvm::Type *Ty) {
1066 assert(D->hasGlobalStorage() && "Not a global variable");
1067 QualType ASTTy = D->getType();
1068 if (Ty == 0)
1069 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
1071 const llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001072 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001073
Anders Carlsson9a20d552010-06-22 16:16:50 +00001074 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001075 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001076}
1077
1078/// CreateRuntimeVariable - Create a new runtime global variable with the
1079/// specified type and name.
1080llvm::Constant *
1081CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCallf746aa62010-03-19 23:29:14 +00001082 llvm::StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001083 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001084 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001085}
1086
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001087void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1088 assert(!D->getInit() && "Cannot emit definite definitions here!");
1089
Douglas Gregor7520bd12009-04-21 19:28:58 +00001090 if (MayDeferGeneration(D)) {
1091 // If we have not seen a reference to this variable yet, place it
1092 // into the deferred declarations table to be emitted if needed
1093 // later.
Anders Carlsson9a20d552010-06-22 16:16:50 +00001094 llvm::StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001095 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001096 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001097 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001098 }
1099 }
1100
1101 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001102 EmitGlobalVarDefinition(D);
1103}
1104
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001105void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1106 if (DefinitionRequired)
1107 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1108}
1109
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001110llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001111CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregordffb8012010-01-06 22:00:56 +00001112 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1113 return llvm::GlobalVariable::InternalLinkage;
1114
1115 if (const CXXMethodDecl *KeyFunction
1116 = RD->getASTContext().getKeyFunction(RD)) {
1117 // If this class has a key function, use that to determine the linkage of
1118 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001119 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001120 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001121 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001122
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001123 switch (KeyFunction->getTemplateSpecializationKind()) {
1124 case TSK_Undeclared:
1125 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001126 // When compiling with optimizations turned on, we emit all vtables,
1127 // even if the key function is not defined in the current translation
1128 // unit. If this is the case, use available_externally linkage.
1129 if (!Def && CodeGenOpts.OptimizationLevel)
1130 return llvm::GlobalVariable::AvailableExternallyLinkage;
1131
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001132 if (KeyFunction->isInlined())
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001133 return !Context.getLangOptions().AppleKext ?
1134 llvm::GlobalVariable::LinkOnceODRLinkage :
1135 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001136
1137 return llvm::GlobalVariable::ExternalLinkage;
1138
1139 case TSK_ImplicitInstantiation:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001140 return !Context.getLangOptions().AppleKext ?
1141 llvm::GlobalVariable::LinkOnceODRLinkage :
1142 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001143
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001144 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001145 return !Context.getLangOptions().AppleKext ?
1146 llvm::GlobalVariable::WeakODRLinkage :
1147 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001148
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001149 case TSK_ExplicitInstantiationDeclaration:
1150 // FIXME: Use available_externally linkage. However, this currently
1151 // breaks LLVM's build due to undefined symbols.
1152 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001153 return !Context.getLangOptions().AppleKext ?
1154 llvm::GlobalVariable::LinkOnceODRLinkage :
1155 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001156 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001157 }
1158
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001159 if (Context.getLangOptions().AppleKext)
1160 return llvm::Function::InternalLinkage;
1161
Douglas Gregordffb8012010-01-06 22:00:56 +00001162 switch (RD->getTemplateSpecializationKind()) {
1163 case TSK_Undeclared:
1164 case TSK_ExplicitSpecialization:
1165 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001166 // FIXME: Use available_externally linkage. However, this currently
1167 // breaks LLVM's build due to undefined symbols.
1168 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001169 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001170 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001171
1172 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001173 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001174 }
1175
1176 // Silence GCC warning.
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001177 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001178}
1179
Ken Dyck687cc4a2010-01-26 13:48:07 +00001180CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001181 return Context.toCharUnitsFromBits(
1182 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001183}
1184
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001185void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001186 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001187 QualType ASTTy = D->getType();
Eli Friedman6c6bda32010-01-08 00:50:11 +00001188 bool NonConstInit = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Sebastian Redl31310a22010-02-01 20:16:42 +00001190 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlsson3bb92692010-01-26 17:43:42 +00001191
1192 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001193 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001194 // implicitly initialized with { 0 }.
1195 //
1196 // Note that tentative definitions are only emitted at the end of
1197 // a translation unit, so they should never have incomplete
1198 // type. In addition, EmitTentativeDefinition makes sure that we
1199 // never attempt to emit a tentative definition if a real one
1200 // exists. A use may still exists, however, so we still may need
1201 // to do a RAUW.
1202 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001203 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001204 } else {
Douglas Gregorc446d182010-05-05 20:15:55 +00001205 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +00001206 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001207 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001208 if (D->getType()->isReferenceType())
1209 T = D->getType();
1210
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001211 if (getLangOptions().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001212 Init = EmitNullConstant(T);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001213 NonConstInit = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001214 } else {
1215 ErrorUnsupported(D, "static initializer");
1216 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1217 }
John McCallbf40cb52010-07-15 23:40:35 +00001218 } else {
1219 // We don't need an initializer, so remove the entry for the delayed
1220 // initializer position (just in case this entry was delayed).
1221 if (getLangOptions().CPlusPlus)
1222 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001223 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001224 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001225
Chris Lattner2d584062009-03-21 08:13:05 +00001226 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001227 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Chris Lattner570585c2009-03-21 09:16:30 +00001229 // Strip off a bitcast if we got one back.
1230 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001231 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1232 // all zero index gep.
1233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001234 Entry = CE->getOperand(0);
1235 }
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Chris Lattner570585c2009-03-21 09:16:30 +00001237 // Entry is now either a Function or GlobalVariable.
1238 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Chris Lattner570585c2009-03-21 09:16:30 +00001240 // We have a definition after a declaration with the wrong type.
1241 // We must make a new GlobalVariable* and update everything that used OldGV
1242 // (a declaration or tentative definition) with the new GlobalVariable*
1243 // (which will be a definition).
1244 //
1245 // This happens if there is a prototype for a global (e.g.
1246 // "extern int x[];") and then a definition of a different type (e.g.
1247 // "int x[10];"). This also happens when an initializer has a different type
1248 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001249 if (GV == 0 ||
1250 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001251 GV->getType()->getAddressSpace() !=
1252 getContext().getTargetAddressSpace(ASTTy)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001253
John McCallf746aa62010-03-19 23:29:14 +00001254 // Move the old entry aside so that we'll create a new one.
1255 Entry->setName(llvm::StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001256
Chris Lattner570585c2009-03-21 09:16:30 +00001257 // Make a new global with the correct type, this is now guaranteed to work.
1258 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001259
Eli Friedman77ba7082008-05-30 19:50:47 +00001260 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001261 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001262 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001263 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001264
1265 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001266 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001267 }
Devang Patel8e53e722007-10-26 16:31:40 +00001268
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001269 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001270 SourceManager &SM = Context.getSourceManager();
1271 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +00001272 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001273 }
1274
Chris Lattner88a69ad2007-07-13 05:13:43 +00001275 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001276
1277 // If it is safe to mark the global 'constant', do so now.
1278 GV->setConstant(false);
Eli Friedman6c6bda32010-01-08 00:50:11 +00001279 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnere78b86f2009-08-05 05:20:29 +00001280 GV->setConstant(true);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Ken Dyck8b752f12010-01-27 17:10:57 +00001282 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001283
Chris Lattner88a69ad2007-07-13 05:13:43 +00001284 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001285 llvm::GlobalValue::LinkageTypes Linkage =
1286 GetLLVMLinkageVarDefinition(D, GV);
1287 GV->setLinkage(Linkage);
1288 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001289 // common vars aren't constant even if declared const.
1290 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001291
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001292 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001293
John McCall3030eb82010-11-06 09:44:32 +00001294 // Emit the initializer function if necessary.
1295 if (NonConstInit)
1296 EmitCXXGlobalVarDeclInitFunc(D, GV);
1297
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001298 // Emit global variable debug information.
Devang Patelaa112892011-03-07 18:45:56 +00001299 if (CGDebugInfo *DI = getModuleDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +00001300 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001301 DI->EmitGlobalVariable(GV, D);
1302 }
Chris Lattner88a69ad2007-07-13 05:13:43 +00001303}
Reid Spencer5f016e22007-07-11 17:01:13 +00001304
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001305llvm::GlobalValue::LinkageTypes
1306CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1307 llvm::GlobalVariable *GV) {
1308 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1309 if (Linkage == GVA_Internal)
1310 return llvm::Function::InternalLinkage;
1311 else if (D->hasAttr<DLLImportAttr>())
1312 return llvm::Function::DLLImportLinkage;
1313 else if (D->hasAttr<DLLExportAttr>())
1314 return llvm::Function::DLLExportLinkage;
1315 else if (D->hasAttr<WeakAttr>()) {
1316 if (GV->isConstant())
1317 return llvm::GlobalVariable::WeakODRLinkage;
1318 else
1319 return llvm::GlobalVariable::WeakAnyLinkage;
1320 } else if (Linkage == GVA_TemplateInstantiation ||
1321 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001322 return llvm::GlobalVariable::WeakODRLinkage;
Eric Christophera6cf1e72010-12-02 02:45:55 +00001323 else if (!getLangOptions().CPlusPlus &&
1324 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1325 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001326 !D->hasExternalStorage() && !D->getInit() &&
1327 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1328 // Thread local vars aren't considered common linkage.
1329 return llvm::GlobalVariable::CommonLinkage;
1330 }
1331 return llvm::GlobalVariable::ExternalLinkage;
1332}
1333
Chris Lattnerbdb01322009-05-05 06:16:31 +00001334/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1335/// implement a function with no prototype, e.g. "int foo() {}". If there are
1336/// existing call uses of the old function in the module, this adjusts them to
1337/// call the new function directly.
1338///
1339/// This is not just a cleanup: the always_inline pass requires direct calls to
1340/// functions to be able to inline them. If there is a bitcast in the way, it
1341/// won't inline them. Instcombine normally deletes these calls, but it isn't
1342/// run at -O0.
1343static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1344 llvm::Function *NewFn) {
1345 // If we're redefining a global as a function, don't transform it.
1346 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1347 if (OldFn == 0) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Chris Lattnerbdb01322009-05-05 06:16:31 +00001349 const llvm::Type *NewRetTy = NewFn->getReturnType();
1350 llvm::SmallVector<llvm::Value*, 4> ArgList;
1351
1352 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001353 UI != E; ) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001354 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001355 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1356 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif8670cd32010-07-28 09:19:33 +00001357 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greif35db3b92010-04-10 03:45:50 +00001358 llvm::CallSite CS(CI);
Benjamin Kramerdbf02bc2010-04-10 11:02:40 +00001359 if (!CI || !CS.isCallee(I)) continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Chris Lattnerbdb01322009-05-05 06:16:31 +00001361 // If the return types don't match exactly, and if the call isn't dead, then
1362 // we can't transform this call.
1363 if (CI->getType() != NewRetTy && !CI->use_empty())
1364 continue;
1365
1366 // If the function was passed too few arguments, don't transform. If extra
1367 // arguments were passed, we silently drop them. If any of the types
1368 // mismatch, we don't transform.
1369 unsigned ArgNo = 0;
1370 bool DontTransform = false;
1371 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1372 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greif35db3b92010-04-10 03:45:50 +00001373 if (CS.arg_size() == ArgNo ||
1374 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001375 DontTransform = true;
1376 break;
1377 }
1378 }
1379 if (DontTransform)
1380 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Chris Lattnerbdb01322009-05-05 06:16:31 +00001382 // Okay, we can transform this. Create the new call instruction and copy
1383 // over the required information.
Gabor Greif6ba728d2010-04-10 02:56:12 +00001384 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001385 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1386 ArgList.end(), "", CI);
1387 ArgList.clear();
Benjamin Kramerffbb15e2009-10-05 13:47:21 +00001388 if (!NewCall->getType()->isVoidTy())
Chris Lattnerbdb01322009-05-05 06:16:31 +00001389 NewCall->takeName(CI);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001390 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbarca6408c2009-09-12 00:59:20 +00001391 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001392
1393 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner00549fc2009-10-14 05:49:21 +00001394 if (!CI->use_empty())
1395 CI->replaceAllUsesWith(NewCall);
Devang Patel3b122bc2009-10-13 17:02:04 +00001396
Chris Lattnerc6034632010-04-01 06:31:43 +00001397 // Copy debug location attached to CI.
1398 if (!CI->getDebugLoc().isUnknown())
1399 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001400 CI->eraseFromParent();
1401 }
1402}
1403
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001404
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001405void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001406 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001407
John McCall1f6f9612011-03-09 08:12:35 +00001408 // Compute the function info and LLVM type.
John McCalld26bc762011-03-09 04:27:21 +00001409 const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
John McCall1f6f9612011-03-09 08:12:35 +00001410 bool variadic = false;
1411 if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1412 variadic = fpt->isVariadic();
1413 const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
John McCalld26bc762011-03-09 04:27:21 +00001414
Chris Lattner9fa959d2009-05-12 20:58:15 +00001415 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001416 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Chris Lattner0558e792009-03-21 09:25:43 +00001418 // Strip off a bitcast if we got one back.
1419 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1420 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1421 Entry = CE->getOperand(0);
1422 }
Mike Stump1eb44332009-09-09 15:08:12 +00001423
1424
Chris Lattner0558e792009-03-21 09:25:43 +00001425 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001426 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Daniel Dunbar42745812009-03-09 23:53:08 +00001428 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001429 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001430 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001431
Chris Lattner62b33ea2009-03-21 08:38:50 +00001432 // F is the Function* for the one with the wrong type, we must make a new
1433 // Function* and update everything that used F (a declaration) with the new
1434 // Function* (which will be a definition).
1435 //
1436 // This happens if there is a prototype for a function
1437 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001438 // (e.g. "int f(int x)"). Move the old function aside so that it
1439 // doesn't interfere with GetAddrOfFunction.
1440 OldFn->setName(llvm::StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001441 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Chris Lattnerbdb01322009-05-05 06:16:31 +00001443 // If this is an implementation of a function without a prototype, try to
1444 // replace any existing uses of the function (which may be calls) with uses
1445 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001446 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001447 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001448 OldFn->removeDeadConstantUsers();
1449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Chris Lattner62b33ea2009-03-21 08:38:50 +00001451 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001452 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001453 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001454 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001455 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Chris Lattner62b33ea2009-03-21 08:38:50 +00001458 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001459 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Chris Lattner0558e792009-03-21 09:25:43 +00001461 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
John McCall112c9672010-11-02 21:04:24 +00001464 // We need to set linkage and visibility on the function before
1465 // generating code for it because various parts of IR generation
1466 // want to propagate this information down (e.g. to local static
1467 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001468 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001469 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001470
John McCall112c9672010-11-02 21:04:24 +00001471 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00001472 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00001473
John McCalld26bc762011-03-09 04:27:21 +00001474 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001475
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001476 SetFunctionDefinitionAttributes(D, Fn);
1477 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001479 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001480 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001481 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001482 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001483}
1484
John McCallf746aa62010-03-19 23:29:14 +00001485void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1486 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001487 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001488 assert(AA && "Not an alias?");
1489
Anders Carlsson9a20d552010-06-22 16:16:50 +00001490 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCallf746aa62010-03-19 23:29:14 +00001492 // If there is a definition in the module, then it wins over the alias.
1493 // This is dubious, but allow it to be safe. Just ignore the alias.
1494 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1495 if (Entry && !Entry->isDeclaration())
1496 return;
1497
1498 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00001499
1500 // Create a reference to the named value. This ensures that it is emitted
1501 // if a deferred decl.
1502 llvm::Constant *Aliasee;
1503 if (isa<llvm::FunctionType>(DeclTy))
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001504 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1505 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00001506 else
John McCallf746aa62010-03-19 23:29:14 +00001507 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00001508 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00001509
1510 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00001511 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00001512 new llvm::GlobalAlias(Aliasee->getType(),
1513 llvm::Function::ExternalLinkage,
1514 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Chris Lattnerbd532712009-03-22 21:47:11 +00001516 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00001517 assert(Entry->isDeclaration());
1518
Chris Lattnerbd532712009-03-22 21:47:11 +00001519 // If there is a declaration in the module, then we had an extern followed
1520 // by the alias, as in:
1521 // extern int test6();
1522 // ...
1523 // int test6() __attribute__((alias("test7")));
1524 //
1525 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00001526 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Owen Anderson3c4972d2009-07-29 18:54:39 +00001528 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00001529 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001530 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00001531 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00001532 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00001533 }
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001535 // Set attributes which are particular to an alias; this is a
1536 // specialization of the attributes which may be set on a global
1537 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001538 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001539 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1540 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001541 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001542 GA->setLinkage(llvm::Function::DLLExportLinkage);
1543 } else {
1544 GA->setLinkage(llvm::Function::DLLExportLinkage);
1545 }
Mike Stump1eb44332009-09-09 15:08:12 +00001546 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00001547 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001548 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001549 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1550 }
1551
1552 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001553}
1554
Chris Lattnerb808c952009-03-22 21:56:56 +00001555/// getBuiltinLibFunction - Given a builtin id for a function like
1556/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbar34771b52009-09-14 04:33:21 +00001557llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1558 unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001559 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001560 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +00001561 "isn't a lib fn");
Mike Stump1eb44332009-09-09 15:08:12 +00001562
Douglas Gregor3e41d602009-02-13 23:20:09 +00001563 // Get the name, skip over the __builtin_ prefix (if necessary).
1564 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1565 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1566 Name += 10;
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Mike Stump1eb44332009-09-09 15:08:12 +00001568 const llvm::FunctionType *Ty =
Eli Friedman386ca782009-12-09 03:05:59 +00001569 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001570
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001571 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001572}
1573
Chris Lattner7acda7c2007-12-18 00:25:38 +00001574llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1575 unsigned NumTys) {
1576 return llvm::Intrinsic::getDeclaration(&getModule(),
1577 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1578}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001579
Daniel Dunbar1d552912009-07-23 22:52:48 +00001580static llvm::StringMapEntry<llvm::Constant*> &
1581GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1582 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001583 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00001584 bool &IsUTF16,
1585 unsigned &StringLength) {
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001586 llvm::StringRef String = Literal->getString();
1587 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001588
Daniel Dunbarf015b032009-09-22 10:03:52 +00001589 // Check for simple case.
1590 if (!Literal->containsNonAsciiOrNull()) {
1591 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001592 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00001593 }
1594
Daniel Dunbar1d552912009-07-23 22:52:48 +00001595 // Otherwise, convert the UTF8 literals into a byte string.
1596 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001597 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00001598 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00001600 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1601 &ToPtr, ToPtr + NumBytes,
1602 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001604 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00001605 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001606
1607 // Render the UTF-16 string into a byte array and convert to the target byte
1608 // order.
1609 //
1610 // FIXME: This isn't something we should need to do here.
1611 llvm::SmallString<128> AsBytes;
1612 AsBytes.reserve(StringLength * 2);
1613 for (unsigned i = 0; i != StringLength; ++i) {
1614 unsigned short Val = ToBuf[i];
1615 if (TargetIsLSB) {
1616 AsBytes.push_back(Val & 0xFF);
1617 AsBytes.push_back(Val >> 8);
1618 } else {
1619 AsBytes.push_back(Val >> 8);
1620 AsBytes.push_back(Val & 0xFF);
1621 }
1622 }
Daniel Dunbar434da482009-08-03 21:47:08 +00001623 // Append one extra null character, the second is automatically added by our
1624 // caller.
1625 AsBytes.push_back(0);
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001626
Daniel Dunbar1d552912009-07-23 22:52:48 +00001627 IsUTF16 = true;
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001628 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar1d552912009-07-23 22:52:48 +00001629}
1630
1631llvm::Constant *
1632CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1633 unsigned StringLength = 0;
1634 bool isUTF16 = false;
1635 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00001636 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00001637 getTargetData().isLittleEndian(),
1638 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Daniel Dunbar1d552912009-07-23 22:52:48 +00001640 if (llvm::Constant *C = Entry.getValue())
1641 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Owen Anderson0032b272009-08-13 21:57:51 +00001643 llvm::Constant *Zero =
1644 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001645 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001647 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00001648 if (!CFConstantStringClassRef) {
1649 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001650 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001651 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001652 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001653 // Decay array -> ptr
1654 CFConstantStringClassRef =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001655 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Anders Carlssone3daa762008-11-15 18:54:24 +00001658 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001659
Mike Stump1eb44332009-09-09 15:08:12 +00001660 const llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00001661 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1662
Anders Carlsson5add6832009-08-16 05:55:31 +00001663 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor44b43212008-12-11 16:49:14 +00001664
Anders Carlssonc9e20912007-08-21 00:21:21 +00001665 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00001666 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Anders Carlssonc9e20912007-08-21 00:21:21 +00001668 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001669 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001670 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00001671 llvm::ConstantInt::get(Ty, 0x07C8);
1672
Anders Carlssonc9e20912007-08-21 00:21:21 +00001673 // String pointer.
Owen Anderson0032b272009-08-13 21:57:51 +00001674 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001675
Chris Lattner95b851e2009-07-16 05:03:48 +00001676 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001677 bool isConstant;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001678 if (isUTF16) {
Chris Lattner278b9f02009-10-14 05:55:45 +00001679 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00001680 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001681 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1682 // does make plain ascii ones writable.
Daniel Dunbara9668e02009-04-03 00:57:44 +00001683 isConstant = true;
Chris Lattner278b9f02009-10-14 05:55:45 +00001684 } else {
Rafael Espindola584acf22011-03-14 17:55:00 +00001685 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1686 // when using private linkage. It is not clear if this is a bug in ld
1687 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00001688 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00001689 isConstant = !Features.WritableStrings;
Daniel Dunbara9668e02009-04-03 00:57:44 +00001690 }
Chris Lattner278b9f02009-10-14 05:55:45 +00001691
Mike Stump1eb44332009-09-09 15:08:12 +00001692 llvm::GlobalVariable *GV =
Chris Lattner278b9f02009-10-14 05:55:45 +00001693 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1694 ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00001695 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001696 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00001697 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1698 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00001699 } else {
1700 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1701 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00001702 }
Anders Carlsson5add6832009-08-16 05:55:31 +00001703 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1704
Anders Carlssonc9e20912007-08-21 00:21:21 +00001705 // String length.
1706 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00001707 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Anders Carlssonc9e20912007-08-21 00:21:21 +00001709 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00001710 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00001711 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1712 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00001713 "_unnamed_cfstring_");
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001714 if (const char *Sect = getContext().Target.getCFStringSection())
1715 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00001716 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Anders Carlsson0c678292007-11-01 00:41:52 +00001718 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001719}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001720
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001721llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001722CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001723 unsigned StringLength = 0;
1724 bool isUTF16 = false;
1725 llvm::StringMapEntry<llvm::Constant*> &Entry =
1726 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1727 getTargetData().isLittleEndian(),
1728 isUTF16, StringLength);
1729
1730 if (llvm::Constant *C = Entry.getValue())
1731 return C;
1732
1733 llvm::Constant *Zero =
1734 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1735 llvm::Constant *Zeros[] = { Zero, Zero };
1736
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001737 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001738 if (!ConstantStringClassRef) {
1739 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001740 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1741 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001742 llvm::Constant *GV;
1743 if (StringClass.empty())
1744 GV = CreateRuntimeVariable(Ty,
1745 Features.ObjCNonFragileABI ?
1746 "OBJC_CLASS_$_NSConstantString" :
1747 "_NSConstantStringClassReference");
1748 else {
1749 std::string str;
1750 if (Features.ObjCNonFragileABI)
1751 str = "OBJC_CLASS_$_" + StringClass;
1752 else
1753 str = "_" + StringClass + "ClassReference";
1754 GV = CreateRuntimeVariable(Ty, str);
1755 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001756 // Decay array -> ptr
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001757 ConstantStringClassRef =
1758 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001759 }
1760
1761 QualType NSTy = getContext().getNSConstantStringType();
1762
1763 const llvm::StructType *STy =
1764 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1765
1766 std::vector<llvm::Constant*> Fields(3);
1767
1768 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00001769 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001770
1771 // String pointer.
1772 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1773
1774 llvm::GlobalValue::LinkageTypes Linkage;
1775 bool isConstant;
1776 if (isUTF16) {
1777 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1778 Linkage = llvm::GlobalValue::InternalLinkage;
1779 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1780 // does make plain ascii ones writable.
1781 isConstant = true;
1782 } else {
1783 Linkage = llvm::GlobalValue::PrivateLinkage;
1784 isConstant = !Features.WritableStrings;
1785 }
1786
1787 llvm::GlobalVariable *GV =
1788 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1789 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00001790 GV->setUnnamedAddr(true);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001791 if (isUTF16) {
1792 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1793 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00001794 } else {
1795 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1796 GV->setAlignment(Align.getQuantity());
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001797 }
1798 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1799
1800 // String length.
1801 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1802 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1803
1804 // The struct.
1805 C = llvm::ConstantStruct::get(STy, Fields);
1806 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1807 llvm::GlobalVariable::PrivateLinkage, C,
1808 "_unnamed_nsstring_");
1809 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00001810 if (const char *Sect =
1811 Features.ObjCNonFragileABI
1812 ? getContext().Target.getNSStringNonFragileABISection()
1813 : getContext().Target.getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00001814 GV->setSection(Sect);
1815 Entry.setValue(GV);
1816
1817 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00001818}
1819
Daniel Dunbar61432932008-08-13 23:20:05 +00001820/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001821/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001822std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dyck3b8037a2011-01-29 17:53:12 +00001823 const ASTContext &Context = getContext();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001824 const ConstantArrayType *CAT =
Ken Dyck3b8037a2011-01-29 17:53:12 +00001825 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar1e049762008-08-10 20:25:57 +00001826 assert(CAT && "String isn't pointer or array!");
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001828 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001829 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001831 if (E->isWide())
Ken Dyck3b8037a2011-01-29 17:53:12 +00001832 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001834 std::string Str = E->getString().str();
Daniel Dunbar1e049762008-08-10 20:25:57 +00001835 Str.resize(RealLen, '\0');
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Daniel Dunbar1e049762008-08-10 20:25:57 +00001837 return Str;
1838}
1839
Daniel Dunbar61432932008-08-13 23:20:05 +00001840/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1841/// constant array for the given string literal.
1842llvm::Constant *
1843CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1844 // FIXME: This can be more efficient.
Eli Friedman7eb79c12009-11-16 05:55:46 +00001845 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1846 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1847 if (S->isWide()) {
1848 llvm::Type *DestTy =
1849 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1850 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1851 }
1852 return C;
Daniel Dunbar61432932008-08-13 23:20:05 +00001853}
1854
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001855/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1856/// array for the given ObjCEncodeExpr node.
1857llvm::Constant *
1858CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1859 std::string Str;
1860 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001861
1862 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001863}
1864
1865
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001866/// GenerateWritableString -- Creates storage for a string literal.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001867static llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001868 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001869 CodeGenModule &CGM,
1870 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001871 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00001872 llvm::Constant *C =
1873 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001875 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00001876 llvm::GlobalVariable *GV =
1877 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1878 llvm::GlobalValue::PrivateLinkage,
1879 C, GlobalName);
1880 GV->setUnnamedAddr(true);
1881 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001882}
1883
Daniel Dunbar61432932008-08-13 23:20:05 +00001884/// GetAddrOfConstantString - Returns a pointer to a character array
1885/// containing the literal. This contents are exactly that of the
1886/// given string, i.e. it will not be null terminated automatically;
1887/// see GetAddrOfConstantCString. Note that whether the result is
1888/// actually a pointer to an LLVM constant depends on
1889/// Feature.WriteableStrings.
1890///
1891/// The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001892llvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001893 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001894 bool IsConstant = !Features.WritableStrings;
1895
1896 // Get the default prefix if a name wasn't specified.
1897 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00001898 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001899
1900 // Don't share any string literals if strings aren't constant.
1901 if (!IsConstant)
Benjamin Kramer9de43422011-03-05 13:45:23 +00001902 return GenerateStringLiteral(Str, false, *this, GlobalName);
Mike Stump1eb44332009-09-09 15:08:12 +00001903
1904 llvm::StringMapEntry<llvm::Constant *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00001905 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001906
1907 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001908 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001909
1910 // Create a global variable for this.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001911 llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001912 Entry.setValue(C);
1913 return C;
1914}
Daniel Dunbar61432932008-08-13 23:20:05 +00001915
1916/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00001917/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00001918/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00001919llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001920 const char *GlobalName){
Benjamin Kramer9de43422011-03-05 13:45:23 +00001921 llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1922 return GetAddrOfConstantString(StrWithNull, GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001923}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001924
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001925/// EmitObjCPropertyImplementations - Emit information for synthesized
1926/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00001927void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001928 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001929 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001930 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001931 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001933 // Dynamic is just for type-checking.
1934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1935 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1936
1937 // Determine which methods need to be implemented, some may have
1938 // been overridden. Note that ::isSynthesized is not the method
1939 // we want, that just indicates if the decl came from a
1940 // property. What we want to know is if the method is defined in
1941 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001942 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001943 CodeGenFunction(*this).GenerateObjCGetter(
1944 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001945 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001946 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001947 CodeGenFunction(*this).GenerateObjCSetter(
1948 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001949 }
1950 }
1951}
1952
John McCalle81ac692011-03-22 07:05:39 +00001953static bool needsDestructMethod(ObjCImplementationDecl *impl) {
1954 ObjCInterfaceDecl *iface
1955 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1956 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1957 ivar; ivar = ivar->getNextIvar())
1958 if (ivar->getType().isDestructedType())
1959 return true;
1960
1961 return false;
1962}
1963
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001964/// EmitObjCIvarInitializations - Emit information for ivar initialization
1965/// for an implementation.
1966void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00001967 // We might need a .cxx_destruct even if we don't have any ivar initializers.
1968 if (needsDestructMethod(D)) {
1969 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1970 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1971 ObjCMethodDecl *DTORMethod =
1972 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
1973 cxxSelector, getContext().VoidTy, 0, D, true,
1974 false, true, false, ObjCMethodDecl::Required);
1975 D->addInstanceMethod(DTORMethod);
1976 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1977 }
1978
1979 // If the implementation doesn't have any ivar initializers, we don't need
1980 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00001981 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001982 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001983
John McCalle81ac692011-03-22 07:05:39 +00001984 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
1985 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001986 // The constructor returns 'self'.
1987 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1988 D->getLocation(),
1989 D->getLocation(), cxxSelector,
1990 getContext().getObjCIdType(), 0,
John McCalle81ac692011-03-22 07:05:39 +00001991 D, true, false, true, false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001992 ObjCMethodDecl::Required);
1993 D->addInstanceMethod(CTORMethod);
1994 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001995}
1996
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001997/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001998void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001999 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002000 I != E; ++I)
2001 EmitTopLevelDecl(*I);
2002}
2003
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002004// EmitLinkageSpec - Emit all declarations in a linkage spec.
2005void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002006 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2007 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002008 ErrorUnsupported(LSD, "linkage spec");
2009 return;
2010 }
2011
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002012 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002013 I != E; ++I)
2014 EmitTopLevelDecl(*I);
2015}
2016
Daniel Dunbar41071de2008-08-15 23:26:23 +00002017/// EmitTopLevelDecl - Emit code for a single top level declaration.
2018void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2019 // If an error has occurred, stop code generation, but continue
2020 // parsing and semantic analysis (to ensure all warnings and errors
2021 // are emitted).
2022 if (Diags.hasErrorOccurred())
2023 return;
2024
Douglas Gregor16e8be22009-06-29 17:30:29 +00002025 // Ignore dependent declarations.
2026 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2027 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Daniel Dunbar41071de2008-08-15 23:26:23 +00002029 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002030 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002031 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002032 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002033 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002034 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2035 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002036 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002038 EmitGlobal(cast<FunctionDecl>(D));
2039 break;
2040
Daniel Dunbar41071de2008-08-15 23:26:23 +00002041 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002042 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002043 break;
2044
John McCall26fbc722011-04-12 01:01:22 +00002045 // Indirect fields from global anonymous structs and unions can be
2046 // ignored; only the actual variable requires IR gen support.
2047 case Decl::IndirectField:
2048 break;
2049
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002050 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002051 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002052 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002053 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002054 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002055 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002056 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002057 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002058 case Decl::ClassTemplate:
2059 case Decl::FunctionTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002060 case Decl::NamespaceAlias:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002061 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002062 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002063 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002064 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2065 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002066 return;
2067
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002068 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2069 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002070 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002071 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2072 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002073 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2074 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002075
2076 case Decl::StaticAssert:
2077 // Nothing to do.
2078 break;
2079
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002080 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002082 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002083 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002084 case Decl::ObjCForwardProtocol:
Chris Lattner285d0db2009-04-01 02:36:43 +00002085 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00002086 break;
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002087
Chris Lattnerbaf101d2011-04-09 07:11:53 +00002088 case Decl::ObjCCategory: {
2089 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2090 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2091 Context.ResetObjCLayout(CD->getClassInterface());
2092 break;
2093 }
Chris Lattner285d0db2009-04-01 02:36:43 +00002094
Daniel Dunbar41071de2008-08-15 23:26:23 +00002095 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00002096 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002097 break;
2098
2099 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002100 // Categories have properties but don't support synthesize so we
2101 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002102 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2103 break;
2104
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002105 case Decl::ObjCImplementation: {
2106 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanian000835d2010-08-23 18:51:39 +00002107 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2108 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002109 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002110 EmitObjCIvarInitializations(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002111 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002112 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002113 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002114 case Decl::ObjCMethod: {
2115 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2116 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002117 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002118 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2119 break;
2120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00002122 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002123 break;
2124
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002125 case Decl::LinkageSpec:
2126 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002127 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002128
2129 case Decl::FileScopeAsm: {
2130 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramer8d042582009-12-11 13:33:18 +00002131 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Daniel Dunbar41071de2008-08-15 23:26:23 +00002133 const std::string &S = getModule().getModuleInlineAsm();
2134 if (S.empty())
2135 getModule().setModuleInlineAsm(AsmString);
2136 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002137 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002138 break;
2139 }
Mike Stump1eb44332009-09-09 15:08:12 +00002140
2141 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002142 // Make sure we handled everything we should, every other kind is a
2143 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2144 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002145 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2146 }
2147}
John McCall744016d2010-07-06 23:57:41 +00002148
2149/// Turns the given pointer into a constant.
2150static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2151 const void *Ptr) {
2152 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2153 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2154 return llvm::ConstantInt::get(i64, PtrInt);
2155}
2156
2157static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2158 llvm::NamedMDNode *&GlobalMetadata,
2159 GlobalDecl D,
2160 llvm::GlobalValue *Addr) {
2161 if (!GlobalMetadata)
2162 GlobalMetadata =
2163 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2164
2165 // TODO: should we report variant information for ctors/dtors?
2166 llvm::Value *Ops[] = {
2167 Addr,
2168 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2169 };
Jay Foad6f141652011-04-21 19:59:12 +00002170 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002171}
2172
2173/// Emits metadata nodes associating all the global values in the
2174/// current module with the Decls they came from. This is useful for
2175/// projects using IR gen as a subroutine.
2176///
2177/// Since there's currently no way to associate an MDNode directly
2178/// with an llvm::GlobalValue, we create a global named metadata
2179/// with the name 'clang.global.decl.ptrs'.
2180void CodeGenModule::EmitDeclMetadata() {
2181 llvm::NamedMDNode *GlobalMetadata = 0;
2182
2183 // StaticLocalDeclMap
2184 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2185 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2186 I != E; ++I) {
2187 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2188 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2189 }
2190}
2191
2192/// Emits metadata nodes for all the local variables in the current
2193/// function.
2194void CodeGenFunction::EmitDeclMetadata() {
2195 if (LocalDeclMap.empty()) return;
2196
2197 llvm::LLVMContext &Context = getLLVMContext();
2198
2199 // Find the unique metadata ID for this name.
2200 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2201
2202 llvm::NamedMDNode *GlobalMetadata = 0;
2203
2204 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2205 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2206 const Decl *D = I->first;
2207 llvm::Value *Addr = I->second;
2208
2209 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2210 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002211 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002212 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2213 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2214 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2215 }
2216 }
2217}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002218
2219///@name Custom Runtime Function Interfaces
2220///@{
2221//
2222// FIXME: These can be eliminated once we can have clients just get the required
2223// AST nodes from the builtin tables.
2224
2225llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2226 if (BlockObjectDispose)
2227 return BlockObjectDispose;
2228
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002229 // If we saw an explicit decl, use that.
2230 if (BlockObjectDisposeDecl) {
2231 return BlockObjectDispose = GetAddrOfFunction(
2232 BlockObjectDisposeDecl,
2233 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2234 }
2235
2236 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002237 const llvm::FunctionType *FTy;
2238 std::vector<const llvm::Type*> ArgTys;
2239 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
John McCalld16c2cf2011-02-08 08:22:06 +00002240 ArgTys.push_back(Int8PtrTy);
Daniel Dunbar673431a2010-07-16 00:00:15 +00002241 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2242 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2243 return BlockObjectDispose =
2244 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2245}
2246
2247llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2248 if (BlockObjectAssign)
2249 return BlockObjectAssign;
2250
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002251 // If we saw an explicit decl, use that.
2252 if (BlockObjectAssignDecl) {
2253 return BlockObjectAssign = GetAddrOfFunction(
2254 BlockObjectAssignDecl,
2255 getTypes().GetFunctionType(BlockObjectAssignDecl));
2256 }
2257
2258 // Otherwise construct the function by hand.
Daniel Dunbar673431a2010-07-16 00:00:15 +00002259 const llvm::FunctionType *FTy;
2260 std::vector<const llvm::Type*> ArgTys;
2261 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
John McCalld16c2cf2011-02-08 08:22:06 +00002262 ArgTys.push_back(Int8PtrTy);
2263 ArgTys.push_back(Int8PtrTy);
Daniel Dunbar673431a2010-07-16 00:00:15 +00002264 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2265 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2266 return BlockObjectAssign =
2267 CreateRuntimeFunction(FTy, "_Block_object_assign");
2268}
2269
2270llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2271 if (NSConcreteGlobalBlock)
2272 return NSConcreteGlobalBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002273
2274 // If we saw an explicit decl, use that.
2275 if (NSConcreteGlobalBlockDecl) {
2276 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2277 NSConcreteGlobalBlockDecl,
2278 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2279 }
2280
2281 // Otherwise construct the variable by hand.
John McCalld16c2cf2011-02-08 08:22:06 +00002282 return NSConcreteGlobalBlock =
2283 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002284}
2285
2286llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2287 if (NSConcreteStackBlock)
2288 return NSConcreteStackBlock;
Daniel Dunbar754b9fb2010-07-16 00:00:19 +00002289
2290 // If we saw an explicit decl, use that.
2291 if (NSConcreteStackBlockDecl) {
2292 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2293 NSConcreteStackBlockDecl,
2294 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2295 }
2296
2297 // Otherwise construct the variable by hand.
John McCalld16c2cf2011-02-08 08:22:06 +00002298 return NSConcreteStackBlock =
2299 CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");
Daniel Dunbar673431a2010-07-16 00:00:15 +00002300}
2301
2302///@}