blob: 5d549c91964dd15fc157c0570865b63902ef0a30 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattner984fac52009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000016#include "CodeGenFunction.h"
Dan Gohman947c9af2010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CGCall.h"
John McCall5d865c322010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Douglas Gregor5fec5b02009-02-13 00:10:09 +000021#include "Mangle.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000022#include "TargetInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000023#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000024#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000025#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000026#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000027#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000028#include "clang/AST/DeclTemplate.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000036#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000037#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCallbeec5a02010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000041#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000042#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000043using namespace clang;
44using namespace CodeGen;
45
John McCall614dbdc2010-08-22 21:01:12 +000046static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
47 switch (CGM.getContext().Target.getCXXABI()) {
48 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
49 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
50 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
51 }
52
53 llvm_unreachable("invalid C++ ABI kind");
54 return *CreateItaniumCXXABI(CGM);
55}
56
Chris Lattnerbed31442007-05-28 01:07:47 +000057
Chandler Carruthbc55fe22009-11-12 17:24:48 +000058CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000059 llvm::Module &M, const llvm::TargetData &TD,
60 Diagnostic &diags)
Chris Lattner984fac52009-03-26 05:00:52 +000061 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruthbc55fe22009-11-12 17:24:48 +000062 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000063 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCall614dbdc2010-08-22 21:01:12 +000064 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman947c9af2010-10-14 23:06:10 +000066 TBAA(0),
John McCall614dbdc2010-08-22 21:01:12 +000067 VTables(*this), Runtime(0),
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000068 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000069 VMContext(M.getContext()),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000070 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000071 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000072 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000073 BlockObjectAssign(0), BlockObjectDispose(0){
Daniel Dunbar8d480592008-08-11 18:12:00 +000074
Chris Lattner36376522009-03-21 07:12:05 +000075 if (!Features.ObjC1)
76 Runtime = 0;
77 else if (!Features.NeXTRuntime)
78 Runtime = CreateGNUObjCRuntime(*this);
79 else if (Features.ObjCNonFragileABI)
80 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
81 else
82 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000083
Dan Gohman947c9af2010-10-14 23:06:10 +000084 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman2e29eb52010-10-15 20:23:12 +000086 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +000088
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000089 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson3efc6e62009-12-06 18:00:51 +000090 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattnera087ff92008-03-01 08:45:05 +000091}
92
93CodeGenModule::~CodeGenModule() {
Ted Kremenek2c674f62008-08-05 18:50:11 +000094 delete Runtime;
John McCall614dbdc2010-08-22 21:01:12 +000095 delete &ABI;
Dan Gohmand19ee8a2010-10-15 18:04:46 +000096 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +000097 delete DebugInfo;
98}
99
David Chisnall481e3a82010-01-23 02:40:42 +0000100void CodeGenModule::createObjCRuntime() {
101 if (!Features.NeXTRuntime)
102 Runtime = CreateGNUObjCRuntime(*this);
103 else if (Features.ObjCNonFragileABI)
104 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
105 else
106 Runtime = CreateMacObjCRuntime(*this);
107}
108
Ted Kremenek2c674f62008-08-05 18:50:11 +0000109void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000110 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000111 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000112 EmitCXXGlobalDtorFunc();
Daniel Dunbar8d480592008-08-11 18:12:00 +0000113 if (Runtime)
114 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
115 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000116 EmitCtorList(GlobalCtors, "llvm.global_ctors");
117 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman7fab5782008-04-18 23:43:57 +0000118 EmitAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000119 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000120
John McCall0bdb1fd2010-09-16 06:16:50 +0000121 SimplifyPersonality();
122
John McCall09ae0322010-07-06 23:57:41 +0000123 if (getCodeGenOpts().EmitDeclMetadata)
124 EmitDeclMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000125}
126
Dan Gohman947c9af2010-10-14 23:06:10 +0000127llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
128 if (!TBAA)
129 return 0;
130 return TBAA->getTBAAInfo(QTy);
131}
132
133void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
134 llvm::MDNode *TBAAInfo) {
135 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
136}
137
John McCallbeec5a02010-03-06 00:35:14 +0000138bool CodeGenModule::isTargetDarwin() const {
139 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
140}
141
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000142/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000143/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000144void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
145 bool OmitOnError) {
146 if (OmitOnError && getDiags().hasErrorOccurred())
147 return;
Mike Stump11289f42009-09-09 15:08:12 +0000148 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000149 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000150 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000151 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
152 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000153}
Chris Lattner41af8182007-12-02 06:27:33 +0000154
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000155/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000156/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000157void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
158 bool OmitOnError) {
159 if (OmitOnError && getDiags().hasErrorOccurred())
160 return;
Mike Stump11289f42009-09-09 15:08:12 +0000161 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000162 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000163 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000164 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000165}
166
John McCall37bb6c92010-10-29 22:22:43 +0000167static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
168 switch (V) {
169 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
170 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
171 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
172 }
173 llvm_unreachable("unknown visibility!");
174 return llvm::GlobalValue::DefaultVisibility;
175}
176
177
Mike Stump11289f42009-09-09 15:08:12 +0000178void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
John McCallc273f242010-10-30 11:50:40 +0000179 const NamedDecl *D,
180 bool IsForDefinition) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000181 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000182 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000183 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000184 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000185 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000186
John McCallc273f242010-10-30 11:50:40 +0000187 // Set visibility for definitions.
188 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
189 if (LV.visibilityExplicit() ||
190 (IsForDefinition && !GV->hasAvailableExternallyLinkage()))
191 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000192}
193
John McCalle16adc22010-08-04 08:34:44 +0000194/// Set the symbol visibility of type information (vtable and RTTI)
195/// associated with the given type.
196void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
197 const CXXRecordDecl *RD,
John McCallc273f242010-10-30 11:50:40 +0000198 bool IsForRTTI,
199 bool IsForDefinition) const {
200 setGlobalVisibility(GV, RD, IsForDefinition);
John McCalle16adc22010-08-04 08:34:44 +0000201
John McCallb3732bb2010-08-12 23:36:15 +0000202 if (!CodeGenOpts.HiddenWeakVTables)
203 return;
204
John McCalle16adc22010-08-04 08:34:44 +0000205 // We want to drop the visibility to hidden for weak type symbols.
206 // This isn't possible if there might be unresolved references
207 // elsewhere that rely on this symbol being visible.
208
John McCall5513fce92010-08-05 20:39:18 +0000209 // This should be kept roughly in sync with setThunkVisibility
210 // in CGVTables.cpp.
211
John McCalle16adc22010-08-04 08:34:44 +0000212 // Preconditions.
213 if (GV->getLinkage() != llvm::GlobalVariable::WeakODRLinkage ||
214 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
215 return;
216
217 // Don't override an explicit visibility attribute.
218 if (RD->hasAttr<VisibilityAttr>())
219 return;
220
221 switch (RD->getTemplateSpecializationKind()) {
222 // We have to disable the optimization if this is an EI definition
223 // because there might be EI declarations in other shared objects.
224 case TSK_ExplicitInstantiationDefinition:
225 case TSK_ExplicitInstantiationDeclaration:
226 return;
227
John McCall5513fce92010-08-05 20:39:18 +0000228 // Every use of a non-template class's type information has to emit it.
John McCalle16adc22010-08-04 08:34:44 +0000229 case TSK_Undeclared:
230 break;
231
John McCall5513fce92010-08-05 20:39:18 +0000232 // In theory, implicit instantiations can ignore the possibility of
233 // an explicit instantiation declaration because there necessarily
234 // must be an EI definition somewhere with default visibility. In
235 // practice, it's possible to have an explicit instantiation for
236 // an arbitrary template class, and linkers aren't necessarily able
237 // to deal with mixed-visibility symbols.
238 case TSK_ExplicitSpecialization:
John McCalle16adc22010-08-04 08:34:44 +0000239 case TSK_ImplicitInstantiation:
John McCallb3732bb2010-08-12 23:36:15 +0000240 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall5513fce92010-08-05 20:39:18 +0000241 return;
John McCalle16adc22010-08-04 08:34:44 +0000242 break;
243 }
244
245 // If there's a key function, there may be translation units
246 // that don't have the key function's definition. But ignore
247 // this if we're emitting RTTI under -fno-rtti.
248 if (!IsForRTTI || Features.RTTI)
249 if (Context.getKeyFunction(RD))
250 return;
251
252 // Otherwise, drop the visibility to hidden.
253 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
254}
255
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000256llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
257 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
258
259 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
260 if (!Str.empty())
261 return Str;
262
John McCall5d865c322010-08-31 07:33:07 +0000263 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000264 IdentifierInfo *II = ND->getIdentifier();
265 assert(II && "Attempt to mangle unnamed decl.");
266
267 Str = II->getName();
268 return Str;
269 }
270
271 llvm::SmallString<256> Buffer;
272 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000273 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000274 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000275 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000276 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000277 getCXXABI().getMangleContext().mangleBlock(GD, BD, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000278 else
John McCall5d865c322010-08-31 07:33:07 +0000279 getCXXABI().getMangleContext().mangleName(ND, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000280
281 // Allocate space for the mangled name.
282 size_t Length = Buffer.size();
283 char *Name = MangledNamesAllocator.Allocate<char>(Length);
284 std::copy(Buffer.begin(), Buffer.end(), Name);
285
286 Str = llvm::StringRef(Name, Length);
287
288 return Str;
289}
290
Fariborz Jahanian9b5528d2010-06-24 00:08:06 +0000291void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer,
292 const BlockDecl *BD) {
John McCall5d865c322010-08-31 07:33:07 +0000293 getCXXABI().getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer());
Anders Carlsson635186a2010-06-09 02:36:32 +0000294}
295
John McCall7ec50432010-03-19 23:29:14 +0000296llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
297 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000298}
299
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000300/// AddGlobalCtor - Add a function to the list that will be called before
301/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000302void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000303 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000304 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000305}
306
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000307/// AddGlobalDtor - Add a function to the list that will be called
308/// when the module is unloaded.
309void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000310 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000311 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
312}
313
314void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
315 // Ctor function type is void()*.
316 llvm::FunctionType* CtorFTy =
Mike Stump11289f42009-09-09 15:08:12 +0000317 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000318 std::vector<const llvm::Type*>(),
319 false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000320 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000321
322 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump11289f42009-09-09 15:08:12 +0000323 llvm::StructType* CtorStructTy =
324 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson9793f0e2009-07-29 22:16:19 +0000325 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000326
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000327 // Construct the constructor and destructor arrays.
328 std::vector<llvm::Constant*> Ctors;
329 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
330 std::vector<llvm::Constant*> S;
Mike Stump11289f42009-09-09 15:08:12 +0000331 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson41a75022009-08-13 21:57:51 +0000332 I->second, false));
Owen Andersonade90fd2009-07-29 18:54:39 +0000333 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson0e0189d2009-07-27 22:29:56 +0000334 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000335 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000336
337 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000338 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000339 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000340 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000341 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000342 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000343 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000344}
345
Nate Begeman7fab5782008-04-18 23:43:57 +0000346void CodeGenModule::EmitAnnotations() {
347 if (Annotations.empty())
348 return;
349
350 // Create a new global variable for the ConstantStruct in the Module.
351 llvm::Constant *Array =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000352 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman7fab5782008-04-18 23:43:57 +0000353 Annotations.size()),
354 Annotations);
Mike Stump11289f42009-09-09 15:08:12 +0000355 llvm::GlobalValue *gv =
356 new llvm::GlobalVariable(TheModule, Array->getType(), false,
357 llvm::GlobalValue::AppendingLinkage, Array,
Owen Andersonc10c8d32009-07-08 19:05:04 +0000358 "llvm.global.annotations");
Nate Begeman7fab5782008-04-18 23:43:57 +0000359 gv->setSection("llvm.metadata");
360}
361
John McCalld4324142010-02-19 01:32:20 +0000362llvm::GlobalValue::LinkageTypes
363CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000364 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000365
Chris Lattner749b8ed2010-06-30 16:58:07 +0000366 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000367 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000368
369 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000370 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000371
372 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000373 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000374
375 // In C99 mode, 'inline' functions are guaranteed to have a strong
376 // definition somewhere else, so we can use available_externally linkage.
377 if (Linkage == GVA_C99Inline)
John McCalld4324142010-02-19 01:32:20 +0000378 return llvm::Function::AvailableExternallyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000379
380 // In C++, the compiler has to emit a definition in every translation unit
381 // that references the function. We should use linkonce_odr because
382 // a) if all references in this translation unit are optimized away, we
383 // don't need to codegen it. b) if the function persists, it needs to be
384 // merged with other definitions. c) C++ has the ODR, so we know the
385 // definition is dependable.
386 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld4324142010-02-19 01:32:20 +0000387 return llvm::Function::LinkOnceODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000388
389 // An explicit instantiation of a template has weak linkage, since
390 // explicit instantiations can occur in multiple translation units
391 // and must all be equivalent. However, we are not allowed to
392 // throw away these explicit instantiations.
393 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregorb14d1232010-03-13 18:23:07 +0000394 return llvm::Function::WeakODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000395
396 // Otherwise, we have strong external linkage.
397 assert(Linkage == GVA_StrongExternal);
398 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000399}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000400
John McCalld4324142010-02-19 01:32:20 +0000401
402/// SetFunctionDefinitionAttributes - Set attributes for a global.
403///
404/// FIXME: This is currently only done for aliases and functions, but not for
405/// variables (these details are set in EmitGlobalVarDefinition for variables).
406void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
407 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000408 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000409}
410
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000411void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000412 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000413 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000414 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000415 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000416 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel322300d2008-09-25 21:02:23 +0000417 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000418 AttributeList.size()));
419 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000420}
421
Daniel Dunbar38932572009-04-14 08:05:55 +0000422void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
423 llvm::Function *F) {
Daniel Dunbar0f3403c2009-03-02 04:58:03 +0000424 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump11289f42009-09-09 15:08:12 +0000425 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000426
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000427 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbar03a38442008-10-28 00:17:57 +0000428 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000430 if (D->hasAttr<NakedAttr>())
431 F->addFnAttr(llvm::Attribute::Naked);
432
Mike Stump3722f582009-08-26 22:31:08 +0000433 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000434 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000435
Rafael Espindola0ee986c1f2011-01-11 00:26:26 +0000436 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
437 F->setUnnamedAddr(true);
438
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000439 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
440 F->addFnAttr(llvm::Attribute::StackProtect);
441 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
442 F->addFnAttr(llvm::Attribute::StackProtectReq);
443
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000444 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
445 if (alignment)
446 F->setAlignment(alignment);
447
Mike Stump3472ae52009-10-05 22:49:20 +0000448 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000449 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
450 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000451}
452
Mike Stump11289f42009-09-09 15:08:12 +0000453void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000454 llvm::GlobalValue *GV) {
John McCall457a04e2010-10-22 21:05:15 +0000455 if (isa<NamedDecl>(D))
John McCallc273f242010-10-30 11:50:40 +0000456 setGlobalVisibility(GV, cast<NamedDecl>(D), /*ForDef*/ true);
John McCall457a04e2010-10-22 21:05:15 +0000457 else
458 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000459
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000460 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000461 AddUsedGlobal(GV);
462
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000463 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000464 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000465
466 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000467}
468
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000469void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
470 llvm::Function *F,
471 const CGFunctionInfo &FI) {
472 SetLLVMFunctionAttributes(D, FI, F);
473 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000474
475 F->setLinkage(llvm::Function::InternalLinkage);
476
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000477 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000478}
479
Anders Carlsson6710c532010-02-06 02:44:09 +0000480void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000481 llvm::Function *F,
482 bool IsIncompleteFunction) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000483 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
484
Eli Friedman895771a2009-05-26 01:22:57 +0000485 if (!IsIncompleteFunction)
Anders Carlsson6710c532010-02-06 02:44:09 +0000486 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000487
Daniel Dunbar38932572009-04-14 08:05:55 +0000488 // Only a few attributes are set on declarations; these may later be
489 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000490
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000491 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000492 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000493 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000494 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000495 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000496 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000497 F->setLinkage(llvm::Function::ExternalWeakLinkage);
498 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000499 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallc273f242010-10-30 11:50:40 +0000500
501 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
502 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
503 F->setVisibility(GetLLVMVisibility(LV.visibility()));
504 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000505 }
506
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000507 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000508 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000509}
510
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000511void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000512 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000513 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000514 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000515}
516
517void CodeGenModule::EmitLLVMUsed() {
518 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000519 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000520 return;
521
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000522 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000524 // Convert LLVMUsed to what ConstantArray needs.
525 std::vector<llvm::Constant*> UsedArray;
526 UsedArray.resize(LLVMUsed.size());
527 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000528 UsedArray[i] =
529 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Anderson170229f2009-07-14 23:10:40 +0000530 i8PTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000531 }
Mike Stump11289f42009-09-09 15:08:12 +0000532
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000533 if (UsedArray.empty())
534 return;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000535 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000536
537 llvm::GlobalVariable *GV =
538 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000539 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000540 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000541 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000542
543 GV->setSection("llvm.metadata");
544}
545
546void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000547 // Emit code for any potentially referenced deferred decls. Since a
548 // previously unused static decl may become used during the generation of code
549 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000550
Anders Carlsson11e51402010-04-17 20:15:18 +0000551 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
552 if (!DeferredVTables.empty()) {
553 const CXXRecordDecl *RD = DeferredVTables.back();
554 DeferredVTables.pop_back();
555 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000556 continue;
557 }
558
Anders Carlssondae1abc2009-05-05 04:44:02 +0000559 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000560 DeferredDeclsToEmit.pop_back();
561
John McCallc2af9392010-05-27 01:45:30 +0000562 // Check to see if we've already emitted this. This is necessary
563 // for a couple of reasons: first, decls can end up in the
564 // deferred-decls queue multiple times, and second, decls can end
565 // up with definitions in unusual ways (e.g. by an extern inline
566 // function acquiring a strong function redefinition). Just
567 // ignore these cases.
568 //
569 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000570 llvm::StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000571 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000572 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000573
Chris Lattner45470942009-03-21 09:44:56 +0000574 if (!CGRef->isDeclaration())
575 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000576
John McCallc2af9392010-05-27 01:45:30 +0000577 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
578 // purposes an alias counts as a definition.
579 if (isa<llvm::GlobalAlias>(CGRef))
580 continue;
581
Chris Lattner45470942009-03-21 09:44:56 +0000582 // Otherwise, emit the definition and move on to the next one.
583 EmitGlobalDefinition(D);
584 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000585}
Chris Lattner09153c02007-06-22 18:48:09 +0000586
Mike Stump11289f42009-09-09 15:08:12 +0000587/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begemanfaae0812008-04-19 04:17:09 +0000588/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump11289f42009-09-09 15:08:12 +0000589/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
590/// GlobalValue being annotated. The second field is the constant string
591/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begemanfaae0812008-04-19 04:17:09 +0000592/// string containing the name of the translation unit. The fourth field is
593/// the line number in the file of the annotated value declaration.
594///
595/// FIXME: this does not unique the annotation string constants, as llvm-gcc
596/// appears to.
597///
Mike Stump11289f42009-09-09 15:08:12 +0000598llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000599 const AnnotateAttr *AA,
600 unsigned LineNo) {
601 llvm::Module *M = &getModule();
602
603 // get [N x i8] constants for the annotation string, and the filename string
604 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000605 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000606 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000607 AA->getAnnotation(), true);
608 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
609 M->getModuleIdentifier(),
Nate Begemanfaae0812008-04-19 04:17:09 +0000610 true);
611
612 // Get the two global values corresponding to the ConstantArrays we just
613 // created to hold the bytes of the strings.
Mike Stump11289f42009-09-09 15:08:12 +0000614 llvm::GlobalValue *annoGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000615 new llvm::GlobalVariable(*M, anno->getType(), false,
616 llvm::GlobalValue::PrivateLinkage, anno,
617 GV->getName());
Nate Begemanfaae0812008-04-19 04:17:09 +0000618 // translation unit name string, emitted into the llvm.metadata section.
619 llvm::GlobalValue *unitGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000620 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump11289f42009-09-09 15:08:12 +0000621 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner3afa3e12009-07-16 05:03:48 +0000622 ".str");
Nate Begemanfaae0812008-04-19 04:17:09 +0000623
Daniel Dunbar346892a2009-04-14 22:41:13 +0000624 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000625 llvm::Constant *Fields[4] = {
Owen Andersonade90fd2009-07-29 18:54:39 +0000626 llvm::ConstantExpr::getBitCast(GV, SBP),
627 llvm::ConstantExpr::getBitCast(annoGV, SBP),
628 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson41a75022009-08-13 21:57:51 +0000629 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begemanfaae0812008-04-19 04:17:09 +0000630 };
Owen Anderson758428f2009-08-05 23:18:46 +0000631 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begemanfaae0812008-04-19 04:17:09 +0000632}
633
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +0000634bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000635 // Never defer when EmitAllDecls is specified.
636 if (Features.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000637 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000638
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +0000639 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000640}
641
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000642llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
643 const AliasAttr *AA = VD->getAttr<AliasAttr>();
644 assert(AA && "No alias?");
645
646 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
647
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000648 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000649 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000650
651 llvm::Constant *Aliasee;
652 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +0000653 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000654 else
John McCall7ec50432010-03-19 23:29:14 +0000655 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000656 llvm::PointerType::getUnqual(DeclTy), 0);
657 if (!Entry) {
658 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
659 F->setLinkage(llvm::Function::ExternalWeakLinkage);
660 WeakRefReferences.insert(F);
661 }
662
663 return Aliasee;
664}
665
Chris Lattnere0be0df2009-05-12 21:21:08 +0000666void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000667 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000668
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000669 // Weak references don't produce any output by themselves.
670 if (Global->hasAttr<WeakRefAttr>())
671 return;
672
Chris Lattner54041692009-03-22 21:47:11 +0000673 // If this is an alias definition (which otherwise looks like a declaration)
674 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000675 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000676 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000677
Chris Lattner45470942009-03-21 09:44:56 +0000678 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000679 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000680 if (FD->getIdentifier()) {
681 llvm::StringRef Name = FD->getName();
682 if (Name == "_Block_object_assign") {
683 BlockObjectAssignDecl = FD;
684 } else if (Name == "_Block_object_dispose") {
685 BlockObjectDisposeDecl = FD;
686 }
687 }
688
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000689 // Forward declarations are emitted lazily on first use.
690 if (!FD->isThisDeclarationADefinition())
691 return;
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000692 } else {
693 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000694 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
695
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000696 if (VD->getIdentifier()) {
697 llvm::StringRef Name = VD->getName();
698 if (Name == "_NSConcreteGlobalBlock") {
699 NSConcreteGlobalBlockDecl = VD;
700 } else if (Name == "_NSConcreteStackBlock") {
701 NSConcreteStackBlockDecl = VD;
702 }
703 }
704
705
Douglas Gregor61f6db52010-02-06 05:15:45 +0000706 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000707 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000708 }
709
Chris Lattner45470942009-03-21 09:44:56 +0000710 // Defer code generation when possible if this is a static definition, inline
711 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000712 if (!MayDeferGeneration(Global)) {
713 // Emit the definition if it can't be deferred.
714 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000715 return;
716 }
John McCall70013b62010-07-15 23:40:35 +0000717
718 // If we're deferring emission of a C++ variable with an
719 // initializer, remember the order in which it appeared in the file.
720 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
721 cast<VarDecl>(Global)->hasInit()) {
722 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
723 CXXGlobalInits.push_back(0);
724 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000725
726 // If the value has already been used, add it directly to the
727 // DeferredDeclsToEmit list.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000728 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000729 if (GetGlobalValue(MangledName))
730 DeferredDeclsToEmit.push_back(GD);
731 else {
732 // Otherwise, remember that we saw a deferred decl with this name. The
733 // first use of the mangled name will cause it to move into
734 // DeferredDeclsToEmit.
735 DeferredDecls[MangledName] = GD;
736 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000737}
738
Chris Lattnere0be0df2009-05-12 21:21:08 +0000739void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000740 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000741
Dan Gohman145f3f12010-04-19 16:39:44 +0000742 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000743 Context.getSourceManager(),
744 "Generating code for declaration");
745
Douglas Gregora700f682010-07-13 06:02:28 +0000746 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
747 // At -O0, don't generate IR for functions with available_externally
748 // linkage.
Douglas Gregor89976902010-07-15 22:58:18 +0000749 if (CodeGenOpts.OptimizationLevel == 0 &&
750 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregora700f682010-07-13 06:02:28 +0000751 getFunctionLinkage(Function)
752 == llvm::Function::AvailableExternallyLinkage)
753 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000754
Douglas Gregora700f682010-07-13 06:02:28 +0000755 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
756 if (Method->isVirtual())
757 getVTables().EmitThunks(GD);
758
759 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
760 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000761
Douglas Gregora700f682010-07-13 06:02:28 +0000762 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
763 return EmitCXXDestructor(DD, GD.getDtorType());
764 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000765
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000766 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000767 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000768
769 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
770 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000771
772 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000773}
774
Chris Lattnerd4808922009-03-22 21:03:39 +0000775/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
776/// module, create and return an llvm Function with the specified type. If there
777/// is something in the module with the specified name, return it potentially
778/// bitcasted to the right type.
779///
780/// If D is non-null, it specifies a decl that correspond to this. This is used
781/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000782llvm::Constant *
783CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
784 const llvm::Type *Ty,
785 GlobalDecl D) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000786 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000787 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000788 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000789 if (WeakRefReferences.count(Entry)) {
790 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
791 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000792 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000793
794 WeakRefReferences.erase(Entry);
795 }
796
Chris Lattnera85d68e2009-03-21 09:25:43 +0000797 if (Entry->getType()->getElementType() == Ty)
798 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000799
Chris Lattnera85d68e2009-03-21 09:25:43 +0000800 // Make sure the result is of the correct type.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000801 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Andersonade90fd2009-07-29 18:54:39 +0000802 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Eli Friedmancc522d92009-11-09 05:07:37 +0000805 // This function doesn't have a complete type (for example, the return
806 // type is an incomplete struct). Use a fake type instead, and make
807 // sure not to try to set attributes.
808 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +0000809
810 const llvm::FunctionType *FTy;
811 if (isa<llvm::FunctionType>(Ty)) {
812 FTy = cast<llvm::FunctionType>(Ty);
813 } else {
814 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
815 std::vector<const llvm::Type*>(), false);
Eli Friedmancc522d92009-11-09 05:07:37 +0000816 IsIncompleteFunction = true;
817 }
Chris Lattner5c740f12010-06-30 19:14:05 +0000818
John McCalld06fb862010-04-28 00:00:30 +0000819 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +0000820 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000821 MangledName, &getModule());
822 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +0000823 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +0000824 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedmancc522d92009-11-09 05:07:37 +0000825
Chris Lattner45470942009-03-21 09:44:56 +0000826 // This is the first use or definition of a mangled name. If there is a
827 // deferred decl with this name, remember that we need to emit it at the end
828 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000829 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000830 if (DDI != DeferredDecls.end()) {
831 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
832 // list, and remove it from DeferredDecls (since we don't need it anymore).
833 DeferredDeclsToEmit.push_back(DDI->second);
834 DeferredDecls.erase(DDI);
John McCall357d0f32010-12-15 04:00:32 +0000835
836 // Otherwise, there are cases we have to worry about where we're
837 // using a declaration for which we must emit a definition but where
838 // we might not find a top-level definition:
839 // - member functions defined inline in their classes
840 // - friend functions defined inline in some class
841 // - special member functions with implicit definitions
842 // If we ever change our AST traversal to walk into class methods,
843 // this will be unnecessary.
844 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
845 // Look for a declaration that's lexically in a record.
846 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
847 do {
848 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
849 if (FD->isImplicit()) {
850 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
851 DeferredDeclsToEmit.push_back(D);
852 break;
853 } else if (FD->isThisDeclarationADefinition()) {
854 DeferredDeclsToEmit.push_back(D);
855 break;
856 }
Rafael Espindola70e040d2010-03-02 21:28:26 +0000857 }
John McCall357d0f32010-12-15 04:00:32 +0000858 FD = FD->getPreviousDeclaration();
859 } while (FD);
Chris Lattner45470942009-03-21 09:44:56 +0000860 }
Mike Stump11289f42009-09-09 15:08:12 +0000861
John McCalld06fb862010-04-28 00:00:30 +0000862 // Make sure the result is of the requested type.
863 if (!IsIncompleteFunction) {
864 assert(F->getType()->getElementType() == Ty);
865 return F;
866 }
867
868 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
869 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000870}
871
Chris Lattnerd4808922009-03-22 21:03:39 +0000872/// GetAddrOfFunction - Return the address of the given function. If Ty is
873/// non-null, then this function will use the specified type if it has to
874/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +0000875llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattnerd4808922009-03-22 21:03:39 +0000876 const llvm::Type *Ty) {
877 // If there was no specific requested type, just convert it now.
878 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +0000879 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +0000880
Anders Carlssonea836bc2010-06-22 16:16:50 +0000881 llvm::StringRef MangledName = getMangledName(GD);
John McCall7ec50432010-03-19 23:29:14 +0000882 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattnerd4808922009-03-22 21:03:39 +0000883}
Eli Friedmanc18d9d52008-05-30 19:50:47 +0000884
Chris Lattnerd4808922009-03-22 21:03:39 +0000885/// CreateRuntimeFunction - Create a new runtime function with the specified
886/// type and name.
887llvm::Constant *
888CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCall7ec50432010-03-19 23:29:14 +0000889 llvm::StringRef Name) {
Chris Lattnere0be0df2009-05-12 21:21:08 +0000890 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattnerd4808922009-03-22 21:03:39 +0000891}
Daniel Dunbar9c426522008-07-29 23:18:29 +0000892
Eli Friedmanb095e152009-12-11 21:23:03 +0000893static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall340aafa2010-02-08 21:46:50 +0000894 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +0000895 return false;
896 if (Context.getLangOptions().CPlusPlus &&
897 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
898 // FIXME: We should do something fancier here!
899 return false;
900 }
901 return true;
902}
903
Chris Lattnerd4808922009-03-22 21:03:39 +0000904/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
905/// create and return an llvm GlobalVariable with the specified type. If there
906/// is something in the module with the specified name, return it potentially
907/// bitcasted to the right type.
908///
909/// If D is non-null, it specifies a decl that correspond to this. This is used
910/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000911llvm::Constant *
912CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
913 const llvm::PointerType *Ty,
914 const VarDecl *D) {
Daniel Dunbar829e9882008-08-05 23:31:02 +0000915 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000916 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +0000917 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000918 if (WeakRefReferences.count(Entry)) {
919 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000920 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000921
922 WeakRefReferences.erase(Entry);
923 }
924
Chris Lattnerd4808922009-03-22 21:03:39 +0000925 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +0000926 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattner3bfce182009-03-21 08:03:33 +0000928 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +0000929 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +0000930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattner45470942009-03-21 09:44:56 +0000932 // This is the first use or definition of a mangled name. If there is a
933 // deferred decl with this name, remember that we need to emit it at the end
934 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000935 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000936 if (DDI != DeferredDecls.end()) {
937 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
938 // list, and remove it from DeferredDecls (since we don't need it anymore).
939 DeferredDeclsToEmit.push_back(DDI->second);
940 DeferredDecls.erase(DDI);
941 }
Mike Stump11289f42009-09-09 15:08:12 +0000942
943 llvm::GlobalVariable *GV =
944 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +0000945 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000946 0, MangledName, 0,
Eli Friedman4f856742009-04-19 21:05:03 +0000947 false, Ty->getAddressSpace());
Chris Lattner3bfce182009-03-21 08:03:33 +0000948
949 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +0000950 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +0000951 // FIXME: This code is overly simple and should be merged with other global
952 // handling.
Eli Friedmanb095e152009-12-11 21:23:03 +0000953 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner3bfce182009-03-21 08:03:33 +0000954
John McCall37bb6c92010-10-29 22:22:43 +0000955 // Set linkage and visibility in case we never see a definition.
John McCallc273f242010-10-30 11:50:40 +0000956 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
957 if (LV.linkage() != ExternalLinkage) {
John McCall37bb6c92010-10-29 22:22:43 +0000958 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
959 } else {
960 if (D->hasAttr<DLLImportAttr>())
961 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
962 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
963 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +0000964
John McCallc273f242010-10-30 11:50:40 +0000965 // Set visibility on a declaration only if it's explicit.
966 if (LV.visibilityExplicit())
967 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall37bb6c92010-10-29 22:22:43 +0000968 }
Eli Friedman4f856742009-04-19 21:05:03 +0000969
970 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +0000971 }
Mike Stump11289f42009-09-09 15:08:12 +0000972
John McCall7ec50432010-03-19 23:29:14 +0000973 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000974}
975
Chris Lattnerd4808922009-03-22 21:03:39 +0000976
977/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
978/// given global variable. If Ty is non-null and if the global doesn't exist,
979/// then it will be greated with the specified type instead of whatever the
980/// normal requested type would be.
981llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
982 const llvm::Type *Ty) {
983 assert(D->hasGlobalStorage() && "Not a global variable");
984 QualType ASTTy = D->getType();
985 if (Ty == 0)
986 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +0000987
988 const llvm::PointerType *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000989 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCall7ec50432010-03-19 23:29:14 +0000990
Anders Carlssonea836bc2010-06-22 16:16:50 +0000991 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000992 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +0000993}
994
995/// CreateRuntimeVariable - Create a new runtime global variable with the
996/// specified type and name.
997llvm::Constant *
998CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCall7ec50432010-03-19 23:29:14 +0000999 llvm::StringRef Name) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001000 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
Chris Lattnerd4808922009-03-22 21:03:39 +00001001}
1002
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001003void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1004 assert(!D->getInit() && "Cannot emit definite definitions here!");
1005
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001006 if (MayDeferGeneration(D)) {
1007 // If we have not seen a reference to this variable yet, place it
1008 // into the deferred declarations table to be emitted if needed
1009 // later.
Anders Carlssonea836bc2010-06-22 16:16:50 +00001010 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001011 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001012 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001013 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001014 }
1015 }
1016
1017 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001018 EmitGlobalVarDefinition(D);
1019}
1020
Douglas Gregor88d292c2010-05-13 16:44:06 +00001021void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1022 if (DefinitionRequired)
1023 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1024}
1025
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001026llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001027CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregor2a34df32010-01-06 22:00:56 +00001028 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1029 return llvm::GlobalVariable::InternalLinkage;
1030
1031 if (const CXXMethodDecl *KeyFunction
1032 = RD->getASTContext().getKeyFunction(RD)) {
1033 // If this class has a key function, use that to determine the linkage of
1034 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001035 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001036 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001037 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001038
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001039 switch (KeyFunction->getTemplateSpecializationKind()) {
1040 case TSK_Undeclared:
1041 case TSK_ExplicitSpecialization:
1042 if (KeyFunction->isInlined())
1043 return llvm::GlobalVariable::WeakODRLinkage;
1044
1045 return llvm::GlobalVariable::ExternalLinkage;
1046
1047 case TSK_ImplicitInstantiation:
1048 case TSK_ExplicitInstantiationDefinition:
1049 return llvm::GlobalVariable::WeakODRLinkage;
1050
1051 case TSK_ExplicitInstantiationDeclaration:
1052 // FIXME: Use available_externally linkage. However, this currently
1053 // breaks LLVM's build due to undefined symbols.
1054 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1055 return llvm::GlobalVariable::WeakODRLinkage;
1056 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001057 }
1058
1059 switch (RD->getTemplateSpecializationKind()) {
1060 case TSK_Undeclared:
1061 case TSK_ExplicitSpecialization:
1062 case TSK_ImplicitInstantiation:
1063 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001064 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor2a34df32010-01-06 22:00:56 +00001065
1066 case TSK_ExplicitInstantiationDeclaration:
1067 // FIXME: Use available_externally linkage. However, this currently
1068 // breaks LLVM's build due to undefined symbols.
1069 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1070 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001071 }
1072
1073 // Silence GCC warning.
1074 return llvm::GlobalVariable::WeakODRLinkage;
1075}
1076
Ken Dyck98ca7942010-01-26 13:48:07 +00001077CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1078 return CharUnits::fromQuantity(
1079 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1080}
1081
Daniel Dunbar9c426522008-07-29 23:18:29 +00001082void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001083 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001084 QualType ASTTy = D->getType();
Eli Friedman5866fe32010-01-08 00:50:11 +00001085 bool NonConstInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001086
Sebastian Redl5ca79842010-02-01 20:16:42 +00001087 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlssonca4a5452010-01-26 17:43:42 +00001088
1089 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001090 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001091 // implicitly initialized with { 0 }.
1092 //
1093 // Note that tentative definitions are only emitted at the end of
1094 // a translation unit, so they should never have incomplete
1095 // type. In addition, EmitTentativeDefinition makes sure that we
1096 // never attempt to emit a tentative definition if a real one
1097 // exists. A use may still exists, however, so we still may need
1098 // to do a RAUW.
1099 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001100 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001101 } else {
Douglas Gregord450f062010-05-05 20:15:55 +00001102 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman719ed1a2009-02-20 01:18:21 +00001103 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001104 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001105 if (D->getType()->isReferenceType())
1106 T = D->getType();
1107
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001108 if (getLangOptions().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001109 Init = EmitNullConstant(T);
Eli Friedman5866fe32010-01-08 00:50:11 +00001110 NonConstInit = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001111 } else {
1112 ErrorUnsupported(D, "static initializer");
1113 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1114 }
John McCall70013b62010-07-15 23:40:35 +00001115 } else {
1116 // We don't need an initializer, so remove the entry for the delayed
1117 // initializer position (just in case this entry was delayed).
1118 if (getLangOptions().CPlusPlus)
1119 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001120 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001121 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001122
Chris Lattner64c55932009-03-21 08:13:05 +00001123 const llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001124 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner149927c2009-03-21 09:16:30 +00001126 // Strip off a bitcast if we got one back.
1127 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001128 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1129 // all zero index gep.
1130 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001131 Entry = CE->getOperand(0);
1132 }
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattner149927c2009-03-21 09:16:30 +00001134 // Entry is now either a Function or GlobalVariable.
1135 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001136
Chris Lattner149927c2009-03-21 09:16:30 +00001137 // We have a definition after a declaration with the wrong type.
1138 // We must make a new GlobalVariable* and update everything that used OldGV
1139 // (a declaration or tentative definition) with the new GlobalVariable*
1140 // (which will be a definition).
1141 //
1142 // This happens if there is a prototype for a global (e.g.
1143 // "extern int x[];") and then a definition of a different type (e.g.
1144 // "int x[10];"). This also happens when an initializer has a different type
1145 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001146 if (GV == 0 ||
1147 GV->getType()->getElementType() != InitType ||
1148 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump11289f42009-09-09 15:08:12 +00001149
John McCall7ec50432010-03-19 23:29:14 +00001150 // Move the old entry aside so that we'll create a new one.
1151 Entry->setName(llvm::StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001152
Chris Lattner149927c2009-03-21 09:16:30 +00001153 // Make a new global with the correct type, this is now guaranteed to work.
1154 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001155
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001156 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001157 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001158 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001159 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001160
1161 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001162 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001163 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001164
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001165 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +00001166 SourceManager &SM = Context.getSourceManager();
1167 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +00001168 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begemanfaae0812008-04-19 04:17:09 +00001169 }
1170
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001171 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001172
1173 // If it is safe to mark the global 'constant', do so now.
1174 GV->setConstant(false);
Eli Friedman5866fe32010-01-08 00:50:11 +00001175 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnerf49573d2009-08-05 05:20:29 +00001176 GV->setConstant(true);
Mike Stump11289f42009-09-09 15:08:12 +00001177
Ken Dyck160146e2010-01-27 17:10:57 +00001178 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001179
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001180 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001181 llvm::GlobalValue::LinkageTypes Linkage =
1182 GetLLVMLinkageVarDefinition(D, GV);
1183 GV->setLinkage(Linkage);
1184 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001185 // common vars aren't constant even if declared const.
1186 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001187
Daniel Dunbar38932572009-04-14 08:05:55 +00001188 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001189
John McCallcdf7ef52010-11-06 09:44:32 +00001190 // Emit the initializer function if necessary.
1191 if (NonConstInit)
1192 EmitCXXGlobalVarDeclInitFunc(D, GV);
1193
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001194 // Emit global variable debug information.
Chris Lattner64c55932009-03-21 08:13:05 +00001195 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +00001196 DI->setLocation(D->getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001197 DI->EmitGlobalVariable(GV, D);
1198 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001199}
Chris Lattner09153c02007-06-22 18:48:09 +00001200
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001201llvm::GlobalValue::LinkageTypes
1202CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1203 llvm::GlobalVariable *GV) {
1204 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1205 if (Linkage == GVA_Internal)
1206 return llvm::Function::InternalLinkage;
1207 else if (D->hasAttr<DLLImportAttr>())
1208 return llvm::Function::DLLImportLinkage;
1209 else if (D->hasAttr<DLLExportAttr>())
1210 return llvm::Function::DLLExportLinkage;
1211 else if (D->hasAttr<WeakAttr>()) {
1212 if (GV->isConstant())
1213 return llvm::GlobalVariable::WeakODRLinkage;
1214 else
1215 return llvm::GlobalVariable::WeakAnyLinkage;
1216 } else if (Linkage == GVA_TemplateInstantiation ||
1217 Linkage == GVA_ExplicitTemplateInstantiation)
1218 // FIXME: It seems like we can provide more specific linkage here
1219 // (LinkOnceODR, WeakODR).
1220 return llvm::GlobalVariable::WeakAnyLinkage;
Eric Christopher8a2ee392010-12-02 02:45:55 +00001221 else if (!getLangOptions().CPlusPlus &&
1222 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1223 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001224 !D->hasExternalStorage() && !D->getInit() &&
1225 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1226 // Thread local vars aren't considered common linkage.
1227 return llvm::GlobalVariable::CommonLinkage;
1228 }
1229 return llvm::GlobalVariable::ExternalLinkage;
1230}
1231
Chris Lattner36797ab2009-05-05 06:16:31 +00001232/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1233/// implement a function with no prototype, e.g. "int foo() {}". If there are
1234/// existing call uses of the old function in the module, this adjusts them to
1235/// call the new function directly.
1236///
1237/// This is not just a cleanup: the always_inline pass requires direct calls to
1238/// functions to be able to inline them. If there is a bitcast in the way, it
1239/// won't inline them. Instcombine normally deletes these calls, but it isn't
1240/// run at -O0.
1241static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1242 llvm::Function *NewFn) {
1243 // If we're redefining a global as a function, don't transform it.
1244 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1245 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001246
Chris Lattner36797ab2009-05-05 06:16:31 +00001247 const llvm::Type *NewRetTy = NewFn->getReturnType();
1248 llvm::SmallVector<llvm::Value*, 4> ArgList;
1249
1250 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001251 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001252 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001253 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1254 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif79ac9ed2010-07-28 09:19:33 +00001255 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greifd394aec2010-04-10 03:45:50 +00001256 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001257 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001258
Chris Lattner36797ab2009-05-05 06:16:31 +00001259 // If the return types don't match exactly, and if the call isn't dead, then
1260 // we can't transform this call.
1261 if (CI->getType() != NewRetTy && !CI->use_empty())
1262 continue;
1263
1264 // If the function was passed too few arguments, don't transform. If extra
1265 // arguments were passed, we silently drop them. If any of the types
1266 // mismatch, we don't transform.
1267 unsigned ArgNo = 0;
1268 bool DontTransform = false;
1269 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1270 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001271 if (CS.arg_size() == ArgNo ||
1272 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001273 DontTransform = true;
1274 break;
1275 }
1276 }
1277 if (DontTransform)
1278 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001279
Chris Lattner36797ab2009-05-05 06:16:31 +00001280 // Okay, we can transform this. Create the new call instruction and copy
1281 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001282 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattner36797ab2009-05-05 06:16:31 +00001283 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1284 ArgList.end(), "", CI);
1285 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001286 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001287 NewCall->takeName(CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001288 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001289 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001290
1291 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001292 if (!CI->use_empty())
1293 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001294
Chris Lattnere675d0f2010-04-01 06:31:43 +00001295 // Copy debug location attached to CI.
1296 if (!CI->getDebugLoc().isUnknown())
1297 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001298 CI->eraseFromParent();
1299 }
1300}
1301
Daniel Dunbar9c426522008-07-29 23:18:29 +00001302
Chris Lattnere0be0df2009-05-12 21:21:08 +00001303void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001304 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +00001305 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
John McCall5d865c322010-08-31 07:33:07 +00001306 getCXXABI().getMangleContext().mangleInitDiscriminator();
Chris Lattnereb7466d2009-05-12 20:58:15 +00001307 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001308 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattnera85d68e2009-03-21 09:25:43 +00001310 // Strip off a bitcast if we got one back.
1311 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1312 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1313 Entry = CE->getOperand(0);
1314 }
Mike Stump11289f42009-09-09 15:08:12 +00001315
1316
Chris Lattnera85d68e2009-03-21 09:25:43 +00001317 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001318 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001319
Daniel Dunbar99d28352009-03-09 23:53:08 +00001320 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001321 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001322 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001323
Chris Lattner5eaee562009-03-21 08:38:50 +00001324 // F is the Function* for the one with the wrong type, we must make a new
1325 // Function* and update everything that used F (a declaration) with the new
1326 // Function* (which will be a definition).
1327 //
1328 // This happens if there is a prototype for a function
1329 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001330 // (e.g. "int f(int x)"). Move the old function aside so that it
1331 // doesn't interfere with GetAddrOfFunction.
1332 OldFn->setName(llvm::StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001333 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001334
Chris Lattner36797ab2009-05-05 06:16:31 +00001335 // If this is an implementation of a function without a prototype, try to
1336 // replace any existing uses of the function (which may be calls) with uses
1337 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001338 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001339 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001340 OldFn->removeDeadConstantUsers();
1341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Chris Lattner5eaee562009-03-21 08:38:50 +00001343 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001344 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001345 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001346 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001347 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattner5eaee562009-03-21 08:38:50 +00001350 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001351 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001352
Chris Lattnera85d68e2009-03-21 09:25:43 +00001353 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001354 }
Mike Stump11289f42009-09-09 15:08:12 +00001355
John McCall8e7cb6d2010-11-02 21:04:24 +00001356 // We need to set linkage and visibility on the function before
1357 // generating code for it because various parts of IR generation
1358 // want to propagate this information down (e.g. to local static
1359 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00001360 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001361 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001362
John McCall8e7cb6d2010-11-02 21:04:24 +00001363 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1364 setGlobalVisibility(Fn, D, /*ForDef*/ true);
1365
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001366 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001367
Daniel Dunbar38932572009-04-14 08:05:55 +00001368 SetFunctionDefinitionAttributes(D, Fn);
1369 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001370
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001371 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001372 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001373 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001374 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar9c426522008-07-29 23:18:29 +00001375}
1376
John McCall7ec50432010-03-19 23:29:14 +00001377void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1378 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001379 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001380 assert(AA && "Not an alias?");
1381
Anders Carlssonea836bc2010-06-22 16:16:50 +00001382 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001383
John McCall7ec50432010-03-19 23:29:14 +00001384 // If there is a definition in the module, then it wins over the alias.
1385 // This is dubious, but allow it to be safe. Just ignore the alias.
1386 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1387 if (Entry && !Entry->isDeclaration())
1388 return;
1389
1390 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001391
1392 // Create a reference to the named value. This ensures that it is emitted
1393 // if a deferred decl.
1394 llvm::Constant *Aliasee;
1395 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +00001396 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattner54041692009-03-22 21:47:11 +00001397 else
John McCall7ec50432010-03-19 23:29:14 +00001398 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001399 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001400
1401 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001402 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001403 new llvm::GlobalAlias(Aliasee->getType(),
1404 llvm::Function::ExternalLinkage,
1405 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattner54041692009-03-22 21:47:11 +00001407 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001408 assert(Entry->isDeclaration());
1409
Chris Lattner54041692009-03-22 21:47:11 +00001410 // If there is a declaration in the module, then we had an extern followed
1411 // by the alias, as in:
1412 // extern int test6();
1413 // ...
1414 // int test6() __attribute__((alias("test7")));
1415 //
1416 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001417 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Owen Andersonade90fd2009-07-29 18:54:39 +00001419 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001420 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001421 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001422 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001423 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001424 }
Mike Stump11289f42009-09-09 15:08:12 +00001425
Daniel Dunbar38932572009-04-14 08:05:55 +00001426 // Set attributes which are particular to an alias; this is a
1427 // specialization of the attributes which may be set on a global
1428 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001429 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001430 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1431 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001432 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001433 GA->setLinkage(llvm::Function::DLLExportLinkage);
1434 } else {
1435 GA->setLinkage(llvm::Function::DLLExportLinkage);
1436 }
Mike Stump11289f42009-09-09 15:08:12 +00001437 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001438 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001439 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001440 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1441 }
1442
1443 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001444}
1445
Chris Lattnere64911a2009-03-22 21:56:56 +00001446/// getBuiltinLibFunction - Given a builtin id for a function like
1447/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001448llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1449 unsigned BuiltinID) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001450 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump11289f42009-09-09 15:08:12 +00001451 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001452 "isn't a lib fn");
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001454 // Get the name, skip over the __builtin_ prefix (if necessary).
1455 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1456 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1457 Name += 10;
Mike Stump11289f42009-09-09 15:08:12 +00001458
Mike Stump11289f42009-09-09 15:08:12 +00001459 const llvm::FunctionType *Ty =
Eli Friedman4f678f32009-12-09 03:05:59 +00001460 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattner1eec6602007-08-31 04:31:45 +00001461
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001462 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattner1eec6602007-08-31 04:31:45 +00001463}
1464
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001465llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1466 unsigned NumTys) {
1467 return llvm::Intrinsic::getDeclaration(&getModule(),
1468 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1469}
Chris Lattner1eec6602007-08-31 04:31:45 +00001470
Daniel Dunbar64509b22009-07-23 22:52:48 +00001471static llvm::StringMapEntry<llvm::Constant*> &
1472GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1473 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001474 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001475 bool &IsUTF16,
1476 unsigned &StringLength) {
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001477 llvm::StringRef String = Literal->getString();
1478 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001479
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001480 // Check for simple case.
1481 if (!Literal->containsNonAsciiOrNull()) {
1482 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001483 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001484 }
1485
Daniel Dunbar64509b22009-07-23 22:52:48 +00001486 // Otherwise, convert the UTF8 literals into a byte string.
1487 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001488 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001489 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001490
Fariborz Jahanian535618b2010-09-07 19:57:04 +00001491 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1492 &ToPtr, ToPtr + NumBytes,
1493 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001494
Daniel Dunbar91ade142009-07-23 23:41:22 +00001495 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001496 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001497
1498 // Render the UTF-16 string into a byte array and convert to the target byte
1499 // order.
1500 //
1501 // FIXME: This isn't something we should need to do here.
1502 llvm::SmallString<128> AsBytes;
1503 AsBytes.reserve(StringLength * 2);
1504 for (unsigned i = 0; i != StringLength; ++i) {
1505 unsigned short Val = ToBuf[i];
1506 if (TargetIsLSB) {
1507 AsBytes.push_back(Val & 0xFF);
1508 AsBytes.push_back(Val >> 8);
1509 } else {
1510 AsBytes.push_back(Val >> 8);
1511 AsBytes.push_back(Val & 0xFF);
1512 }
1513 }
Daniel Dunbar4d93a4f2009-08-03 21:47:08 +00001514 // Append one extra null character, the second is automatically added by our
1515 // caller.
1516 AsBytes.push_back(0);
Daniel Dunbar91ade142009-07-23 23:41:22 +00001517
Daniel Dunbar64509b22009-07-23 22:52:48 +00001518 IsUTF16 = true;
Daniel Dunbar91ade142009-07-23 23:41:22 +00001519 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001520}
1521
1522llvm::Constant *
1523CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1524 unsigned StringLength = 0;
1525 bool isUTF16 = false;
1526 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001527 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001528 getTargetData().isLittleEndian(),
1529 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001530
Daniel Dunbar64509b22009-07-23 22:52:48 +00001531 if (llvm::Constant *C = Entry.getValue())
1532 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001533
Owen Anderson41a75022009-08-13 21:57:51 +00001534 llvm::Constant *Zero =
1535 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbard644ad62008-08-23 18:37:06 +00001536 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattneraa64ca22009-07-16 16:48:25 +00001538 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001539 if (!CFConstantStringClassRef) {
1540 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001541 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001542 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001543 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001544 // Decay array -> ptr
1545 CFConstantStringClassRef =
Owen Andersonade90fd2009-07-29 18:54:39 +00001546 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Anders Carlssonc2480a52008-11-15 18:54:24 +00001549 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001550
Mike Stump11289f42009-09-09 15:08:12 +00001551 const llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001552 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1553
Anders Carlsson157c3212009-08-16 05:55:31 +00001554 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor91f84212008-12-11 16:49:14 +00001555
Anders Carlssonb04ea612007-08-21 00:21:21 +00001556 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001557 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001558
Anders Carlssonb04ea612007-08-21 00:21:21 +00001559 // Flags.
Daniel Dunbard644ad62008-08-23 18:37:06 +00001560 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001561 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001562 llvm::ConstantInt::get(Ty, 0x07C8);
1563
Anders Carlssonb04ea612007-08-21 00:21:21 +00001564 // String pointer.
Owen Anderson41a75022009-08-13 21:57:51 +00001565 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001566
Chris Lattner3afa3e12009-07-16 05:03:48 +00001567 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001568 bool isConstant;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001569 if (isUTF16) {
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001570 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00001571 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001572 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1573 // does make plain ascii ones writable.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001574 isConstant = true;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001575 } else {
1576 Linkage = llvm::GlobalValue::PrivateLinkage;
1577 isConstant = !Features.WritableStrings;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001578 }
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001579
Mike Stump11289f42009-09-09 15:08:12 +00001580 llvm::GlobalVariable *GV =
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001581 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1582 ".str");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001583 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00001584 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1585 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001586 }
Anders Carlsson157c3212009-08-16 05:55:31 +00001587 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1588
Anders Carlssonb04ea612007-08-21 00:21:21 +00001589 // String length.
1590 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00001591 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Anders Carlssonb04ea612007-08-21 00:21:21 +00001593 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00001594 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00001595 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1596 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001597 "_unnamed_cfstring_");
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001598 if (const char *Sect = getContext().Target.getCFStringSection())
1599 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00001600 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00001602 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00001603}
Chris Lattnerfb300092007-11-28 05:34:05 +00001604
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001605llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001606CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001607 unsigned StringLength = 0;
1608 bool isUTF16 = false;
1609 llvm::StringMapEntry<llvm::Constant*> &Entry =
1610 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1611 getTargetData().isLittleEndian(),
1612 isUTF16, StringLength);
1613
1614 if (llvm::Constant *C = Entry.getValue())
1615 return C;
1616
1617 llvm::Constant *Zero =
1618 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1619 llvm::Constant *Zeros[] = { Zero, Zero };
1620
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001621 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001622 if (!ConstantStringClassRef) {
1623 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001624 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1625 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001626 llvm::Constant *GV;
1627 if (StringClass.empty())
1628 GV = CreateRuntimeVariable(Ty,
1629 Features.ObjCNonFragileABI ?
1630 "OBJC_CLASS_$_NSConstantString" :
1631 "_NSConstantStringClassReference");
1632 else {
1633 std::string str;
1634 if (Features.ObjCNonFragileABI)
1635 str = "OBJC_CLASS_$_" + StringClass;
1636 else
1637 str = "_" + StringClass + "ClassReference";
1638 GV = CreateRuntimeVariable(Ty, str);
1639 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001640 // Decay array -> ptr
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001641 ConstantStringClassRef =
1642 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001643 }
1644
1645 QualType NSTy = getContext().getNSConstantStringType();
1646
1647 const llvm::StructType *STy =
1648 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1649
1650 std::vector<llvm::Constant*> Fields(3);
1651
1652 // Class pointer.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001653 Fields[0] = ConstantStringClassRef;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001654
1655 // String pointer.
1656 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1657
1658 llvm::GlobalValue::LinkageTypes Linkage;
1659 bool isConstant;
1660 if (isUTF16) {
1661 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1662 Linkage = llvm::GlobalValue::InternalLinkage;
1663 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1664 // does make plain ascii ones writable.
1665 isConstant = true;
1666 } else {
1667 Linkage = llvm::GlobalValue::PrivateLinkage;
1668 isConstant = !Features.WritableStrings;
1669 }
1670
1671 llvm::GlobalVariable *GV =
1672 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1673 ".str");
1674 if (isUTF16) {
1675 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1676 GV->setAlignment(Align.getQuantity());
1677 }
1678 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1679
1680 // String length.
1681 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1682 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1683
1684 // The struct.
1685 C = llvm::ConstantStruct::get(STy, Fields);
1686 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1687 llvm::GlobalVariable::PrivateLinkage, C,
1688 "_unnamed_nsstring_");
1689 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001690 if (const char *Sect =
1691 Features.ObjCNonFragileABI
1692 ? getContext().Target.getNSStringNonFragileABISection()
1693 : getContext().Target.getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001694 GV->setSection(Sect);
1695 Entry.setValue(GV);
1696
1697 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001698}
1699
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001700/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001701/// string literal, properly padded to match the literal type.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001702std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001703 const ConstantArrayType *CAT =
1704 getContext().getAsConstantArrayType(E->getType());
1705 assert(CAT && "String isn't pointer or array!");
Mike Stump11289f42009-09-09 15:08:12 +00001706
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001707 // Resize the string to the right size.
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001708 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001710 if (E->isWide())
1711 RealLen *= getContext().Target.getWCharWidth()/8;
Mike Stump11289f42009-09-09 15:08:12 +00001712
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001713 std::string Str = E->getString().str();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001714 Str.resize(RealLen, '\0');
Mike Stump11289f42009-09-09 15:08:12 +00001715
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001716 return Str;
1717}
1718
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001719/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1720/// constant array for the given string literal.
1721llvm::Constant *
1722CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1723 // FIXME: This can be more efficient.
Eli Friedman49ddc5f2009-11-16 05:55:46 +00001724 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1725 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1726 if (S->isWide()) {
1727 llvm::Type *DestTy =
1728 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1729 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1730 }
1731 return C;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001732}
1733
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001734/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1735/// array for the given ObjCEncodeExpr node.
1736llvm::Constant *
1737CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1738 std::string Str;
1739 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00001740
1741 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001742}
1743
1744
Chris Lattner36fc8792008-02-11 00:02:17 +00001745/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001746static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattnerfb300092007-11-28 05:34:05 +00001747 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001748 CodeGenModule &CGM,
1749 const char *GlobalName) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001750 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00001751 llvm::Constant *C =
1752 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00001753
Chris Lattnerfb300092007-11-28 05:34:05 +00001754 // Create a global variable for this string
Rafael Espindolab7f60e32011-01-10 22:34:03 +00001755 llvm::GlobalVariable *GV =
1756 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1757 llvm::GlobalValue::PrivateLinkage,
1758 C, GlobalName);
1759 GV->setUnnamedAddr(true);
1760 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00001761}
1762
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001763/// GetAddrOfConstantString - Returns a pointer to a character array
1764/// containing the literal. This contents are exactly that of the
1765/// given string, i.e. it will not be null terminated automatically;
1766/// see GetAddrOfConstantCString. Note that whether the result is
1767/// actually a pointer to an LLVM constant depends on
1768/// Feature.WriteableStrings.
1769///
1770/// The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001771llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1772 const char *GlobalName) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001773 bool IsConstant = !Features.WritableStrings;
1774
1775 // Get the default prefix if a name wasn't specified.
1776 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00001777 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001778
1779 // Don't share any string literals if strings aren't constant.
1780 if (!IsConstant)
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001781 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump11289f42009-09-09 15:08:12 +00001782
1783 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner3afa3e12009-07-16 05:03:48 +00001784 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattnerfb300092007-11-28 05:34:05 +00001785
1786 if (Entry.getValue())
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001787 return Entry.getValue();
Chris Lattnerfb300092007-11-28 05:34:05 +00001788
1789 // Create a global variable for this.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001790 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001791 Entry.setValue(C);
1792 return C;
1793}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001794
1795/// GetAddrOfConstantCString - Returns a pointer to a character
1796/// array containing the literal and a terminating '\-'
1797/// character. The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001798llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1799 const char *GlobalName){
Chris Lattner2e41b0e2008-12-09 19:10:54 +00001800 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001801}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001802
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001803/// EmitObjCPropertyImplementations - Emit information for synthesized
1804/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00001805void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001806 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001807 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001808 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001809 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00001810
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001811 // Dynamic is just for type-checking.
1812 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1813 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1814
1815 // Determine which methods need to be implemented, some may have
1816 // been overridden. Note that ::isSynthesized is not the method
1817 // we want, that just indicates if the decl came from a
1818 // property. What we want to know is if the method is defined in
1819 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001820 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001821 CodeGenFunction(*this).GenerateObjCGetter(
1822 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001823 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001824 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001825 CodeGenFunction(*this).GenerateObjCSetter(
1826 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001827 }
1828 }
1829}
1830
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001831/// EmitObjCIvarInitializations - Emit information for ivar initialization
1832/// for an implementation.
1833void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1834 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1835 return;
1836 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1837 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1838 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1839 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1840 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1841 D->getLocation(),
1842 D->getLocation(), cxxSelector,
1843 getContext().VoidTy, 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001844 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001845 ObjCMethodDecl::Required);
1846 D->addInstanceMethod(DTORMethod);
1847 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1848
1849 II = &getContext().Idents.get(".cxx_construct");
1850 cxxSelector = getContext().Selectors.getSelector(0, &II);
1851 // The constructor returns 'self'.
1852 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1853 D->getLocation(),
1854 D->getLocation(), cxxSelector,
1855 getContext().getObjCIdType(), 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001856 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001857 ObjCMethodDecl::Required);
1858 D->addInstanceMethod(CTORMethod);
1859 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1860
1861
1862}
1863
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001864/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00001865void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001866 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00001867 I != E; ++I)
1868 EmitTopLevelDecl(*I);
1869}
1870
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001871// EmitLinkageSpec - Emit all declarations in a linkage spec.
1872void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00001873 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1874 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001875 ErrorUnsupported(LSD, "linkage spec");
1876 return;
1877 }
1878
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001879 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001880 I != E; ++I)
1881 EmitTopLevelDecl(*I);
1882}
1883
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001884/// EmitTopLevelDecl - Emit code for a single top level declaration.
1885void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1886 // If an error has occurred, stop code generation, but continue
1887 // parsing and semantic analysis (to ensure all warnings and errors
1888 // are emitted).
1889 if (Diags.hasErrorOccurred())
1890 return;
1891
Douglas Gregor70d83e22009-06-29 17:30:29 +00001892 // Ignore dependent declarations.
1893 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1894 return;
Mike Stump11289f42009-09-09 15:08:12 +00001895
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001896 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00001897 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00001898 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001899 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00001900 // Skip function templates
1901 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1902 return;
Mike Stump11289f42009-09-09 15:08:12 +00001903
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001904 EmitGlobal(cast<FunctionDecl>(D));
1905 break;
1906
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001907 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001908 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001909 break;
1910
Anders Carlssonf7475242009-04-15 15:55:24 +00001911 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001912 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00001913 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001914 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00001915 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00001916 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00001917 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00001918 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001919 case Decl::ClassTemplate:
1920 case Decl::FunctionTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00001921 case Decl::NamespaceAlias:
Douglas Gregorfec52632009-06-20 00:51:54 +00001922 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00001923 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00001924 // Skip function templates
1925 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1926 return;
1927
Anders Carlssonf7475242009-04-15 15:55:24 +00001928 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1929 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00001930 case Decl::CXXDestructor:
1931 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1932 break;
Anders Carlsson87835432009-06-11 21:22:55 +00001933
1934 case Decl::StaticAssert:
1935 // Nothing to do.
1936 break;
1937
Anders Carlssonf7475242009-04-15 15:55:24 +00001938 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00001939
Fariborz Jahanian3654e652009-03-18 22:33:24 +00001940 // Forward declarations, no (immediate) code generation.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001941 case Decl::ObjCClass:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001942 case Decl::ObjCForwardProtocol:
Chris Lattnerd18136a2009-04-01 02:36:43 +00001943 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00001944 break;
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00001945
1946 case Decl::ObjCCategory: {
1947 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
1948 if (CD->IsClassExtension() && CD->hasSynthBitfield())
1949 Context.ResetObjCLayout(CD->getClassInterface());
1950 break;
1951 }
1952
Chris Lattnerd18136a2009-04-01 02:36:43 +00001953
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001954 case Decl::ObjCProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00001955 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001956 break;
1957
1958 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001959 // Categories have properties but don't support synthesize so we
1960 // can ignore them here.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001961 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1962 break;
1963
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001964 case Decl::ObjCImplementation: {
1965 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00001966 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
1967 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001968 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001969 EmitObjCIvarInitializations(OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001970 Runtime->GenerateClass(OMD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001971 break;
Mike Stump11289f42009-09-09 15:08:12 +00001972 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001973 case Decl::ObjCMethod: {
1974 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1975 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001976 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001977 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1978 break;
1979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001981 // compatibility-alias is a directive and has no code gen.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001982 break;
1983
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001984 case Decl::LinkageSpec:
1985 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001986 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001987
1988 case Decl::FileScopeAsm: {
1989 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramerb11118b2009-12-11 13:33:18 +00001990 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00001991
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001992 const std::string &S = getModule().getModuleInlineAsm();
1993 if (S.empty())
1994 getModule().setModuleInlineAsm(AsmString);
1995 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00001996 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001997 break;
1998 }
Mike Stump11289f42009-09-09 15:08:12 +00001999
2000 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002001 // Make sure we handled everything we should, every other kind is a
2002 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2003 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002004 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2005 }
2006}
John McCall09ae0322010-07-06 23:57:41 +00002007
2008/// Turns the given pointer into a constant.
2009static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2010 const void *Ptr) {
2011 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2012 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2013 return llvm::ConstantInt::get(i64, PtrInt);
2014}
2015
2016static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2017 llvm::NamedMDNode *&GlobalMetadata,
2018 GlobalDecl D,
2019 llvm::GlobalValue *Addr) {
2020 if (!GlobalMetadata)
2021 GlobalMetadata =
2022 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2023
2024 // TODO: should we report variant information for ctors/dtors?
2025 llvm::Value *Ops[] = {
2026 Addr,
2027 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2028 };
2029 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2030}
2031
2032/// Emits metadata nodes associating all the global values in the
2033/// current module with the Decls they came from. This is useful for
2034/// projects using IR gen as a subroutine.
2035///
2036/// Since there's currently no way to associate an MDNode directly
2037/// with an llvm::GlobalValue, we create a global named metadata
2038/// with the name 'clang.global.decl.ptrs'.
2039void CodeGenModule::EmitDeclMetadata() {
2040 llvm::NamedMDNode *GlobalMetadata = 0;
2041
2042 // StaticLocalDeclMap
2043 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2044 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2045 I != E; ++I) {
2046 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2047 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2048 }
2049}
2050
2051/// Emits metadata nodes for all the local variables in the current
2052/// function.
2053void CodeGenFunction::EmitDeclMetadata() {
2054 if (LocalDeclMap.empty()) return;
2055
2056 llvm::LLVMContext &Context = getLLVMContext();
2057
2058 // Find the unique metadata ID for this name.
2059 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2060
2061 llvm::NamedMDNode *GlobalMetadata = 0;
2062
2063 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2064 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2065 const Decl *D = I->first;
2066 llvm::Value *Addr = I->second;
2067
2068 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2069 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2070 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2071 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2072 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2073 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2074 }
2075 }
2076}
Daniel Dunbar900546d2010-07-16 00:00:15 +00002077
2078///@name Custom Runtime Function Interfaces
2079///@{
2080//
2081// FIXME: These can be eliminated once we can have clients just get the required
2082// AST nodes from the builtin tables.
2083
2084llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2085 if (BlockObjectDispose)
2086 return BlockObjectDispose;
2087
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002088 // If we saw an explicit decl, use that.
2089 if (BlockObjectDisposeDecl) {
2090 return BlockObjectDispose = GetAddrOfFunction(
2091 BlockObjectDisposeDecl,
2092 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2093 }
2094
2095 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002096 const llvm::FunctionType *FTy;
2097 std::vector<const llvm::Type*> ArgTys;
2098 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2099 ArgTys.push_back(PtrToInt8Ty);
2100 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2101 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2102 return BlockObjectDispose =
2103 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2104}
2105
2106llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2107 if (BlockObjectAssign)
2108 return BlockObjectAssign;
2109
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002110 // If we saw an explicit decl, use that.
2111 if (BlockObjectAssignDecl) {
2112 return BlockObjectAssign = GetAddrOfFunction(
2113 BlockObjectAssignDecl,
2114 getTypes().GetFunctionType(BlockObjectAssignDecl));
2115 }
2116
2117 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002118 const llvm::FunctionType *FTy;
2119 std::vector<const llvm::Type*> ArgTys;
2120 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2121 ArgTys.push_back(PtrToInt8Ty);
2122 ArgTys.push_back(PtrToInt8Ty);
2123 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2124 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2125 return BlockObjectAssign =
2126 CreateRuntimeFunction(FTy, "_Block_object_assign");
2127}
2128
2129llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2130 if (NSConcreteGlobalBlock)
2131 return NSConcreteGlobalBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002132
2133 // If we saw an explicit decl, use that.
2134 if (NSConcreteGlobalBlockDecl) {
2135 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2136 NSConcreteGlobalBlockDecl,
2137 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2138 }
2139
2140 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002141 return NSConcreteGlobalBlock = CreateRuntimeVariable(
2142 PtrToInt8Ty, "_NSConcreteGlobalBlock");
2143}
2144
2145llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2146 if (NSConcreteStackBlock)
2147 return NSConcreteStackBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002148
2149 // If we saw an explicit decl, use that.
2150 if (NSConcreteStackBlockDecl) {
2151 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2152 NSConcreteStackBlockDecl,
2153 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2154 }
2155
2156 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002157 return NSConcreteStackBlock = CreateRuntimeVariable(
2158 PtrToInt8Ty, "_NSConcreteStackBlock");
2159}
2160
2161///@}