blob: a574bb6a98be2fb3a10e2bd8fe32932e60f8ee7c [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"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5fec5b02009-02-13 00:10:09 +000019#include "Mangle.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000020#include "TargetInfo.h"
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +000021#include "clang/CodeGen/BackendUtil.h"
Chandler Carruth85098242010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000023#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000028#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000030#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000031#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000032#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000033#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000034#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000035#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000036#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000037#include "llvm/LLVMContext.h"
John McCallbeec5a02010-03-06 00:35:14 +000038#include "llvm/ADT/Triple.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000039#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000040#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000042using namespace clang;
43using namespace CodeGen;
44
45
Chandler Carruthbc55fe22009-11-12 17:24:48 +000046CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000047 llvm::Module &M, const llvm::TargetData &TD,
48 Diagnostic &diags)
Chris Lattner984fac52009-03-26 05:00:52 +000049 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruthbc55fe22009-11-12 17:24:48 +000050 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000051 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000052 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
Charles Davis4e786dd2010-05-25 19:52:27 +000053 VTables(*this), Runtime(0), ABI(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000054 CFConstantStringClassRef(0), NSConstantStringClassRef(0),
55 VMContext(M.getContext()),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000056 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000057 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000058 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000059 BlockObjectAssign(0), BlockObjectDispose(0){
Daniel Dunbar8d480592008-08-11 18:12:00 +000060
Chris Lattner36376522009-03-21 07:12:05 +000061 if (!Features.ObjC1)
62 Runtime = 0;
63 else if (!Features.NeXTRuntime)
64 Runtime = CreateGNUObjCRuntime(*this);
65 else if (Features.ObjCNonFragileABI)
66 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
67 else
68 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000069
Charles Davis4e786dd2010-05-25 19:52:27 +000070 if (!Features.CPlusPlus)
71 ABI = 0;
72 else createCXXABI();
73
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000074 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson3efc6e62009-12-06 18:00:51 +000075 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattnera087ff92008-03-01 08:45:05 +000076}
77
78CodeGenModule::~CodeGenModule() {
Ted Kremenek2c674f62008-08-05 18:50:11 +000079 delete Runtime;
Charles Davis4e786dd2010-05-25 19:52:27 +000080 delete ABI;
Ted Kremenek2c674f62008-08-05 18:50:11 +000081 delete DebugInfo;
82}
83
David Chisnall481e3a82010-01-23 02:40:42 +000084void CodeGenModule::createObjCRuntime() {
85 if (!Features.NeXTRuntime)
86 Runtime = CreateGNUObjCRuntime(*this);
87 else if (Features.ObjCNonFragileABI)
88 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
89 else
90 Runtime = CreateMacObjCRuntime(*this);
91}
92
Charles Davis4e786dd2010-05-25 19:52:27 +000093void CodeGenModule::createCXXABI() {
Charles Davis95a546e2010-06-11 01:06:47 +000094 if (Context.Target.getCXXABI() == "microsoft")
95 ABI = CreateMicrosoftCXXABI(*this);
96 else
97 ABI = CreateItaniumCXXABI(*this);
Charles Davis4e786dd2010-05-25 19:52:27 +000098}
99
Ted Kremenek2c674f62008-08-05 18:50:11 +0000100void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000101 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000102 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000103 EmitCXXGlobalDtorFunc();
Daniel Dunbar8d480592008-08-11 18:12:00 +0000104 if (Runtime)
105 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
106 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000107 EmitCtorList(GlobalCtors, "llvm.global_ctors");
108 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman7fab5782008-04-18 23:43:57 +0000109 EmitAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000110 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000111
112 if (getCodeGenOpts().EmitDeclMetadata)
113 EmitDeclMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000114}
115
John McCallbeec5a02010-03-06 00:35:14 +0000116bool CodeGenModule::isTargetDarwin() const {
117 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
118}
119
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000120/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000121/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000122void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
123 bool OmitOnError) {
124 if (OmitOnError && getDiags().hasErrorOccurred())
125 return;
Mike Stump11289f42009-09-09 15:08:12 +0000126 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000127 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000128 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000129 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
130 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000131}
Chris Lattner41af8182007-12-02 06:27:33 +0000132
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000133/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000134/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000135void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
136 bool OmitOnError) {
137 if (OmitOnError && getDiags().hasErrorOccurred())
138 return;
Mike Stump11289f42009-09-09 15:08:12 +0000139 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000140 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000141 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000142 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000143}
144
Mike Stump11289f42009-09-09 15:08:12 +0000145LangOptions::VisibilityMode
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000146CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
147 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
148 if (VD->getStorageClass() == VarDecl::PrivateExtern)
149 return LangOptions::Hidden;
150
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000151 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000152 switch (attr->getVisibility()) {
153 default: assert(0 && "Unknown visibility!");
Mike Stump11289f42009-09-09 15:08:12 +0000154 case VisibilityAttr::DefaultVisibility:
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000155 return LangOptions::Default;
156 case VisibilityAttr::HiddenVisibility:
157 return LangOptions::Hidden;
158 case VisibilityAttr::ProtectedVisibility:
159 return LangOptions::Protected;
160 }
161 }
Douglas Gregor08329632010-06-15 17:05:35 +0000162
Douglas Gregor5dd34742010-06-21 18:41:26 +0000163 if (getLangOptions().CPlusPlus) {
164 // Entities subject to an explicit instantiation declaration get default
165 // visibility.
166 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
167 if (Function->getTemplateSpecializationKind()
168 == TSK_ExplicitInstantiationDeclaration)
169 return LangOptions::Default;
170 } else if (const ClassTemplateSpecializationDecl *ClassSpec
171 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
172 if (ClassSpec->getSpecializationKind()
173 == TSK_ExplicitInstantiationDeclaration)
174 return LangOptions::Default;
175 } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
176 if (Record->getTemplateSpecializationKind()
177 == TSK_ExplicitInstantiationDeclaration)
178 return LangOptions::Default;
179 } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
180 if (Var->isStaticDataMember() &&
181 (Var->getTemplateSpecializationKind()
182 == TSK_ExplicitInstantiationDeclaration))
183 return LangOptions::Default;
184 }
185
186 // If -fvisibility-inlines-hidden was provided, then inline C++ member
187 // functions get "hidden" visibility by default.
188 if (getLangOptions().InlineVisibilityHidden)
189 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
190 if (Method->isInlined())
191 return LangOptions::Hidden;
192 }
193
Anders Carlsson10d369d2010-02-07 01:44:36 +0000194 // This decl should have the same visibility as its parent.
195 if (const DeclContext *DC = D->getDeclContext())
196 return getDeclVisibilityMode(cast<Decl>(DC));
197
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000198 return getLangOptions().getVisibilityMode();
199}
200
Mike Stump11289f42009-09-09 15:08:12 +0000201void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000202 const Decl *D) const {
203 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000204 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000205 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000206 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000207 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000208
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000209 switch (getDeclVisibilityMode(D)) {
Dan Gohman75d69da2008-05-22 00:50:06 +0000210 default: assert(0 && "Unknown visibility!");
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000211 case LangOptions::Default:
212 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
213 case LangOptions::Hidden:
214 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
215 case LangOptions::Protected:
216 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
Dan Gohman75d69da2008-05-22 00:50:06 +0000217 }
218}
219
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000220llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
221 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
222
223 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
224 if (!Str.empty())
225 return Str;
226
227 if (!getMangleContext().shouldMangleDeclName(ND)) {
228 IdentifierInfo *II = ND->getIdentifier();
229 assert(II && "Attempt to mangle unnamed decl.");
230
231 Str = II->getName();
232 return Str;
233 }
234
235 llvm::SmallString<256> Buffer;
236 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
237 getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
238 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
239 getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
240 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian9b5528d2010-06-24 00:08:06 +0000241 getMangleContext().mangleBlock(GD, BD, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000242 else
243 getMangleContext().mangleName(ND, Buffer);
244
245 // Allocate space for the mangled name.
246 size_t Length = Buffer.size();
247 char *Name = MangledNamesAllocator.Allocate<char>(Length);
248 std::copy(Buffer.begin(), Buffer.end(), Name);
249
250 Str = llvm::StringRef(Name, Length);
251
252 return Str;
253}
254
Fariborz Jahanian9b5528d2010-06-24 00:08:06 +0000255void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer,
256 const BlockDecl *BD) {
257 getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer());
Anders Carlsson635186a2010-06-09 02:36:32 +0000258}
259
John McCall7ec50432010-03-19 23:29:14 +0000260llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
261 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000262}
263
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000264/// AddGlobalCtor - Add a function to the list that will be called before
265/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000266void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000267 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000268 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000269}
270
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000271/// AddGlobalDtor - Add a function to the list that will be called
272/// when the module is unloaded.
273void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000274 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000275 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
276}
277
278void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
279 // Ctor function type is void()*.
280 llvm::FunctionType* CtorFTy =
Mike Stump11289f42009-09-09 15:08:12 +0000281 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000282 std::vector<const llvm::Type*>(),
283 false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000284 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000285
286 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump11289f42009-09-09 15:08:12 +0000287 llvm::StructType* CtorStructTy =
288 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson9793f0e2009-07-29 22:16:19 +0000289 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000290
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000291 // Construct the constructor and destructor arrays.
292 std::vector<llvm::Constant*> Ctors;
293 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
294 std::vector<llvm::Constant*> S;
Mike Stump11289f42009-09-09 15:08:12 +0000295 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson41a75022009-08-13 21:57:51 +0000296 I->second, false));
Owen Andersonade90fd2009-07-29 18:54:39 +0000297 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson0e0189d2009-07-27 22:29:56 +0000298 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000299 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000300
301 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000302 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000303 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000304 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000305 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000306 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000307 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000308}
309
Nate Begeman7fab5782008-04-18 23:43:57 +0000310void CodeGenModule::EmitAnnotations() {
311 if (Annotations.empty())
312 return;
313
314 // Create a new global variable for the ConstantStruct in the Module.
315 llvm::Constant *Array =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000316 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman7fab5782008-04-18 23:43:57 +0000317 Annotations.size()),
318 Annotations);
Mike Stump11289f42009-09-09 15:08:12 +0000319 llvm::GlobalValue *gv =
320 new llvm::GlobalVariable(TheModule, Array->getType(), false,
321 llvm::GlobalValue::AppendingLinkage, Array,
Owen Andersonc10c8d32009-07-08 19:05:04 +0000322 "llvm.global.annotations");
Nate Begeman7fab5782008-04-18 23:43:57 +0000323 gv->setSection("llvm.metadata");
324}
325
Chris Lattner02e987f2009-04-14 16:44:36 +0000326static CodeGenModule::GVALinkage
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000327GetLinkageForFunction(const FunctionDecl *FD, const LangOptions &Features) {
Douglas Gregore8925db2009-06-29 22:39:32 +0000328 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000329
330 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000331 if (L == ExternalLinkage && Features.CPlusPlus &&
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332 FD->getType()->getLinkage() == UniqueExternalLinkage)
333 L = UniqueExternalLinkage;
334
335 switch (L) {
336 case NoLinkage:
337 case InternalLinkage:
338 case UniqueExternalLinkage:
339 return CodeGenModule::GVA_Internal;
Anders Carlsson781161d2009-12-10 22:25:34 +0000340
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000341 case ExternalLinkage:
342 switch (FD->getTemplateSpecializationKind()) {
343 case TSK_Undeclared:
344 case TSK_ExplicitSpecialization:
345 External = CodeGenModule::GVA_StrongExternal;
346 break;
347
348 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorb14d1232010-03-13 18:23:07 +0000349 return CodeGenModule::GVA_ExplicitTemplateInstantiation;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000350
351 case TSK_ExplicitInstantiationDeclaration:
352 case TSK_ImplicitInstantiation:
Anders Carlsson781161d2009-12-10 22:25:34 +0000353 External = CodeGenModule::GVA_TemplateInstantiation;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000354 break;
355 }
Anders Carlsson781161d2009-12-10 22:25:34 +0000356 }
Mike Stump11289f42009-09-09 15:08:12 +0000357
Douglas Gregor583dcaf2009-10-27 21:11:48 +0000358 if (!FD->isInlined())
Douglas Gregore8925db2009-06-29 22:39:32 +0000359 return External;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000360
Douglas Gregor299d76e2009-09-13 07:46:26 +0000361 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
362 // GNU or C99 inline semantics. Determine whether this symbol should be
363 // externally visible.
364 if (FD->isInlineDefinitionExternallyVisible())
365 return External;
366
367 // C99 inline semantics, where the symbol is not externally visible.
368 return CodeGenModule::GVA_C99Inline;
Chris Lattnerf8dc0732009-04-22 00:03:30 +0000369 }
Chris Lattnerbae0e682009-04-14 20:25:53 +0000370
Douglas Gregorb7e5c842009-10-27 23:26:40 +0000371 // C++0x [temp.explicit]p9:
372 // [ Note: The intent is that an inline function that is the subject of
373 // an explicit instantiation declaration will still be implicitly
374 // instantiated when used so that the body can be considered for
375 // inlining, but that no out-of-line copy of the inline function would be
376 // generated in the translation unit. -- end note ]
Rafael Espindolafa1708fd2010-03-23 19:55:22 +0000377 if (FD->getTemplateSpecializationKind()
378 == TSK_ExplicitInstantiationDeclaration)
Douglas Gregorb7e5c842009-10-27 23:26:40 +0000379 return CodeGenModule::GVA_C99Inline;
Rafael Espindola683fe4f2010-04-19 00:44:22 +0000380
Douglas Gregor299d76e2009-09-13 07:46:26 +0000381 return CodeGenModule::GVA_CXXInline;
Daniel Dunbar38932572009-04-14 08:05:55 +0000382}
383
John McCalld4324142010-02-19 01:32:20 +0000384llvm::GlobalValue::LinkageTypes
385CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000386 GVALinkage Linkage = GetLinkageForFunction(D, Features);
Daniel Dunbar38932572009-04-14 08:05:55 +0000387
Chris Lattner749b8ed2010-06-30 16:58:07 +0000388 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000389 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000390
391 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000392 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000393
394 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000395 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000396
397 // In C99 mode, 'inline' functions are guaranteed to have a strong
398 // definition somewhere else, so we can use available_externally linkage.
399 if (Linkage == GVA_C99Inline)
John McCalld4324142010-02-19 01:32:20 +0000400 return llvm::Function::AvailableExternallyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000401
402 // In C++, the compiler has to emit a definition in every translation unit
403 // that references the function. We should use linkonce_odr because
404 // a) if all references in this translation unit are optimized away, we
405 // don't need to codegen it. b) if the function persists, it needs to be
406 // merged with other definitions. c) C++ has the ODR, so we know the
407 // definition is dependable.
408 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld4324142010-02-19 01:32:20 +0000409 return llvm::Function::LinkOnceODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000410
411 // An explicit instantiation of a template has weak linkage, since
412 // explicit instantiations can occur in multiple translation units
413 // and must all be equivalent. However, we are not allowed to
414 // throw away these explicit instantiations.
415 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregorb14d1232010-03-13 18:23:07 +0000416 return llvm::Function::WeakODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000417
418 // Otherwise, we have strong external linkage.
419 assert(Linkage == GVA_StrongExternal);
420 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000421}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000422
John McCalld4324142010-02-19 01:32:20 +0000423
424/// SetFunctionDefinitionAttributes - Set attributes for a global.
425///
426/// FIXME: This is currently only done for aliases and functions, but not for
427/// variables (these details are set in EmitGlobalVarDefinition for variables).
428void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
429 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000430 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000431}
432
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000433void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000434 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000435 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000436 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000437 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000438 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel322300d2008-09-25 21:02:23 +0000439 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000440 AttributeList.size()));
441 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000442}
443
Daniel Dunbar38932572009-04-14 08:05:55 +0000444void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
445 llvm::Function *F) {
Daniel Dunbar0f3403c2009-03-02 04:58:03 +0000446 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump11289f42009-09-09 15:08:12 +0000447 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000448
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000449 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbar03a38442008-10-28 00:17:57 +0000450 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump11289f42009-09-09 15:08:12 +0000451
Mike Stump3722f582009-08-26 22:31:08 +0000452 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000453 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000454
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000455 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
456 F->addFnAttr(llvm::Attribute::StackProtect);
457 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
458 F->addFnAttr(llvm::Attribute::StackProtectReq);
459
Alexis Hunt96d5c762009-11-21 08:43:09 +0000460 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
461 unsigned width = Context.Target.getCharWidth();
462 F->setAlignment(AA->getAlignment() / width);
463 while ((AA = AA->getNext<AlignedAttr>()))
464 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
465 }
Mike Stump3472ae52009-10-05 22:49:20 +0000466 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000467 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
468 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000469}
470
Mike Stump11289f42009-09-09 15:08:12 +0000471void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000472 llvm::GlobalValue *GV) {
473 setGlobalVisibility(GV, D);
474
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000475 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000476 AddUsedGlobal(GV);
477
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000478 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000479 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000480
481 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000482}
483
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000484void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
485 llvm::Function *F,
486 const CGFunctionInfo &FI) {
487 SetLLVMFunctionAttributes(D, FI, F);
488 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000489
490 F->setLinkage(llvm::Function::InternalLinkage);
491
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000492 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000493}
494
Anders Carlsson6710c532010-02-06 02:44:09 +0000495void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000496 llvm::Function *F,
497 bool IsIncompleteFunction) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000498 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
499
Eli Friedman895771a2009-05-26 01:22:57 +0000500 if (!IsIncompleteFunction)
Anders Carlsson6710c532010-02-06 02:44:09 +0000501 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000502
Daniel Dunbar38932572009-04-14 08:05:55 +0000503 // Only a few attributes are set on declarations; these may later be
504 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000505
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000506 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000507 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000508 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000509 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000510 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000511 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000512 F->setLinkage(llvm::Function::ExternalWeakLinkage);
513 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000514 F->setLinkage(llvm::Function::ExternalLinkage);
Daniel Dunbar38932572009-04-14 08:05:55 +0000515 }
516
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000517 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000518 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000519}
520
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000521void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000522 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000523 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000524 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000525}
526
527void CodeGenModule::EmitLLVMUsed() {
528 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000529 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000530 return;
531
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000532 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000533
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000534 // Convert LLVMUsed to what ConstantArray needs.
535 std::vector<llvm::Constant*> UsedArray;
536 UsedArray.resize(LLVMUsed.size());
537 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000538 UsedArray[i] =
539 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Anderson170229f2009-07-14 23:10:40 +0000540 i8PTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000541 }
Mike Stump11289f42009-09-09 15:08:12 +0000542
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000543 if (UsedArray.empty())
544 return;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000545 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000546
547 llvm::GlobalVariable *GV =
548 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000549 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000550 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000551 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000552
553 GV->setSection("llvm.metadata");
554}
555
556void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000557 // Emit code for any potentially referenced deferred decls. Since a
558 // previously unused static decl may become used during the generation of code
559 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000560
Anders Carlsson11e51402010-04-17 20:15:18 +0000561 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
562 if (!DeferredVTables.empty()) {
563 const CXXRecordDecl *RD = DeferredVTables.back();
564 DeferredVTables.pop_back();
565 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000566 continue;
567 }
568
Anders Carlssondae1abc2009-05-05 04:44:02 +0000569 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000570 DeferredDeclsToEmit.pop_back();
571
John McCallc2af9392010-05-27 01:45:30 +0000572 // Check to see if we've already emitted this. This is necessary
573 // for a couple of reasons: first, decls can end up in the
574 // deferred-decls queue multiple times, and second, decls can end
575 // up with definitions in unusual ways (e.g. by an extern inline
576 // function acquiring a strong function redefinition). Just
577 // ignore these cases.
578 //
579 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000580 llvm::StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000581 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000582 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000583
Chris Lattner45470942009-03-21 09:44:56 +0000584 if (!CGRef->isDeclaration())
585 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000586
John McCallc2af9392010-05-27 01:45:30 +0000587 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
588 // purposes an alias counts as a definition.
589 if (isa<llvm::GlobalAlias>(CGRef))
590 continue;
591
Chris Lattner45470942009-03-21 09:44:56 +0000592 // Otherwise, emit the definition and move on to the next one.
593 EmitGlobalDefinition(D);
594 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000595}
Chris Lattner09153c02007-06-22 18:48:09 +0000596
Mike Stump11289f42009-09-09 15:08:12 +0000597/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begemanfaae0812008-04-19 04:17:09 +0000598/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump11289f42009-09-09 15:08:12 +0000599/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
600/// GlobalValue being annotated. The second field is the constant string
601/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begemanfaae0812008-04-19 04:17:09 +0000602/// string containing the name of the translation unit. The fourth field is
603/// the line number in the file of the annotated value declaration.
604///
605/// FIXME: this does not unique the annotation string constants, as llvm-gcc
606/// appears to.
607///
Mike Stump11289f42009-09-09 15:08:12 +0000608llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000609 const AnnotateAttr *AA,
610 unsigned LineNo) {
611 llvm::Module *M = &getModule();
612
613 // get [N x i8] constants for the annotation string, and the filename string
614 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000615 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000616 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000617 AA->getAnnotation(), true);
618 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
619 M->getModuleIdentifier(),
Nate Begemanfaae0812008-04-19 04:17:09 +0000620 true);
621
622 // Get the two global values corresponding to the ConstantArrays we just
623 // created to hold the bytes of the strings.
Mike Stump11289f42009-09-09 15:08:12 +0000624 llvm::GlobalValue *annoGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000625 new llvm::GlobalVariable(*M, anno->getType(), false,
626 llvm::GlobalValue::PrivateLinkage, anno,
627 GV->getName());
Nate Begemanfaae0812008-04-19 04:17:09 +0000628 // translation unit name string, emitted into the llvm.metadata section.
629 llvm::GlobalValue *unitGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000630 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump11289f42009-09-09 15:08:12 +0000631 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner3afa3e12009-07-16 05:03:48 +0000632 ".str");
Nate Begemanfaae0812008-04-19 04:17:09 +0000633
Daniel Dunbar346892a2009-04-14 22:41:13 +0000634 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000635 llvm::Constant *Fields[4] = {
Owen Andersonade90fd2009-07-29 18:54:39 +0000636 llvm::ConstantExpr::getBitCast(GV, SBP),
637 llvm::ConstantExpr::getBitCast(annoGV, SBP),
638 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson41a75022009-08-13 21:57:51 +0000639 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begemanfaae0812008-04-19 04:17:09 +0000640 };
Owen Anderson758428f2009-08-05 23:18:46 +0000641 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begemanfaae0812008-04-19 04:17:09 +0000642}
643
Eli Friedmanc96b2492010-06-19 06:24:06 +0000644static CodeGenModule::GVALinkage
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000645GetLinkageForVariable(const VarDecl *VD, const LangOptions &Features) {
Eli Friedmanc96b2492010-06-19 06:24:06 +0000646 // If this is a static data member, compute the kind of template
647 // specialization. Otherwise, this variable is not part of a
648 // template.
649 TemplateSpecializationKind TSK = TSK_Undeclared;
650 if (VD->isStaticDataMember())
651 TSK = VD->getTemplateSpecializationKind();
652
653 Linkage L = VD->getLinkage();
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000654 if (L == ExternalLinkage && Features.CPlusPlus &&
Eli Friedmanc96b2492010-06-19 06:24:06 +0000655 VD->getType()->getLinkage() == UniqueExternalLinkage)
656 L = UniqueExternalLinkage;
657
658 switch (L) {
659 case NoLinkage:
660 case InternalLinkage:
661 case UniqueExternalLinkage:
662 return CodeGenModule::GVA_Internal;
663
664 case ExternalLinkage:
665 switch (TSK) {
666 case TSK_Undeclared:
667 case TSK_ExplicitSpecialization:
668 return CodeGenModule::GVA_StrongExternal;
669
670 case TSK_ExplicitInstantiationDeclaration:
671 llvm_unreachable("Variable should not be instantiated");
672 // Fall through to treat this like any other instantiation.
673
674 case TSK_ExplicitInstantiationDefinition:
675 return CodeGenModule::GVA_ExplicitTemplateInstantiation;
676
677 case TSK_ImplicitInstantiation:
678 return CodeGenModule::GVA_TemplateInstantiation;
679 }
680 }
681
682 return CodeGenModule::GVA_StrongExternal;
683}
684
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000685bool clang::DeclIsRequiredFunctionOrFileScopedVar(const Decl *D) {
686 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
687 if (!VD->isFileVarDecl())
688 return false;
689 } else if (!isa<FunctionDecl>(D))
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000690 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000691
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000692 // Aliases and used decls are required.
693 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
694 return true;
695
696 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
697 // Forward declarations aren't required.
698 if (!FD->isThisDeclarationADefinition())
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000699 return false;
700
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000701 // Constructors and destructors are required.
702 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
703 return true;
704
705 ASTContext &Ctx = FD->getASTContext();
706
707 // The key function for a class is required.
708 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Eli Friedmanf2c79b62009-12-08 03:56:49 +0000709 const CXXRecordDecl *RD = MD->getParent();
710 if (MD->isOutOfLine() && RD->isDynamicClass()) {
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000711 const CXXMethodDecl *KeyFunc = Ctx.getKeyFunction(RD);
712 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
713 return true;
Eli Friedmanf2c79b62009-12-08 03:56:49 +0000714 }
715 }
716
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000717 CodeGenModule::GVALinkage Linkage
718 = GetLinkageForFunction(FD, Ctx.getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattner92028da2009-04-14 06:44:48 +0000720 // static, static inline, always_inline, and extern inline functions can
Chris Lattner02e987f2009-04-14 16:44:36 +0000721 // always be deferred. Normal inline functions can be deferred in C99/C++.
Douglas Gregorb14d1232010-03-13 18:23:07 +0000722 // Implicit template instantiations can also be deferred in C++.
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000723 if (Linkage == CodeGenModule::GVA_Internal ||
724 Linkage == CodeGenModule::GVA_C99Inline ||
725 Linkage == CodeGenModule::GVA_CXXInline ||
726 Linkage == CodeGenModule::GVA_TemplateInstantiation)
727 return false;
728 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000729 }
Mike Stump11289f42009-09-09 15:08:12 +0000730
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000731 const VarDecl *VD = cast<VarDecl>(D);
732 assert(VD->isFileVarDecl() && "Expected file scoped var");
Douglas Gregorbeecd582009-04-21 17:11:58 +0000733
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000734 // Structs that have non-trivial constructors or destructors are required.
735
Anders Carlssona18ed9b2009-10-08 17:28:59 +0000736 // FIXME: Handle references.
737 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
738 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
739 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000740 return true;
Anders Carlssona18ed9b2009-10-08 17:28:59 +0000741 }
742 }
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000743
744 ASTContext &Ctx = VD->getASTContext();
745
746 CodeGenModule::GVALinkage L = GetLinkageForVariable(VD, Ctx.getLangOptions());
747 if (L == CodeGenModule::GVA_Internal ||
748 L == CodeGenModule::GVA_TemplateInstantiation) {
749 if (!(VD->getInit() && VD->getInit()->HasSideEffects(Ctx)))
750 return false;
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +0000751 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000752
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +0000753 return true;
754}
755
756bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
757 // Never defer when EmitAllDecls is specified.
758 if (Features.EmitAllDecls)
759 return false;
760
761 return !DeclIsRequiredFunctionOrFileScopedVar(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000762}
763
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000764llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
765 const AliasAttr *AA = VD->getAttr<AliasAttr>();
766 assert(AA && "No alias?");
767
768 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
769
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000770 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000771 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000772
773 llvm::Constant *Aliasee;
774 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +0000775 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000776 else
John McCall7ec50432010-03-19 23:29:14 +0000777 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000778 llvm::PointerType::getUnqual(DeclTy), 0);
779 if (!Entry) {
780 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
781 F->setLinkage(llvm::Function::ExternalWeakLinkage);
782 WeakRefReferences.insert(F);
783 }
784
785 return Aliasee;
786}
787
Chris Lattnere0be0df2009-05-12 21:21:08 +0000788void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000789 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000790
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000791 // Weak references don't produce any output by themselves.
792 if (Global->hasAttr<WeakRefAttr>())
793 return;
794
Chris Lattner54041692009-03-22 21:47:11 +0000795 // If this is an alias definition (which otherwise looks like a declaration)
796 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000797 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000798 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000799
Chris Lattner45470942009-03-21 09:44:56 +0000800 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000801 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000802 if (FD->getIdentifier()) {
803 llvm::StringRef Name = FD->getName();
804 if (Name == "_Block_object_assign") {
805 BlockObjectAssignDecl = FD;
806 } else if (Name == "_Block_object_dispose") {
807 BlockObjectDisposeDecl = FD;
808 }
809 }
810
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000811 // Forward declarations are emitted lazily on first use.
812 if (!FD->isThisDeclarationADefinition())
813 return;
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000814 } else {
815 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000816 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
817
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000818 if (VD->getIdentifier()) {
819 llvm::StringRef Name = VD->getName();
820 if (Name == "_NSConcreteGlobalBlock") {
821 NSConcreteGlobalBlockDecl = VD;
822 } else if (Name == "_NSConcreteStackBlock") {
823 NSConcreteStackBlockDecl = VD;
824 }
825 }
826
827
Douglas Gregor61f6db52010-02-06 05:15:45 +0000828 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000829 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000830 }
831
Chris Lattner45470942009-03-21 09:44:56 +0000832 // Defer code generation when possible if this is a static definition, inline
833 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000834 if (!MayDeferGeneration(Global)) {
835 // Emit the definition if it can't be deferred.
836 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000837 return;
838 }
John McCall70013b62010-07-15 23:40:35 +0000839
840 // If we're deferring emission of a C++ variable with an
841 // initializer, remember the order in which it appeared in the file.
842 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
843 cast<VarDecl>(Global)->hasInit()) {
844 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
845 CXXGlobalInits.push_back(0);
846 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000847
848 // If the value has already been used, add it directly to the
849 // DeferredDeclsToEmit list.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000850 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000851 if (GetGlobalValue(MangledName))
852 DeferredDeclsToEmit.push_back(GD);
853 else {
854 // Otherwise, remember that we saw a deferred decl with this name. The
855 // first use of the mangled name will cause it to move into
856 // DeferredDeclsToEmit.
857 DeferredDecls[MangledName] = GD;
858 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000859}
860
Chris Lattnere0be0df2009-05-12 21:21:08 +0000861void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000862 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000863
Dan Gohman145f3f12010-04-19 16:39:44 +0000864 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000865 Context.getSourceManager(),
866 "Generating code for declaration");
867
Douglas Gregora700f682010-07-13 06:02:28 +0000868 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
869 // At -O0, don't generate IR for functions with available_externally
870 // linkage.
Douglas Gregor89976902010-07-15 22:58:18 +0000871 if (CodeGenOpts.OptimizationLevel == 0 &&
872 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregora700f682010-07-13 06:02:28 +0000873 getFunctionLinkage(Function)
874 == llvm::Function::AvailableExternallyLinkage)
875 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000876
Douglas Gregora700f682010-07-13 06:02:28 +0000877 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
878 if (Method->isVirtual())
879 getVTables().EmitThunks(GD);
880
881 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
882 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000883
Douglas Gregora700f682010-07-13 06:02:28 +0000884 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
885 return EmitCXXDestructor(DD, GD.getDtorType());
886 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000887
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000888 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000889 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000890
891 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
892 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000893
894 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000895}
896
Chris Lattnerd4808922009-03-22 21:03:39 +0000897/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
898/// module, create and return an llvm Function with the specified type. If there
899/// is something in the module with the specified name, return it potentially
900/// bitcasted to the right type.
901///
902/// If D is non-null, it specifies a decl that correspond to this. This is used
903/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000904llvm::Constant *
905CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
906 const llvm::Type *Ty,
907 GlobalDecl D) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000908 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000909 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000910 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000911 if (WeakRefReferences.count(Entry)) {
912 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
913 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000914 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000915
916 WeakRefReferences.erase(Entry);
917 }
918
Chris Lattnera85d68e2009-03-21 09:25:43 +0000919 if (Entry->getType()->getElementType() == Ty)
920 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000921
Chris Lattnera85d68e2009-03-21 09:25:43 +0000922 // Make sure the result is of the correct type.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000923 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Andersonade90fd2009-07-29 18:54:39 +0000924 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
Eli Friedmancc522d92009-11-09 05:07:37 +0000927 // This function doesn't have a complete type (for example, the return
928 // type is an incomplete struct). Use a fake type instead, and make
929 // sure not to try to set attributes.
930 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +0000931
932 const llvm::FunctionType *FTy;
933 if (isa<llvm::FunctionType>(Ty)) {
934 FTy = cast<llvm::FunctionType>(Ty);
935 } else {
936 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
937 std::vector<const llvm::Type*>(), false);
Eli Friedmancc522d92009-11-09 05:07:37 +0000938 IsIncompleteFunction = true;
939 }
Chris Lattner5c740f12010-06-30 19:14:05 +0000940
John McCalld06fb862010-04-28 00:00:30 +0000941 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +0000942 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000943 MangledName, &getModule());
944 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +0000945 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +0000946 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedmancc522d92009-11-09 05:07:37 +0000947
Chris Lattner45470942009-03-21 09:44:56 +0000948 // This is the first use or definition of a mangled name. If there is a
949 // deferred decl with this name, remember that we need to emit it at the end
950 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000951 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000952 if (DDI != DeferredDecls.end()) {
953 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
954 // list, and remove it from DeferredDecls (since we don't need it anymore).
955 DeferredDeclsToEmit.push_back(DDI->second);
956 DeferredDecls.erase(DDI);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000957 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
Chris Lattnerd035ebd2009-05-12 21:02:27 +0000958 // If this the first reference to a C++ inline function in a class, queue up
959 // the deferred function body for emission. These are not seen as
960 // top-level declarations.
Chris Lattnere0be0df2009-05-12 21:21:08 +0000961 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
962 DeferredDeclsToEmit.push_back(D);
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000963 // A called constructor which has no definition or declaration need be
964 // synthesized.
965 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Rafael Espindola70e040d2010-03-02 21:28:26 +0000966 if (CD->isImplicit()) {
Benjamin Kramerf0a0f682010-03-06 09:07:19 +0000967 assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
Eli Friedman84a7e342009-11-26 07:40:08 +0000968 DeferredDeclsToEmit.push_back(D);
Rafael Espindola70e040d2010-03-02 21:28:26 +0000969 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000970 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
Rafael Espindola70e040d2010-03-02 21:28:26 +0000971 if (DD->isImplicit()) {
Benjamin Kramerf0a0f682010-03-06 09:07:19 +0000972 assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
Eli Friedman84a7e342009-11-26 07:40:08 +0000973 DeferredDeclsToEmit.push_back(D);
Rafael Espindola70e040d2010-03-02 21:28:26 +0000974 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000975 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Rafael Espindola70e040d2010-03-02 21:28:26 +0000976 if (MD->isCopyAssignment() && MD->isImplicit()) {
Benjamin Kramerf0a0f682010-03-06 09:07:19 +0000977 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000978 DeferredDeclsToEmit.push_back(D);
Rafael Espindola70e040d2010-03-02 21:28:26 +0000979 }
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000980 }
Chris Lattner45470942009-03-21 09:44:56 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
John McCalld06fb862010-04-28 00:00:30 +0000983 // Make sure the result is of the requested type.
984 if (!IsIncompleteFunction) {
985 assert(F->getType()->getElementType() == Ty);
986 return F;
987 }
988
989 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
990 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000991}
992
Chris Lattnerd4808922009-03-22 21:03:39 +0000993/// GetAddrOfFunction - Return the address of the given function. If Ty is
994/// non-null, then this function will use the specified type if it has to
995/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +0000996llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattnerd4808922009-03-22 21:03:39 +0000997 const llvm::Type *Ty) {
998 // If there was no specific requested type, just convert it now.
999 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001000 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001001
Anders Carlssonea836bc2010-06-22 16:16:50 +00001002 llvm::StringRef MangledName = getMangledName(GD);
John McCall7ec50432010-03-19 23:29:14 +00001003 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattnerd4808922009-03-22 21:03:39 +00001004}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001005
Chris Lattnerd4808922009-03-22 21:03:39 +00001006/// CreateRuntimeFunction - Create a new runtime function with the specified
1007/// type and name.
1008llvm::Constant *
1009CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCall7ec50432010-03-19 23:29:14 +00001010 llvm::StringRef Name) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001011 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattnerd4808922009-03-22 21:03:39 +00001012}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001013
Eli Friedmanb095e152009-12-11 21:23:03 +00001014static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall340aafa2010-02-08 21:46:50 +00001015 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001016 return false;
1017 if (Context.getLangOptions().CPlusPlus &&
1018 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
1019 // FIXME: We should do something fancier here!
1020 return false;
1021 }
1022 return true;
1023}
1024
Chris Lattnerd4808922009-03-22 21:03:39 +00001025/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1026/// create and return an llvm GlobalVariable with the specified type. If there
1027/// is something in the module with the specified name, return it potentially
1028/// bitcasted to the right type.
1029///
1030/// If D is non-null, it specifies a decl that correspond to this. This is used
1031/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001032llvm::Constant *
1033CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
1034 const llvm::PointerType *Ty,
1035 const VarDecl *D) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001036 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001037 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001038 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001039 if (WeakRefReferences.count(Entry)) {
1040 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001041 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001042
1043 WeakRefReferences.erase(Entry);
1044 }
1045
Chris Lattnerd4808922009-03-22 21:03:39 +00001046 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001047 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001048
Chris Lattner3bfce182009-03-21 08:03:33 +00001049 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +00001050 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Chris Lattner45470942009-03-21 09:44:56 +00001053 // This is the first use or definition of a mangled name. If there is a
1054 // deferred decl with this name, remember that we need to emit it at the end
1055 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001056 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001057 if (DDI != DeferredDecls.end()) {
1058 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1059 // list, and remove it from DeferredDecls (since we don't need it anymore).
1060 DeferredDeclsToEmit.push_back(DDI->second);
1061 DeferredDecls.erase(DDI);
1062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
1064 llvm::GlobalVariable *GV =
1065 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +00001066 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001067 0, MangledName, 0,
Eli Friedman4f856742009-04-19 21:05:03 +00001068 false, Ty->getAddressSpace());
Chris Lattner3bfce182009-03-21 08:03:33 +00001069
1070 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001071 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001072 // FIXME: This code is overly simple and should be merged with other global
1073 // handling.
Eli Friedmanb095e152009-12-11 21:23:03 +00001074 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner3bfce182009-03-21 08:03:33 +00001075
Chris Lattnerd4808922009-03-22 21:03:39 +00001076 // FIXME: Merge with other attribute handling code.
1077 if (D->getStorageClass() == VarDecl::PrivateExtern)
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001078 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Chris Lattner3bfce182009-03-21 08:03:33 +00001079
Mike Stump11289f42009-09-09 15:08:12 +00001080 if (D->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001081 D->hasAttr<WeakImportAttr>())
Chris Lattnerd4808922009-03-22 21:03:39 +00001082 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Eli Friedman4f856742009-04-19 21:05:03 +00001083
1084 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +00001085 }
Mike Stump11289f42009-09-09 15:08:12 +00001086
John McCall7ec50432010-03-19 23:29:14 +00001087 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001088}
1089
Chris Lattnerd4808922009-03-22 21:03:39 +00001090
1091/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1092/// given global variable. If Ty is non-null and if the global doesn't exist,
1093/// then it will be greated with the specified type instead of whatever the
1094/// normal requested type would be.
1095llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1096 const llvm::Type *Ty) {
1097 assert(D->hasGlobalStorage() && "Not a global variable");
1098 QualType ASTTy = D->getType();
1099 if (Ty == 0)
1100 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001101
1102 const llvm::PointerType *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001103 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCall7ec50432010-03-19 23:29:14 +00001104
Anders Carlssonea836bc2010-06-22 16:16:50 +00001105 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001106 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001107}
1108
1109/// CreateRuntimeVariable - Create a new runtime global variable with the
1110/// specified type and name.
1111llvm::Constant *
1112CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCall7ec50432010-03-19 23:29:14 +00001113 llvm::StringRef Name) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001114 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
Chris Lattnerd4808922009-03-22 21:03:39 +00001115}
1116
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001117void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1118 assert(!D->getInit() && "Cannot emit definite definitions here!");
1119
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001120 if (MayDeferGeneration(D)) {
1121 // If we have not seen a reference to this variable yet, place it
1122 // into the deferred declarations table to be emitted if needed
1123 // later.
Anders Carlssonea836bc2010-06-22 16:16:50 +00001124 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001125 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001126 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001127 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001128 }
1129 }
1130
1131 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001132 EmitGlobalVarDefinition(D);
1133}
1134
Douglas Gregor88d292c2010-05-13 16:44:06 +00001135void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1136 if (DefinitionRequired)
1137 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1138}
1139
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001140llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001141CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregor2a34df32010-01-06 22:00:56 +00001142 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1143 return llvm::GlobalVariable::InternalLinkage;
1144
1145 if (const CXXMethodDecl *KeyFunction
1146 = RD->getASTContext().getKeyFunction(RD)) {
1147 // If this class has a key function, use that to determine the linkage of
1148 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001149 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001150 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001151 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001152
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001153 switch (KeyFunction->getTemplateSpecializationKind()) {
1154 case TSK_Undeclared:
1155 case TSK_ExplicitSpecialization:
1156 if (KeyFunction->isInlined())
1157 return llvm::GlobalVariable::WeakODRLinkage;
1158
1159 return llvm::GlobalVariable::ExternalLinkage;
1160
1161 case TSK_ImplicitInstantiation:
1162 case TSK_ExplicitInstantiationDefinition:
1163 return llvm::GlobalVariable::WeakODRLinkage;
1164
1165 case TSK_ExplicitInstantiationDeclaration:
1166 // FIXME: Use available_externally linkage. However, this currently
1167 // breaks LLVM's build due to undefined symbols.
1168 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1169 return llvm::GlobalVariable::WeakODRLinkage;
1170 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001171 }
1172
1173 switch (RD->getTemplateSpecializationKind()) {
1174 case TSK_Undeclared:
1175 case TSK_ExplicitSpecialization:
1176 case TSK_ImplicitInstantiation:
1177 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001178 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor2a34df32010-01-06 22:00:56 +00001179
1180 case TSK_ExplicitInstantiationDeclaration:
1181 // FIXME: Use available_externally linkage. However, this currently
1182 // breaks LLVM's build due to undefined symbols.
1183 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1184 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001185 }
1186
1187 // Silence GCC warning.
1188 return llvm::GlobalVariable::WeakODRLinkage;
1189}
1190
Ken Dyck98ca7942010-01-26 13:48:07 +00001191CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1192 return CharUnits::fromQuantity(
1193 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1194}
1195
Daniel Dunbar9c426522008-07-29 23:18:29 +00001196void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001197 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001198 QualType ASTTy = D->getType();
Eli Friedman5866fe32010-01-08 00:50:11 +00001199 bool NonConstInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001200
Sebastian Redl5ca79842010-02-01 20:16:42 +00001201 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlssonca4a5452010-01-26 17:43:42 +00001202
1203 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001204 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001205 // implicitly initialized with { 0 }.
1206 //
1207 // Note that tentative definitions are only emitted at the end of
1208 // a translation unit, so they should never have incomplete
1209 // type. In addition, EmitTentativeDefinition makes sure that we
1210 // never attempt to emit a tentative definition if a real one
1211 // exists. A use may still exists, however, so we still may need
1212 // to do a RAUW.
1213 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001214 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001215 } else {
Douglas Gregord450f062010-05-05 20:15:55 +00001216 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman719ed1a2009-02-20 01:18:21 +00001217 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001218 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001219 if (D->getType()->isReferenceType())
1220 T = D->getType();
1221
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001222 if (getLangOptions().CPlusPlus) {
Eli Friedman5866fe32010-01-08 00:50:11 +00001223 EmitCXXGlobalVarDeclInitFunc(D);
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001224 Init = EmitNullConstant(T);
Eli Friedman5866fe32010-01-08 00:50:11 +00001225 NonConstInit = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001226 } else {
1227 ErrorUnsupported(D, "static initializer");
1228 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1229 }
John McCall70013b62010-07-15 23:40:35 +00001230 } else {
1231 // We don't need an initializer, so remove the entry for the delayed
1232 // initializer position (just in case this entry was delayed).
1233 if (getLangOptions().CPlusPlus)
1234 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001235 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001236 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001237
Chris Lattner64c55932009-03-21 08:13:05 +00001238 const llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001239 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Chris Lattner149927c2009-03-21 09:16:30 +00001241 // Strip off a bitcast if we got one back.
1242 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001243 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1244 // all zero index gep.
1245 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001246 Entry = CE->getOperand(0);
1247 }
Mike Stump11289f42009-09-09 15:08:12 +00001248
Chris Lattner149927c2009-03-21 09:16:30 +00001249 // Entry is now either a Function or GlobalVariable.
1250 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001251
Chris Lattner149927c2009-03-21 09:16:30 +00001252 // We have a definition after a declaration with the wrong type.
1253 // We must make a new GlobalVariable* and update everything that used OldGV
1254 // (a declaration or tentative definition) with the new GlobalVariable*
1255 // (which will be a definition).
1256 //
1257 // This happens if there is a prototype for a global (e.g.
1258 // "extern int x[];") and then a definition of a different type (e.g.
1259 // "int x[10];"). This also happens when an initializer has a different type
1260 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001261 if (GV == 0 ||
1262 GV->getType()->getElementType() != InitType ||
1263 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump11289f42009-09-09 15:08:12 +00001264
John McCall7ec50432010-03-19 23:29:14 +00001265 // Move the old entry aside so that we'll create a new one.
1266 Entry->setName(llvm::StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001267
Chris Lattner149927c2009-03-21 09:16:30 +00001268 // Make a new global with the correct type, this is now guaranteed to work.
1269 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001270
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001271 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001272 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001273 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001274 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001275
1276 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001277 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001278 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001279
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001280 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +00001281 SourceManager &SM = Context.getSourceManager();
1282 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +00001283 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begemanfaae0812008-04-19 04:17:09 +00001284 }
1285
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001286 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001287
1288 // If it is safe to mark the global 'constant', do so now.
1289 GV->setConstant(false);
Eli Friedman5866fe32010-01-08 00:50:11 +00001290 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnerf49573d2009-08-05 05:20:29 +00001291 GV->setConstant(true);
Mike Stump11289f42009-09-09 15:08:12 +00001292
Ken Dyck160146e2010-01-27 17:10:57 +00001293 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Eli Friedman174d9c22008-05-29 11:10:27 +00001294
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001295 // Set the llvm linkage type as appropriate.
Argyrios Kyrtzidis4fac2802010-07-27 22:01:17 +00001296 GVALinkage Linkage = GetLinkageForVariable(D, Features);
Douglas Gregor819c3dd2009-10-14 21:36:34 +00001297 if (Linkage == GVA_Internal)
Chris Lattnerbc22b5b2008-05-04 01:44:26 +00001298 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001299 else if (D->hasAttr<DLLImportAttr>())
Chris Lattner84966392008-03-03 03:28:21 +00001300 GV->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001301 else if (D->hasAttr<DLLExportAttr>())
Chris Lattner84966392008-03-03 03:28:21 +00001302 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001303 else if (D->hasAttr<WeakAttr>()) {
1304 if (GV->isConstant())
1305 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1306 else
1307 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Douglas Gregorb14d1232010-03-13 18:23:07 +00001308 } else if (Linkage == GVA_TemplateInstantiation ||
1309 Linkage == GVA_ExplicitTemplateInstantiation)
1310 // FIXME: It seems like we can provide more specific linkage here
1311 // (LinkOnceODR, WeakODR).
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001312 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Daniel Dunbar2c11cd12009-11-30 08:40:34 +00001313 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
Chris Lattnerc0693bc2009-08-05 04:56:58 +00001314 !D->hasExternalStorage() && !D->getInit() &&
Chris Lattnerf49573d2009-08-05 05:20:29 +00001315 !D->getAttr<SectionAttr>()) {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001316 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001317 // common vars aren't constant even if declared const.
1318 GV->setConstant(false);
1319 } else
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001320 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001321
Daniel Dunbar38932572009-04-14 08:05:55 +00001322 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001323
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001324 // Emit global variable debug information.
Chris Lattner64c55932009-03-21 08:13:05 +00001325 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +00001326 DI->setLocation(D->getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001327 DI->EmitGlobalVariable(GV, D);
1328 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001329}
Chris Lattner09153c02007-06-22 18:48:09 +00001330
Chris Lattner36797ab2009-05-05 06:16:31 +00001331/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1332/// implement a function with no prototype, e.g. "int foo() {}". If there are
1333/// existing call uses of the old function in the module, this adjusts them to
1334/// call the new function directly.
1335///
1336/// This is not just a cleanup: the always_inline pass requires direct calls to
1337/// functions to be able to inline them. If there is a bitcast in the way, it
1338/// won't inline them. Instcombine normally deletes these calls, but it isn't
1339/// run at -O0.
1340static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1341 llvm::Function *NewFn) {
1342 // If we're redefining a global as a function, don't transform it.
1343 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1344 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001345
Chris Lattner36797ab2009-05-05 06:16:31 +00001346 const llvm::Type *NewRetTy = NewFn->getReturnType();
1347 llvm::SmallVector<llvm::Value*, 4> ArgList;
1348
1349 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001350 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001351 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001352 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1353 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greifd394aec2010-04-10 03:45:50 +00001354 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001355 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattner36797ab2009-05-05 06:16:31 +00001357 // If the return types don't match exactly, and if the call isn't dead, then
1358 // we can't transform this call.
1359 if (CI->getType() != NewRetTy && !CI->use_empty())
1360 continue;
1361
1362 // If the function was passed too few arguments, don't transform. If extra
1363 // arguments were passed, we silently drop them. If any of the types
1364 // mismatch, we don't transform.
1365 unsigned ArgNo = 0;
1366 bool DontTransform = false;
1367 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1368 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001369 if (CS.arg_size() == ArgNo ||
1370 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001371 DontTransform = true;
1372 break;
1373 }
1374 }
1375 if (DontTransform)
1376 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001377
Chris Lattner36797ab2009-05-05 06:16:31 +00001378 // Okay, we can transform this. Create the new call instruction and copy
1379 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001380 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattner36797ab2009-05-05 06:16:31 +00001381 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1382 ArgList.end(), "", CI);
1383 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001384 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001385 NewCall->takeName(CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001386 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001387 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001388
1389 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001390 if (!CI->use_empty())
1391 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001392
Chris Lattnere675d0f2010-04-01 06:31:43 +00001393 // Copy debug location attached to CI.
1394 if (!CI->getDebugLoc().isUnknown())
1395 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001396 CI->eraseFromParent();
1397 }
1398}
1399
Daniel Dunbar9c426522008-07-29 23:18:29 +00001400
Chris Lattnere0be0df2009-05-12 21:21:08 +00001401void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001402 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +00001403 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Fariborz Jahanian9eba9df2010-03-04 01:02:03 +00001404 getMangleContext().mangleInitDiscriminator();
Chris Lattnereb7466d2009-05-12 20:58:15 +00001405 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001406 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattnera85d68e2009-03-21 09:25:43 +00001408 // Strip off a bitcast if we got one back.
1409 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1410 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1411 Entry = CE->getOperand(0);
1412 }
Mike Stump11289f42009-09-09 15:08:12 +00001413
1414
Chris Lattnera85d68e2009-03-21 09:25:43 +00001415 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001416 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001417
Daniel Dunbar99d28352009-03-09 23:53:08 +00001418 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001419 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001420 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001421
Chris Lattner5eaee562009-03-21 08:38:50 +00001422 // F is the Function* for the one with the wrong type, we must make a new
1423 // Function* and update everything that used F (a declaration) with the new
1424 // Function* (which will be a definition).
1425 //
1426 // This happens if there is a prototype for a function
1427 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001428 // (e.g. "int f(int x)"). Move the old function aside so that it
1429 // doesn't interfere with GetAddrOfFunction.
1430 OldFn->setName(llvm::StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001431 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001432
Chris Lattner36797ab2009-05-05 06:16:31 +00001433 // If this is an implementation of a function without a prototype, try to
1434 // replace any existing uses of the function (which may be calls) with uses
1435 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001436 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001437 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001438 OldFn->removeDeadConstantUsers();
1439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
Chris Lattner5eaee562009-03-21 08:38:50 +00001441 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001442 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001443 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001444 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001445 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1446 }
Mike Stump11289f42009-09-09 15:08:12 +00001447
Chris Lattner5eaee562009-03-21 08:38:50 +00001448 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001449 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001450
Chris Lattnera85d68e2009-03-21 09:25:43 +00001451 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001452 }
Mike Stump11289f42009-09-09 15:08:12 +00001453
Chris Lattnera85d68e2009-03-21 09:25:43 +00001454 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001455 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001456
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001457 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001458
Daniel Dunbar38932572009-04-14 08:05:55 +00001459 SetFunctionDefinitionAttributes(D, Fn);
1460 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001462 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001463 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001464 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001465 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar9c426522008-07-29 23:18:29 +00001466}
1467
John McCall7ec50432010-03-19 23:29:14 +00001468void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1469 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001470 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001471 assert(AA && "Not an alias?");
1472
Anders Carlssonea836bc2010-06-22 16:16:50 +00001473 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001474
John McCall7ec50432010-03-19 23:29:14 +00001475 // If there is a definition in the module, then it wins over the alias.
1476 // This is dubious, but allow it to be safe. Just ignore the alias.
1477 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1478 if (Entry && !Entry->isDeclaration())
1479 return;
1480
1481 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001482
1483 // Create a reference to the named value. This ensures that it is emitted
1484 // if a deferred decl.
1485 llvm::Constant *Aliasee;
1486 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +00001487 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattner54041692009-03-22 21:47:11 +00001488 else
John McCall7ec50432010-03-19 23:29:14 +00001489 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001490 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001491
1492 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001493 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001494 new llvm::GlobalAlias(Aliasee->getType(),
1495 llvm::Function::ExternalLinkage,
1496 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattner54041692009-03-22 21:47:11 +00001498 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001499 assert(Entry->isDeclaration());
1500
Chris Lattner54041692009-03-22 21:47:11 +00001501 // If there is a declaration in the module, then we had an extern followed
1502 // by the alias, as in:
1503 // extern int test6();
1504 // ...
1505 // int test6() __attribute__((alias("test7")));
1506 //
1507 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001508 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Owen Andersonade90fd2009-07-29 18:54:39 +00001510 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001511 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001512 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001513 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001514 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
Daniel Dunbar38932572009-04-14 08:05:55 +00001517 // Set attributes which are particular to an alias; this is a
1518 // specialization of the attributes which may be set on a global
1519 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001520 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001521 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1522 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001523 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001524 GA->setLinkage(llvm::Function::DLLExportLinkage);
1525 } else {
1526 GA->setLinkage(llvm::Function::DLLExportLinkage);
1527 }
Mike Stump11289f42009-09-09 15:08:12 +00001528 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001529 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001530 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001531 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1532 }
1533
1534 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001535}
1536
Chris Lattnere64911a2009-03-22 21:56:56 +00001537/// getBuiltinLibFunction - Given a builtin id for a function like
1538/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001539llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1540 unsigned BuiltinID) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001541 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump11289f42009-09-09 15:08:12 +00001542 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001543 "isn't a lib fn");
Mike Stump11289f42009-09-09 15:08:12 +00001544
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001545 // Get the name, skip over the __builtin_ prefix (if necessary).
1546 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1547 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1548 Name += 10;
Mike Stump11289f42009-09-09 15:08:12 +00001549
Mike Stump11289f42009-09-09 15:08:12 +00001550 const llvm::FunctionType *Ty =
Eli Friedman4f678f32009-12-09 03:05:59 +00001551 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattner1eec6602007-08-31 04:31:45 +00001552
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001553 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattner1eec6602007-08-31 04:31:45 +00001554}
1555
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001556llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1557 unsigned NumTys) {
1558 return llvm::Intrinsic::getDeclaration(&getModule(),
1559 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1560}
Chris Lattner1eec6602007-08-31 04:31:45 +00001561
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001562
1563llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1564 const llvm::Type *SrcType,
1565 const llvm::Type *SizeType) {
1566 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1567 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
Chris Lattner09153c02007-06-22 18:48:09 +00001568}
Anders Carlssonb04ea612007-08-21 00:21:21 +00001569
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001570llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1571 const llvm::Type *SrcType,
1572 const llvm::Type *SizeType) {
1573 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1574 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
Eli Friedmandf649f32008-05-26 12:59:39 +00001575}
1576
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001577llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1578 const llvm::Type *SizeType) {
1579 const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1580 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
Lauro Ramos Venancio91fdb9e2008-02-19 22:01:01 +00001581}
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001582
Daniel Dunbar64509b22009-07-23 22:52:48 +00001583static llvm::StringMapEntry<llvm::Constant*> &
1584GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1585 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001586 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001587 bool &IsUTF16,
1588 unsigned &StringLength) {
Daniel Dunbar5de27da2009-09-22 03:27:52 +00001589 unsigned NumBytes = Literal->getByteLength();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001590
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001591 // Check for simple case.
1592 if (!Literal->containsNonAsciiOrNull()) {
1593 StringLength = NumBytes;
1594 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1595 StringLength));
1596 }
1597
Daniel Dunbar64509b22009-07-23 22:52:48 +00001598 // Otherwise, convert the UTF8 literals into a byte string.
1599 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1600 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1601 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001602
1603 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001604 &ToPtr, ToPtr + NumBytes,
1605 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001606
Daniel Dunbar64509b22009-07-23 22:52:48 +00001607 // Check for conversion failure.
1608 if (Result != conversionOK) {
1609 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1610 // this duplicate code.
1611 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001612 StringLength = NumBytes;
1613 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1614 StringLength));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001615 }
1616
Daniel Dunbar91ade142009-07-23 23:41:22 +00001617 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001618 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001619
1620 // Render the UTF-16 string into a byte array and convert to the target byte
1621 // order.
1622 //
1623 // FIXME: This isn't something we should need to do here.
1624 llvm::SmallString<128> AsBytes;
1625 AsBytes.reserve(StringLength * 2);
1626 for (unsigned i = 0; i != StringLength; ++i) {
1627 unsigned short Val = ToBuf[i];
1628 if (TargetIsLSB) {
1629 AsBytes.push_back(Val & 0xFF);
1630 AsBytes.push_back(Val >> 8);
1631 } else {
1632 AsBytes.push_back(Val >> 8);
1633 AsBytes.push_back(Val & 0xFF);
1634 }
1635 }
Daniel Dunbar4d93a4f2009-08-03 21:47:08 +00001636 // Append one extra null character, the second is automatically added by our
1637 // caller.
1638 AsBytes.push_back(0);
Daniel Dunbar91ade142009-07-23 23:41:22 +00001639
Daniel Dunbar64509b22009-07-23 22:52:48 +00001640 IsUTF16 = true;
Daniel Dunbar91ade142009-07-23 23:41:22 +00001641 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001642}
1643
1644llvm::Constant *
1645CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1646 unsigned StringLength = 0;
1647 bool isUTF16 = false;
1648 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001649 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001650 getTargetData().isLittleEndian(),
1651 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001652
Daniel Dunbar64509b22009-07-23 22:52:48 +00001653 if (llvm::Constant *C = Entry.getValue())
1654 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001655
Owen Anderson41a75022009-08-13 21:57:51 +00001656 llvm::Constant *Zero =
1657 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbard644ad62008-08-23 18:37:06 +00001658 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001659
Chris Lattneraa64ca22009-07-16 16:48:25 +00001660 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001661 if (!CFConstantStringClassRef) {
1662 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001663 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001664 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001665 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001666 // Decay array -> ptr
1667 CFConstantStringClassRef =
Owen Andersonade90fd2009-07-29 18:54:39 +00001668 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001669 }
Mike Stump11289f42009-09-09 15:08:12 +00001670
Anders Carlssonc2480a52008-11-15 18:54:24 +00001671 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001672
Mike Stump11289f42009-09-09 15:08:12 +00001673 const llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001674 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1675
Anders Carlsson157c3212009-08-16 05:55:31 +00001676 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor91f84212008-12-11 16:49:14 +00001677
Anders Carlssonb04ea612007-08-21 00:21:21 +00001678 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001679 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001680
Anders Carlssonb04ea612007-08-21 00:21:21 +00001681 // Flags.
Daniel Dunbard644ad62008-08-23 18:37:06 +00001682 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001683 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001684 llvm::ConstantInt::get(Ty, 0x07C8);
1685
Anders Carlssonb04ea612007-08-21 00:21:21 +00001686 // String pointer.
Owen Anderson41a75022009-08-13 21:57:51 +00001687 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001688
Chris Lattner3afa3e12009-07-16 05:03:48 +00001689 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001690 bool isConstant;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001691 if (isUTF16) {
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001692 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00001693 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001694 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1695 // does make plain ascii ones writable.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001696 isConstant = true;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001697 } else {
1698 Linkage = llvm::GlobalValue::PrivateLinkage;
1699 isConstant = !Features.WritableStrings;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001700 }
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001701
Mike Stump11289f42009-09-09 15:08:12 +00001702 llvm::GlobalVariable *GV =
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001703 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1704 ".str");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001705 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00001706 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1707 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001708 }
Anders Carlsson157c3212009-08-16 05:55:31 +00001709 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1710
Anders Carlssonb04ea612007-08-21 00:21:21 +00001711 // String length.
1712 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00001713 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001714
Anders Carlssonb04ea612007-08-21 00:21:21 +00001715 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00001716 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00001717 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1718 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001719 "_unnamed_cfstring_");
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001720 if (const char *Sect = getContext().Target.getCFStringSection())
1721 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00001722 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00001723
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00001724 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00001725}
Chris Lattnerfb300092007-11-28 05:34:05 +00001726
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001727llvm::Constant *
1728CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001729 unsigned StringLength = 0;
1730 bool isUTF16 = false;
1731 llvm::StringMapEntry<llvm::Constant*> &Entry =
1732 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1733 getTargetData().isLittleEndian(),
1734 isUTF16, StringLength);
1735
1736 if (llvm::Constant *C = Entry.getValue())
1737 return C;
1738
1739 llvm::Constant *Zero =
1740 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1741 llvm::Constant *Zeros[] = { Zero, Zero };
1742
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001743 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001744 if (!NSConstantStringClassRef) {
1745 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1746 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001747 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1748 Features.ObjCNonFragileABI ?
1749 "OBJC_CLASS_$_NSConstantString" :
1750 "_NSConstantStringClassReference");
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001751 // Decay array -> ptr
1752 NSConstantStringClassRef =
1753 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1754 }
1755
1756 QualType NSTy = getContext().getNSConstantStringType();
1757
1758 const llvm::StructType *STy =
1759 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1760
1761 std::vector<llvm::Constant*> Fields(3);
1762
1763 // Class pointer.
1764 Fields[0] = NSConstantStringClassRef;
1765
1766 // String pointer.
1767 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1768
1769 llvm::GlobalValue::LinkageTypes Linkage;
1770 bool isConstant;
1771 if (isUTF16) {
1772 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1773 Linkage = llvm::GlobalValue::InternalLinkage;
1774 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1775 // does make plain ascii ones writable.
1776 isConstant = true;
1777 } else {
1778 Linkage = llvm::GlobalValue::PrivateLinkage;
1779 isConstant = !Features.WritableStrings;
1780 }
1781
1782 llvm::GlobalVariable *GV =
1783 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1784 ".str");
1785 if (isUTF16) {
1786 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1787 GV->setAlignment(Align.getQuantity());
1788 }
1789 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1790
1791 // String length.
1792 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1793 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1794
1795 // The struct.
1796 C = llvm::ConstantStruct::get(STy, Fields);
1797 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1798 llvm::GlobalVariable::PrivateLinkage, C,
1799 "_unnamed_nsstring_");
1800 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001801 if (const char *Sect =
1802 Features.ObjCNonFragileABI
1803 ? getContext().Target.getNSStringNonFragileABISection()
1804 : getContext().Target.getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001805 GV->setSection(Sect);
1806 Entry.setValue(GV);
1807
1808 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001809}
1810
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001811/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001812/// string literal, properly padded to match the literal type.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001813std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001814 const char *StrData = E->getStrData();
1815 unsigned Len = E->getByteLength();
1816
1817 const ConstantArrayType *CAT =
1818 getContext().getAsConstantArrayType(E->getType());
1819 assert(CAT && "String isn't pointer or array!");
Mike Stump11289f42009-09-09 15:08:12 +00001820
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001821 // Resize the string to the right size.
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001822 std::string Str(StrData, StrData+Len);
1823 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001825 if (E->isWide())
1826 RealLen *= getContext().Target.getWCharWidth()/8;
Mike Stump11289f42009-09-09 15:08:12 +00001827
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001828 Str.resize(RealLen, '\0');
Mike Stump11289f42009-09-09 15:08:12 +00001829
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001830 return Str;
1831}
1832
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001833/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1834/// constant array for the given string literal.
1835llvm::Constant *
1836CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1837 // FIXME: This can be more efficient.
Eli Friedman49ddc5f2009-11-16 05:55:46 +00001838 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1839 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1840 if (S->isWide()) {
1841 llvm::Type *DestTy =
1842 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1843 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1844 }
1845 return C;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001846}
1847
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001848/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1849/// array for the given ObjCEncodeExpr node.
1850llvm::Constant *
1851CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1852 std::string Str;
1853 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00001854
1855 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001856}
1857
1858
Chris Lattner36fc8792008-02-11 00:02:17 +00001859/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001860static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattnerfb300092007-11-28 05:34:05 +00001861 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001862 CodeGenModule &CGM,
1863 const char *GlobalName) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001864 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00001865 llvm::Constant *C =
1866 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00001867
Chris Lattnerfb300092007-11-28 05:34:05 +00001868 // Create a global variable for this string
Mike Stump11289f42009-09-09 15:08:12 +00001869 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001870 llvm::GlobalValue::PrivateLinkage,
Owen Andersonc10c8d32009-07-08 19:05:04 +00001871 C, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001872}
1873
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001874/// GetAddrOfConstantString - Returns a pointer to a character array
1875/// containing the literal. This contents are exactly that of the
1876/// given string, i.e. it will not be null terminated automatically;
1877/// see GetAddrOfConstantCString. Note that whether the result is
1878/// actually a pointer to an LLVM constant depends on
1879/// Feature.WriteableStrings.
1880///
1881/// The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001882llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1883 const char *GlobalName) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001884 bool IsConstant = !Features.WritableStrings;
1885
1886 // Get the default prefix if a name wasn't specified.
1887 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00001888 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001889
1890 // Don't share any string literals if strings aren't constant.
1891 if (!IsConstant)
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001892 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump11289f42009-09-09 15:08:12 +00001893
1894 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner3afa3e12009-07-16 05:03:48 +00001895 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattnerfb300092007-11-28 05:34:05 +00001896
1897 if (Entry.getValue())
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001898 return Entry.getValue();
Chris Lattnerfb300092007-11-28 05:34:05 +00001899
1900 // Create a global variable for this.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001901 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001902 Entry.setValue(C);
1903 return C;
1904}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001905
1906/// GetAddrOfConstantCString - Returns a pointer to a character
1907/// array containing the literal and a terminating '\-'
1908/// character. The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001909llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1910 const char *GlobalName){
Chris Lattner2e41b0e2008-12-09 19:10:54 +00001911 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001912}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001913
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001914/// EmitObjCPropertyImplementations - Emit information for synthesized
1915/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00001916void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001917 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001918 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001919 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001920 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00001921
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001922 // Dynamic is just for type-checking.
1923 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1924 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1925
1926 // Determine which methods need to be implemented, some may have
1927 // been overridden. Note that ::isSynthesized is not the method
1928 // we want, that just indicates if the decl came from a
1929 // property. What we want to know is if the method is defined in
1930 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001931 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001932 CodeGenFunction(*this).GenerateObjCGetter(
1933 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001934 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001935 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001936 CodeGenFunction(*this).GenerateObjCSetter(
1937 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001938 }
1939 }
1940}
1941
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001942/// EmitObjCIvarInitializations - Emit information for ivar initialization
1943/// for an implementation.
1944void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1945 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1946 return;
1947 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1948 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1949 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1950 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1951 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1952 D->getLocation(),
1953 D->getLocation(), cxxSelector,
1954 getContext().VoidTy, 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001955 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001956 ObjCMethodDecl::Required);
1957 D->addInstanceMethod(DTORMethod);
1958 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1959
1960 II = &getContext().Idents.get(".cxx_construct");
1961 cxxSelector = getContext().Selectors.getSelector(0, &II);
1962 // The constructor returns 'self'.
1963 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1964 D->getLocation(),
1965 D->getLocation(), cxxSelector,
1966 getContext().getObjCIdType(), 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001967 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001968 ObjCMethodDecl::Required);
1969 D->addInstanceMethod(CTORMethod);
1970 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1971
1972
1973}
1974
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001975/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00001976void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001977 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00001978 I != E; ++I)
1979 EmitTopLevelDecl(*I);
1980}
1981
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001982// EmitLinkageSpec - Emit all declarations in a linkage spec.
1983void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00001984 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1985 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001986 ErrorUnsupported(LSD, "linkage spec");
1987 return;
1988 }
1989
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001990 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001991 I != E; ++I)
1992 EmitTopLevelDecl(*I);
1993}
1994
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001995/// EmitTopLevelDecl - Emit code for a single top level declaration.
1996void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1997 // If an error has occurred, stop code generation, but continue
1998 // parsing and semantic analysis (to ensure all warnings and errors
1999 // are emitted).
2000 if (Diags.hasErrorOccurred())
2001 return;
2002
Douglas Gregor70d83e22009-06-29 17:30:29 +00002003 // Ignore dependent declarations.
2004 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2005 return;
Mike Stump11289f42009-09-09 15:08:12 +00002006
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002007 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00002008 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00002009 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002010 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00002011 // Skip function templates
2012 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2013 return;
Mike Stump11289f42009-09-09 15:08:12 +00002014
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002015 EmitGlobal(cast<FunctionDecl>(D));
2016 break;
2017
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002018 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002019 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002020 break;
2021
Anders Carlssonf7475242009-04-15 15:55:24 +00002022 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002023 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00002024 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002025 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00002026 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00002027 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00002028 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00002029 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002030 case Decl::ClassTemplate:
2031 case Decl::FunctionTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00002032 case Decl::NamespaceAlias:
Douglas Gregorfec52632009-06-20 00:51:54 +00002033 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00002034 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00002035 // Skip function templates
2036 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
2037 return;
2038
Anders Carlssonf7475242009-04-15 15:55:24 +00002039 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2040 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002041 case Decl::CXXDestructor:
2042 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2043 break;
Anders Carlsson87835432009-06-11 21:22:55 +00002044
2045 case Decl::StaticAssert:
2046 // Nothing to do.
2047 break;
2048
Anders Carlssonf7475242009-04-15 15:55:24 +00002049 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00002050
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002051 // Forward declarations, no (immediate) code generation.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002052 case Decl::ObjCClass:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002053 case Decl::ObjCForwardProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002054 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002055 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002056 break;
2057
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002058 case Decl::ObjCProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002059 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002060 break;
2061
2062 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002063 // Categories have properties but don't support synthesize so we
2064 // can ignore them here.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002065 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2066 break;
2067
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002068 case Decl::ObjCImplementation: {
2069 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2070 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002071 EmitObjCIvarInitializations(OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002072 Runtime->GenerateClass(OMD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002073 break;
Mike Stump11289f42009-09-09 15:08:12 +00002074 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002075 case Decl::ObjCMethod: {
2076 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2077 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002078 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002079 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2080 break;
2081 }
Mike Stump11289f42009-09-09 15:08:12 +00002082 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian17290c32009-01-08 01:10:55 +00002083 // compatibility-alias is a directive and has no code gen.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002084 break;
2085
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002086 case Decl::LinkageSpec:
2087 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002088 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002089
2090 case Decl::FileScopeAsm: {
2091 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002092 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002093
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002094 const std::string &S = getModule().getModuleInlineAsm();
2095 if (S.empty())
2096 getModule().setModuleInlineAsm(AsmString);
2097 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002098 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002099 break;
2100 }
Mike Stump11289f42009-09-09 15:08:12 +00002101
2102 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002103 // Make sure we handled everything we should, every other kind is a
2104 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2105 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002106 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2107 }
2108}
John McCall09ae0322010-07-06 23:57:41 +00002109
2110/// Turns the given pointer into a constant.
2111static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2112 const void *Ptr) {
2113 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2114 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2115 return llvm::ConstantInt::get(i64, PtrInt);
2116}
2117
2118static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2119 llvm::NamedMDNode *&GlobalMetadata,
2120 GlobalDecl D,
2121 llvm::GlobalValue *Addr) {
2122 if (!GlobalMetadata)
2123 GlobalMetadata =
2124 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2125
2126 // TODO: should we report variant information for ctors/dtors?
2127 llvm::Value *Ops[] = {
2128 Addr,
2129 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2130 };
2131 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2132}
2133
2134/// Emits metadata nodes associating all the global values in the
2135/// current module with the Decls they came from. This is useful for
2136/// projects using IR gen as a subroutine.
2137///
2138/// Since there's currently no way to associate an MDNode directly
2139/// with an llvm::GlobalValue, we create a global named metadata
2140/// with the name 'clang.global.decl.ptrs'.
2141void CodeGenModule::EmitDeclMetadata() {
2142 llvm::NamedMDNode *GlobalMetadata = 0;
2143
2144 // StaticLocalDeclMap
2145 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2146 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2147 I != E; ++I) {
2148 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2149 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2150 }
2151}
2152
2153/// Emits metadata nodes for all the local variables in the current
2154/// function.
2155void CodeGenFunction::EmitDeclMetadata() {
2156 if (LocalDeclMap.empty()) return;
2157
2158 llvm::LLVMContext &Context = getLLVMContext();
2159
2160 // Find the unique metadata ID for this name.
2161 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2162
2163 llvm::NamedMDNode *GlobalMetadata = 0;
2164
2165 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2166 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2167 const Decl *D = I->first;
2168 llvm::Value *Addr = I->second;
2169
2170 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2171 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2172 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2173 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2174 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2175 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2176 }
2177 }
2178}
Daniel Dunbar900546d2010-07-16 00:00:15 +00002179
2180///@name Custom Runtime Function Interfaces
2181///@{
2182//
2183// FIXME: These can be eliminated once we can have clients just get the required
2184// AST nodes from the builtin tables.
2185
2186llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2187 if (BlockObjectDispose)
2188 return BlockObjectDispose;
2189
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002190 // If we saw an explicit decl, use that.
2191 if (BlockObjectDisposeDecl) {
2192 return BlockObjectDispose = GetAddrOfFunction(
2193 BlockObjectDisposeDecl,
2194 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2195 }
2196
2197 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002198 const llvm::FunctionType *FTy;
2199 std::vector<const llvm::Type*> ArgTys;
2200 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2201 ArgTys.push_back(PtrToInt8Ty);
2202 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2203 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2204 return BlockObjectDispose =
2205 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2206}
2207
2208llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2209 if (BlockObjectAssign)
2210 return BlockObjectAssign;
2211
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002212 // If we saw an explicit decl, use that.
2213 if (BlockObjectAssignDecl) {
2214 return BlockObjectAssign = GetAddrOfFunction(
2215 BlockObjectAssignDecl,
2216 getTypes().GetFunctionType(BlockObjectAssignDecl));
2217 }
2218
2219 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002220 const llvm::FunctionType *FTy;
2221 std::vector<const llvm::Type*> ArgTys;
2222 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2223 ArgTys.push_back(PtrToInt8Ty);
2224 ArgTys.push_back(PtrToInt8Ty);
2225 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2226 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2227 return BlockObjectAssign =
2228 CreateRuntimeFunction(FTy, "_Block_object_assign");
2229}
2230
2231llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2232 if (NSConcreteGlobalBlock)
2233 return NSConcreteGlobalBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002234
2235 // If we saw an explicit decl, use that.
2236 if (NSConcreteGlobalBlockDecl) {
2237 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2238 NSConcreteGlobalBlockDecl,
2239 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2240 }
2241
2242 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002243 return NSConcreteGlobalBlock = CreateRuntimeVariable(
2244 PtrToInt8Ty, "_NSConcreteGlobalBlock");
2245}
2246
2247llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2248 if (NSConcreteStackBlock)
2249 return NSConcreteStackBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002250
2251 // If we saw an explicit decl, use that.
2252 if (NSConcreteStackBlockDecl) {
2253 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2254 NSConcreteStackBlockDecl,
2255 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2256 }
2257
2258 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002259 return NSConcreteStackBlock = CreateRuntimeVariable(
2260 PtrToInt8Ty, "_NSConcreteStackBlock");
2261}
2262
2263///@}