blob: ed9542230023100bf275b5cf1144d87c11088d54 [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"
Chandler Carruth85098242010-06-15 23:19:56 +000021#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000022#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000023#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000025#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000026#include "clang/AST/DeclTemplate.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000027#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000028#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000029#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000030#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000031#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000032#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000033#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000034#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000035#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000036#include "llvm/LLVMContext.h"
John McCallbeec5a02010-03-06 00:35:14 +000037#include "llvm/ADT/Triple.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000038#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000039#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000041using namespace clang;
42using namespace CodeGen;
43
44
Chandler Carruthbc55fe22009-11-12 17:24:48 +000045CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000046 llvm::Module &M, const llvm::TargetData &TD,
47 Diagnostic &diags)
Chris Lattner984fac52009-03-26 05:00:52 +000048 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruthbc55fe22009-11-12 17:24:48 +000049 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000050 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000051 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
Charles Davis4e786dd2010-05-25 19:52:27 +000052 VTables(*this), Runtime(0), ABI(0),
John McCall6936c862010-04-09 22:26:14 +000053 CFConstantStringClassRef(0),
Fariborz Jahaniane804c282010-04-23 17:41:07 +000054 NSConstantStringClassRef(0),
Owen Anderson170229f2009-07-14 23:10:40 +000055 VMContext(M.getContext()) {
Daniel Dunbar8d480592008-08-11 18:12:00 +000056
Chris Lattner36376522009-03-21 07:12:05 +000057 if (!Features.ObjC1)
58 Runtime = 0;
59 else if (!Features.NeXTRuntime)
60 Runtime = CreateGNUObjCRuntime(*this);
61 else if (Features.ObjCNonFragileABI)
62 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
63 else
64 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000065
Charles Davis4e786dd2010-05-25 19:52:27 +000066 if (!Features.CPlusPlus)
67 ABI = 0;
68 else createCXXABI();
69
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000070 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson3efc6e62009-12-06 18:00:51 +000071 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattnera087ff92008-03-01 08:45:05 +000072}
73
74CodeGenModule::~CodeGenModule() {
Ted Kremenek2c674f62008-08-05 18:50:11 +000075 delete Runtime;
Charles Davis4e786dd2010-05-25 19:52:27 +000076 delete ABI;
Ted Kremenek2c674f62008-08-05 18:50:11 +000077 delete DebugInfo;
78}
79
David Chisnall481e3a82010-01-23 02:40:42 +000080void CodeGenModule::createObjCRuntime() {
81 if (!Features.NeXTRuntime)
82 Runtime = CreateGNUObjCRuntime(*this);
83 else if (Features.ObjCNonFragileABI)
84 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
85 else
86 Runtime = CreateMacObjCRuntime(*this);
87}
88
Charles Davis4e786dd2010-05-25 19:52:27 +000089void CodeGenModule::createCXXABI() {
Charles Davis95a546e2010-06-11 01:06:47 +000090 if (Context.Target.getCXXABI() == "microsoft")
91 ABI = CreateMicrosoftCXXABI(*this);
92 else
93 ABI = CreateItaniumCXXABI(*this);
Charles Davis4e786dd2010-05-25 19:52:27 +000094}
95
Ted Kremenek2c674f62008-08-05 18:50:11 +000096void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +000097 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +000098 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +000099 EmitCXXGlobalDtorFunc();
Daniel Dunbar8d480592008-08-11 18:12:00 +0000100 if (Runtime)
101 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
102 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000103 EmitCtorList(GlobalCtors, "llvm.global_ctors");
104 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman7fab5782008-04-18 23:43:57 +0000105 EmitAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000106 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000107
108 if (getCodeGenOpts().EmitDeclMetadata)
109 EmitDeclMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000110}
111
John McCallbeec5a02010-03-06 00:35:14 +0000112bool CodeGenModule::isTargetDarwin() const {
113 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
114}
115
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000116/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000117/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000118void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
119 bool OmitOnError) {
120 if (OmitOnError && getDiags().hasErrorOccurred())
121 return;
Mike Stump11289f42009-09-09 15:08:12 +0000122 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000123 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000124 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000125 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
126 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000127}
Chris Lattner41af8182007-12-02 06:27:33 +0000128
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000129/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000130/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000131void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
132 bool OmitOnError) {
133 if (OmitOnError && getDiags().hasErrorOccurred())
134 return;
Mike Stump11289f42009-09-09 15:08:12 +0000135 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000136 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000137 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000138 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000139}
140
Mike Stump11289f42009-09-09 15:08:12 +0000141LangOptions::VisibilityMode
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000142CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
143 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
144 if (VD->getStorageClass() == VarDecl::PrivateExtern)
145 return LangOptions::Hidden;
146
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000147 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000148 switch (attr->getVisibility()) {
149 default: assert(0 && "Unknown visibility!");
Mike Stump11289f42009-09-09 15:08:12 +0000150 case VisibilityAttr::DefaultVisibility:
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000151 return LangOptions::Default;
152 case VisibilityAttr::HiddenVisibility:
153 return LangOptions::Hidden;
154 case VisibilityAttr::ProtectedVisibility:
155 return LangOptions::Protected;
156 }
157 }
Douglas Gregor08329632010-06-15 17:05:35 +0000158
Douglas Gregor5dd34742010-06-21 18:41:26 +0000159 if (getLangOptions().CPlusPlus) {
160 // Entities subject to an explicit instantiation declaration get default
161 // visibility.
162 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
163 if (Function->getTemplateSpecializationKind()
164 == TSK_ExplicitInstantiationDeclaration)
165 return LangOptions::Default;
166 } else if (const ClassTemplateSpecializationDecl *ClassSpec
167 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
168 if (ClassSpec->getSpecializationKind()
169 == TSK_ExplicitInstantiationDeclaration)
170 return LangOptions::Default;
171 } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
172 if (Record->getTemplateSpecializationKind()
173 == TSK_ExplicitInstantiationDeclaration)
174 return LangOptions::Default;
175 } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
176 if (Var->isStaticDataMember() &&
177 (Var->getTemplateSpecializationKind()
178 == TSK_ExplicitInstantiationDeclaration))
179 return LangOptions::Default;
180 }
181
182 // If -fvisibility-inlines-hidden was provided, then inline C++ member
183 // functions get "hidden" visibility by default.
184 if (getLangOptions().InlineVisibilityHidden)
185 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
186 if (Method->isInlined())
187 return LangOptions::Hidden;
188 }
189
Anders Carlsson10d369d2010-02-07 01:44:36 +0000190 // This decl should have the same visibility as its parent.
191 if (const DeclContext *DC = D->getDeclContext())
192 return getDeclVisibilityMode(cast<Decl>(DC));
193
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000194 return getLangOptions().getVisibilityMode();
195}
196
Mike Stump11289f42009-09-09 15:08:12 +0000197void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000198 const Decl *D) const {
199 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000200 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000201 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000202 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000203 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000204
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000205 switch (getDeclVisibilityMode(D)) {
Dan Gohman75d69da2008-05-22 00:50:06 +0000206 default: assert(0 && "Unknown visibility!");
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000207 case LangOptions::Default:
208 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
209 case LangOptions::Hidden:
210 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
211 case LangOptions::Protected:
212 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
Dan Gohman75d69da2008-05-22 00:50:06 +0000213 }
214}
215
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000216llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
217 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
218
219 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
220 if (!Str.empty())
221 return Str;
222
223 if (!getMangleContext().shouldMangleDeclName(ND)) {
224 IdentifierInfo *II = ND->getIdentifier();
225 assert(II && "Attempt to mangle unnamed decl.");
226
227 Str = II->getName();
228 return Str;
229 }
230
231 llvm::SmallString<256> Buffer;
232 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
233 getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
234 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
235 getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
236 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian9b5528d2010-06-24 00:08:06 +0000237 getMangleContext().mangleBlock(GD, BD, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000238 else
239 getMangleContext().mangleName(ND, Buffer);
240
241 // Allocate space for the mangled name.
242 size_t Length = Buffer.size();
243 char *Name = MangledNamesAllocator.Allocate<char>(Length);
244 std::copy(Buffer.begin(), Buffer.end(), Name);
245
246 Str = llvm::StringRef(Name, Length);
247
248 return Str;
249}
250
Fariborz Jahanian9b5528d2010-06-24 00:08:06 +0000251void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer,
252 const BlockDecl *BD) {
253 getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer());
Anders Carlsson635186a2010-06-09 02:36:32 +0000254}
255
John McCall7ec50432010-03-19 23:29:14 +0000256llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
257 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000258}
259
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000260/// AddGlobalCtor - Add a function to the list that will be called before
261/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000262void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000263 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000264 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000265}
266
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000267/// AddGlobalDtor - Add a function to the list that will be called
268/// when the module is unloaded.
269void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000270 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000271 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
272}
273
274void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
275 // Ctor function type is void()*.
276 llvm::FunctionType* CtorFTy =
Mike Stump11289f42009-09-09 15:08:12 +0000277 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000278 std::vector<const llvm::Type*>(),
279 false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000280 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000281
282 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump11289f42009-09-09 15:08:12 +0000283 llvm::StructType* CtorStructTy =
284 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson9793f0e2009-07-29 22:16:19 +0000285 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000286
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000287 // Construct the constructor and destructor arrays.
288 std::vector<llvm::Constant*> Ctors;
289 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
290 std::vector<llvm::Constant*> S;
Mike Stump11289f42009-09-09 15:08:12 +0000291 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson41a75022009-08-13 21:57:51 +0000292 I->second, false));
Owen Andersonade90fd2009-07-29 18:54:39 +0000293 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson0e0189d2009-07-27 22:29:56 +0000294 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000295 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000296
297 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000298 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000299 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000300 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000301 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000302 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000303 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000304}
305
Nate Begeman7fab5782008-04-18 23:43:57 +0000306void CodeGenModule::EmitAnnotations() {
307 if (Annotations.empty())
308 return;
309
310 // Create a new global variable for the ConstantStruct in the Module.
311 llvm::Constant *Array =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000312 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman7fab5782008-04-18 23:43:57 +0000313 Annotations.size()),
314 Annotations);
Mike Stump11289f42009-09-09 15:08:12 +0000315 llvm::GlobalValue *gv =
316 new llvm::GlobalVariable(TheModule, Array->getType(), false,
317 llvm::GlobalValue::AppendingLinkage, Array,
Owen Andersonc10c8d32009-07-08 19:05:04 +0000318 "llvm.global.annotations");
Nate Begeman7fab5782008-04-18 23:43:57 +0000319 gv->setSection("llvm.metadata");
320}
321
Chris Lattner02e987f2009-04-14 16:44:36 +0000322static CodeGenModule::GVALinkage
Mike Stump11289f42009-09-09 15:08:12 +0000323GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
Douglas Gregor78bd61f2009-06-18 16:11:24 +0000324 const LangOptions &Features) {
Douglas Gregore8925db2009-06-29 22:39:32 +0000325 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000326
327 Linkage L = FD->getLinkage();
328 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
329 FD->getType()->getLinkage() == UniqueExternalLinkage)
330 L = UniqueExternalLinkage;
331
332 switch (L) {
333 case NoLinkage:
334 case InternalLinkage:
335 case UniqueExternalLinkage:
336 return CodeGenModule::GVA_Internal;
Anders Carlsson781161d2009-12-10 22:25:34 +0000337
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000338 case ExternalLinkage:
339 switch (FD->getTemplateSpecializationKind()) {
340 case TSK_Undeclared:
341 case TSK_ExplicitSpecialization:
342 External = CodeGenModule::GVA_StrongExternal;
343 break;
344
345 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorb14d1232010-03-13 18:23:07 +0000346 return CodeGenModule::GVA_ExplicitTemplateInstantiation;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000347
348 case TSK_ExplicitInstantiationDeclaration:
349 case TSK_ImplicitInstantiation:
Anders Carlsson781161d2009-12-10 22:25:34 +0000350 External = CodeGenModule::GVA_TemplateInstantiation;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351 break;
352 }
Anders Carlsson781161d2009-12-10 22:25:34 +0000353 }
Mike Stump11289f42009-09-09 15:08:12 +0000354
Douglas Gregor583dcaf2009-10-27 21:11:48 +0000355 if (!FD->isInlined())
Douglas Gregore8925db2009-06-29 22:39:32 +0000356 return External;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000357
Douglas Gregor299d76e2009-09-13 07:46:26 +0000358 if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
359 // GNU or C99 inline semantics. Determine whether this symbol should be
360 // externally visible.
361 if (FD->isInlineDefinitionExternallyVisible())
362 return External;
363
364 // C99 inline semantics, where the symbol is not externally visible.
365 return CodeGenModule::GVA_C99Inline;
Chris Lattnerf8dc0732009-04-22 00:03:30 +0000366 }
Chris Lattnerbae0e682009-04-14 20:25:53 +0000367
Douglas Gregorb7e5c842009-10-27 23:26:40 +0000368 // C++0x [temp.explicit]p9:
369 // [ Note: The intent is that an inline function that is the subject of
370 // an explicit instantiation declaration will still be implicitly
371 // instantiated when used so that the body can be considered for
372 // inlining, but that no out-of-line copy of the inline function would be
373 // generated in the translation unit. -- end note ]
Rafael Espindolafa1708fd2010-03-23 19:55:22 +0000374 if (FD->getTemplateSpecializationKind()
375 == TSK_ExplicitInstantiationDeclaration)
Douglas Gregorb7e5c842009-10-27 23:26:40 +0000376 return CodeGenModule::GVA_C99Inline;
Rafael Espindola683fe4f2010-04-19 00:44:22 +0000377
Douglas Gregor299d76e2009-09-13 07:46:26 +0000378 return CodeGenModule::GVA_CXXInline;
Daniel Dunbar38932572009-04-14 08:05:55 +0000379}
380
John McCalld4324142010-02-19 01:32:20 +0000381llvm::GlobalValue::LinkageTypes
382CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Douglas Gregor78bd61f2009-06-18 16:11:24 +0000383 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
Daniel Dunbar38932572009-04-14 08:05:55 +0000384
Chris Lattner749b8ed2010-06-30 16:58:07 +0000385 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000386 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000387
388 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000389 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000390
391 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000392 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000393
394 // In C99 mode, 'inline' functions are guaranteed to have a strong
395 // definition somewhere else, so we can use available_externally linkage.
396 if (Linkage == GVA_C99Inline)
John McCalld4324142010-02-19 01:32:20 +0000397 return llvm::Function::AvailableExternallyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000398
399 // In C++, the compiler has to emit a definition in every translation unit
400 // that references the function. We should use linkonce_odr because
401 // a) if all references in this translation unit are optimized away, we
402 // don't need to codegen it. b) if the function persists, it needs to be
403 // merged with other definitions. c) C++ has the ODR, so we know the
404 // definition is dependable.
405 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld4324142010-02-19 01:32:20 +0000406 return llvm::Function::LinkOnceODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000407
408 // An explicit instantiation of a template has weak linkage, since
409 // explicit instantiations can occur in multiple translation units
410 // and must all be equivalent. However, we are not allowed to
411 // throw away these explicit instantiations.
412 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregorb14d1232010-03-13 18:23:07 +0000413 return llvm::Function::WeakODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000414
415 // Otherwise, we have strong external linkage.
416 assert(Linkage == GVA_StrongExternal);
417 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000418}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000419
John McCalld4324142010-02-19 01:32:20 +0000420
421/// SetFunctionDefinitionAttributes - Set attributes for a global.
422///
423/// FIXME: This is currently only done for aliases and functions, but not for
424/// variables (these details are set in EmitGlobalVarDefinition for variables).
425void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
426 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000427 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000428}
429
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000430void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000431 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000432 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000433 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000434 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000435 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel322300d2008-09-25 21:02:23 +0000436 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000437 AttributeList.size()));
438 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000439}
440
Daniel Dunbar38932572009-04-14 08:05:55 +0000441void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
442 llvm::Function *F) {
Daniel Dunbar0f3403c2009-03-02 04:58:03 +0000443 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump11289f42009-09-09 15:08:12 +0000444 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000445
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000446 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbar03a38442008-10-28 00:17:57 +0000447 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump11289f42009-09-09 15:08:12 +0000448
Mike Stump3722f582009-08-26 22:31:08 +0000449 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000450 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000451
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000452 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
453 F->addFnAttr(llvm::Attribute::StackProtect);
454 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
455 F->addFnAttr(llvm::Attribute::StackProtectReq);
456
Alexis Hunt96d5c762009-11-21 08:43:09 +0000457 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
458 unsigned width = Context.Target.getCharWidth();
459 F->setAlignment(AA->getAlignment() / width);
460 while ((AA = AA->getNext<AlignedAttr>()))
461 F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
462 }
Mike Stump3472ae52009-10-05 22:49:20 +0000463 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000464 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
465 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000466}
467
Mike Stump11289f42009-09-09 15:08:12 +0000468void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000469 llvm::GlobalValue *GV) {
470 setGlobalVisibility(GV, D);
471
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000472 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000473 AddUsedGlobal(GV);
474
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000475 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000476 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000477
478 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000479}
480
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000481void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
482 llvm::Function *F,
483 const CGFunctionInfo &FI) {
484 SetLLVMFunctionAttributes(D, FI, F);
485 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000486
487 F->setLinkage(llvm::Function::InternalLinkage);
488
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000489 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000490}
491
Anders Carlsson6710c532010-02-06 02:44:09 +0000492void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000493 llvm::Function *F,
494 bool IsIncompleteFunction) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000495 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
496
Eli Friedman895771a2009-05-26 01:22:57 +0000497 if (!IsIncompleteFunction)
Anders Carlsson6710c532010-02-06 02:44:09 +0000498 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000499
Daniel Dunbar38932572009-04-14 08:05:55 +0000500 // Only a few attributes are set on declarations; these may later be
501 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000502
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000503 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000504 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000505 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000506 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000507 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000508 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000509 F->setLinkage(llvm::Function::ExternalWeakLinkage);
510 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000511 F->setLinkage(llvm::Function::ExternalLinkage);
Daniel Dunbar38932572009-04-14 08:05:55 +0000512 }
513
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000514 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000515 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000516}
517
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000518void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000519 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000520 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000521 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000522}
523
524void CodeGenModule::EmitLLVMUsed() {
525 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000526 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000527 return;
528
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000529 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000531 // Convert LLVMUsed to what ConstantArray needs.
532 std::vector<llvm::Constant*> UsedArray;
533 UsedArray.resize(LLVMUsed.size());
534 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000535 UsedArray[i] =
536 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Anderson170229f2009-07-14 23:10:40 +0000537 i8PTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000540 if (UsedArray.empty())
541 return;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000542 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000543
544 llvm::GlobalVariable *GV =
545 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000546 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000547 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000548 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000549
550 GV->setSection("llvm.metadata");
551}
552
553void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000554 // Emit code for any potentially referenced deferred decls. Since a
555 // previously unused static decl may become used during the generation of code
556 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000557
Anders Carlsson11e51402010-04-17 20:15:18 +0000558 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
559 if (!DeferredVTables.empty()) {
560 const CXXRecordDecl *RD = DeferredVTables.back();
561 DeferredVTables.pop_back();
562 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000563 continue;
564 }
565
Anders Carlssondae1abc2009-05-05 04:44:02 +0000566 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000567 DeferredDeclsToEmit.pop_back();
568
John McCallc2af9392010-05-27 01:45:30 +0000569 // Check to see if we've already emitted this. This is necessary
570 // for a couple of reasons: first, decls can end up in the
571 // deferred-decls queue multiple times, and second, decls can end
572 // up with definitions in unusual ways (e.g. by an extern inline
573 // function acquiring a strong function redefinition). Just
574 // ignore these cases.
575 //
576 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000577 llvm::StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000578 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000579 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000580
Chris Lattner45470942009-03-21 09:44:56 +0000581 if (!CGRef->isDeclaration())
582 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000583
John McCallc2af9392010-05-27 01:45:30 +0000584 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
585 // purposes an alias counts as a definition.
586 if (isa<llvm::GlobalAlias>(CGRef))
587 continue;
588
Chris Lattner45470942009-03-21 09:44:56 +0000589 // Otherwise, emit the definition and move on to the next one.
590 EmitGlobalDefinition(D);
591 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000592}
Chris Lattner09153c02007-06-22 18:48:09 +0000593
Mike Stump11289f42009-09-09 15:08:12 +0000594/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begemanfaae0812008-04-19 04:17:09 +0000595/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump11289f42009-09-09 15:08:12 +0000596/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
597/// GlobalValue being annotated. The second field is the constant string
598/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begemanfaae0812008-04-19 04:17:09 +0000599/// string containing the name of the translation unit. The fourth field is
600/// the line number in the file of the annotated value declaration.
601///
602/// FIXME: this does not unique the annotation string constants, as llvm-gcc
603/// appears to.
604///
Mike Stump11289f42009-09-09 15:08:12 +0000605llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000606 const AnnotateAttr *AA,
607 unsigned LineNo) {
608 llvm::Module *M = &getModule();
609
610 // get [N x i8] constants for the annotation string, and the filename string
611 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000612 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000613 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000614 AA->getAnnotation(), true);
615 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
616 M->getModuleIdentifier(),
Nate Begemanfaae0812008-04-19 04:17:09 +0000617 true);
618
619 // Get the two global values corresponding to the ConstantArrays we just
620 // created to hold the bytes of the strings.
Mike Stump11289f42009-09-09 15:08:12 +0000621 llvm::GlobalValue *annoGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000622 new llvm::GlobalVariable(*M, anno->getType(), false,
623 llvm::GlobalValue::PrivateLinkage, anno,
624 GV->getName());
Nate Begemanfaae0812008-04-19 04:17:09 +0000625 // translation unit name string, emitted into the llvm.metadata section.
626 llvm::GlobalValue *unitGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000627 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump11289f42009-09-09 15:08:12 +0000628 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner3afa3e12009-07-16 05:03:48 +0000629 ".str");
Nate Begemanfaae0812008-04-19 04:17:09 +0000630
Daniel Dunbar346892a2009-04-14 22:41:13 +0000631 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000632 llvm::Constant *Fields[4] = {
Owen Andersonade90fd2009-07-29 18:54:39 +0000633 llvm::ConstantExpr::getBitCast(GV, SBP),
634 llvm::ConstantExpr::getBitCast(annoGV, SBP),
635 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson41a75022009-08-13 21:57:51 +0000636 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begemanfaae0812008-04-19 04:17:09 +0000637 };
Owen Anderson758428f2009-08-05 23:18:46 +0000638 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begemanfaae0812008-04-19 04:17:09 +0000639}
640
Eli Friedmanc96b2492010-06-19 06:24:06 +0000641static CodeGenModule::GVALinkage
642GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
643 // If this is a static data member, compute the kind of template
644 // specialization. Otherwise, this variable is not part of a
645 // template.
646 TemplateSpecializationKind TSK = TSK_Undeclared;
647 if (VD->isStaticDataMember())
648 TSK = VD->getTemplateSpecializationKind();
649
650 Linkage L = VD->getLinkage();
651 if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
652 VD->getType()->getLinkage() == UniqueExternalLinkage)
653 L = UniqueExternalLinkage;
654
655 switch (L) {
656 case NoLinkage:
657 case InternalLinkage:
658 case UniqueExternalLinkage:
659 return CodeGenModule::GVA_Internal;
660
661 case ExternalLinkage:
662 switch (TSK) {
663 case TSK_Undeclared:
664 case TSK_ExplicitSpecialization:
665 return CodeGenModule::GVA_StrongExternal;
666
667 case TSK_ExplicitInstantiationDeclaration:
668 llvm_unreachable("Variable should not be instantiated");
669 // Fall through to treat this like any other instantiation.
670
671 case TSK_ExplicitInstantiationDefinition:
672 return CodeGenModule::GVA_ExplicitTemplateInstantiation;
673
674 case TSK_ImplicitInstantiation:
675 return CodeGenModule::GVA_TemplateInstantiation;
676 }
677 }
678
679 return CodeGenModule::GVA_StrongExternal;
680}
681
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000682bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar128a1382009-02-13 22:08:43 +0000683 // Never defer when EmitAllDecls is specified or the decl has
684 // attribute used.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000685 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000686 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000687
688 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000689 // Constructors and destructors should never be deferred.
Mike Stump11289f42009-09-09 15:08:12 +0000690 if (FD->hasAttr<ConstructorAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000691 FD->hasAttr<DestructorAttr>())
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000692 return false;
693
Eli Friedmanf2c79b62009-12-08 03:56:49 +0000694 // The key function for a class must never be deferred.
695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
696 const CXXRecordDecl *RD = MD->getParent();
697 if (MD->isOutOfLine() && RD->isDynamicClass()) {
698 const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
Douglas Gregora318efd2010-01-05 19:06:31 +0000699 if (KeyFunction &&
700 KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
Eli Friedmanf2c79b62009-12-08 03:56:49 +0000701 return false;
702 }
703 }
704
Douglas Gregor78bd61f2009-06-18 16:11:24 +0000705 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner92028da2009-04-14 06:44:48 +0000707 // static, static inline, always_inline, and extern inline functions can
Chris Lattner02e987f2009-04-14 16:44:36 +0000708 // always be deferred. Normal inline functions can be deferred in C99/C++.
Douglas Gregorb14d1232010-03-13 18:23:07 +0000709 // Implicit template instantiations can also be deferred in C++.
Chris Lattnerbae0e682009-04-14 20:25:53 +0000710 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Eli Friedman2e06e8b2009-12-25 05:29:40 +0000711 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Chris Lattner92028da2009-04-14 06:44:48 +0000712 return true;
Chris Lattner92028da2009-04-14 06:44:48 +0000713 return false;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000714 }
Mike Stump11289f42009-09-09 15:08:12 +0000715
Chris Lattner92028da2009-04-14 06:44:48 +0000716 const VarDecl *VD = cast<VarDecl>(Global);
717 assert(VD->isFileVarDecl() && "Invalid decl");
Douglas Gregorbeecd582009-04-21 17:11:58 +0000718
Anders Carlssona18ed9b2009-10-08 17:28:59 +0000719 // We never want to defer structs that have non-trivial constructors or
720 // destructors.
721
722 // FIXME: Handle references.
723 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
724 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
725 if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
726 return false;
727 }
728 }
729
Eli Friedmanc96b2492010-06-19 06:24:06 +0000730 GVALinkage L = GetLinkageForVariable(getContext(), VD);
731 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
732 if (!(VD->getInit() && VD->getInit()->HasSideEffects(Context)))
733 return true;
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +0000734 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000735
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +0000736 return false;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000737}
738
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000739llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
740 const AliasAttr *AA = VD->getAttr<AliasAttr>();
741 assert(AA && "No alias?");
742
743 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
744
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000745 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000746 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000747
748 llvm::Constant *Aliasee;
749 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +0000750 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000751 else
John McCall7ec50432010-03-19 23:29:14 +0000752 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000753 llvm::PointerType::getUnqual(DeclTy), 0);
754 if (!Entry) {
755 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
756 F->setLinkage(llvm::Function::ExternalWeakLinkage);
757 WeakRefReferences.insert(F);
758 }
759
760 return Aliasee;
761}
762
Chris Lattnere0be0df2009-05-12 21:21:08 +0000763void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000764 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000765
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000766 // Weak references don't produce any output by themselves.
767 if (Global->hasAttr<WeakRefAttr>())
768 return;
769
Chris Lattner54041692009-03-22 21:47:11 +0000770 // If this is an alias definition (which otherwise looks like a declaration)
771 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000772 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000773 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000774
Chris Lattner45470942009-03-21 09:44:56 +0000775 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000776 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000777 // Forward declarations are emitted lazily on first use.
778 if (!FD->isThisDeclarationADefinition())
779 return;
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000780 } else {
781 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000782 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
783
Douglas Gregor61f6db52010-02-06 05:15:45 +0000784 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000785 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000786 }
787
Chris Lattner45470942009-03-21 09:44:56 +0000788 // Defer code generation when possible if this is a static definition, inline
789 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000790 if (!MayDeferGeneration(Global)) {
791 // Emit the definition if it can't be deferred.
792 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000793 return;
794 }
John McCall70013b62010-07-15 23:40:35 +0000795
796 // If we're deferring emission of a C++ variable with an
797 // initializer, remember the order in which it appeared in the file.
798 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
799 cast<VarDecl>(Global)->hasInit()) {
800 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
801 CXXGlobalInits.push_back(0);
802 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000803
804 // If the value has already been used, add it directly to the
805 // DeferredDeclsToEmit list.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000806 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000807 if (GetGlobalValue(MangledName))
808 DeferredDeclsToEmit.push_back(GD);
809 else {
810 // Otherwise, remember that we saw a deferred decl with this name. The
811 // first use of the mangled name will cause it to move into
812 // DeferredDeclsToEmit.
813 DeferredDecls[MangledName] = GD;
814 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000815}
816
Chris Lattnere0be0df2009-05-12 21:21:08 +0000817void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000818 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000819
Dan Gohman145f3f12010-04-19 16:39:44 +0000820 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000821 Context.getSourceManager(),
822 "Generating code for declaration");
823
Douglas Gregora700f682010-07-13 06:02:28 +0000824 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
825 // At -O0, don't generate IR for functions with available_externally
826 // linkage.
Douglas Gregor89976902010-07-15 22:58:18 +0000827 if (CodeGenOpts.OptimizationLevel == 0 &&
828 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregora700f682010-07-13 06:02:28 +0000829 getFunctionLinkage(Function)
830 == llvm::Function::AvailableExternallyLinkage)
831 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000832
Douglas Gregora700f682010-07-13 06:02:28 +0000833 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
834 if (Method->isVirtual())
835 getVTables().EmitThunks(GD);
836
837 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
838 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000839
Douglas Gregora700f682010-07-13 06:02:28 +0000840 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
841 return EmitCXXDestructor(DD, GD.getDtorType());
842 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000843
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000844 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000845 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000846
847 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
848 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000849
850 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000851}
852
Chris Lattnerd4808922009-03-22 21:03:39 +0000853/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
854/// module, create and return an llvm Function with the specified type. If there
855/// is something in the module with the specified name, return it potentially
856/// bitcasted to the right type.
857///
858/// If D is non-null, it specifies a decl that correspond to this. This is used
859/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000860llvm::Constant *
861CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
862 const llvm::Type *Ty,
863 GlobalDecl D) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000864 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000865 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000866 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000867 if (WeakRefReferences.count(Entry)) {
868 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
869 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000870 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000871
872 WeakRefReferences.erase(Entry);
873 }
874
Chris Lattnera85d68e2009-03-21 09:25:43 +0000875 if (Entry->getType()->getElementType() == Ty)
876 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000877
Chris Lattnera85d68e2009-03-21 09:25:43 +0000878 // Make sure the result is of the correct type.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000879 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Andersonade90fd2009-07-29 18:54:39 +0000880 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000881 }
Mike Stump11289f42009-09-09 15:08:12 +0000882
Eli Friedmancc522d92009-11-09 05:07:37 +0000883 // This function doesn't have a complete type (for example, the return
884 // type is an incomplete struct). Use a fake type instead, and make
885 // sure not to try to set attributes.
886 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +0000887
888 const llvm::FunctionType *FTy;
889 if (isa<llvm::FunctionType>(Ty)) {
890 FTy = cast<llvm::FunctionType>(Ty);
891 } else {
892 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
893 std::vector<const llvm::Type*>(), false);
Eli Friedmancc522d92009-11-09 05:07:37 +0000894 IsIncompleteFunction = true;
895 }
Chris Lattner5c740f12010-06-30 19:14:05 +0000896
John McCalld06fb862010-04-28 00:00:30 +0000897 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +0000898 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000899 MangledName, &getModule());
900 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +0000901 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +0000902 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedmancc522d92009-11-09 05:07:37 +0000903
Chris Lattner45470942009-03-21 09:44:56 +0000904 // This is the first use or definition of a mangled name. If there is a
905 // deferred decl with this name, remember that we need to emit it at the end
906 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000907 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000908 if (DDI != DeferredDecls.end()) {
909 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
910 // list, and remove it from DeferredDecls (since we don't need it anymore).
911 DeferredDeclsToEmit.push_back(DDI->second);
912 DeferredDecls.erase(DDI);
Chris Lattnere0be0df2009-05-12 21:21:08 +0000913 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
Chris Lattnerd035ebd2009-05-12 21:02:27 +0000914 // If this the first reference to a C++ inline function in a class, queue up
915 // the deferred function body for emission. These are not seen as
916 // top-level declarations.
Chris Lattnere0be0df2009-05-12 21:21:08 +0000917 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
918 DeferredDeclsToEmit.push_back(D);
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000919 // A called constructor which has no definition or declaration need be
920 // synthesized.
921 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Rafael Espindola70e040d2010-03-02 21:28:26 +0000922 if (CD->isImplicit()) {
Benjamin Kramerf0a0f682010-03-06 09:07:19 +0000923 assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
Eli Friedman84a7e342009-11-26 07:40:08 +0000924 DeferredDeclsToEmit.push_back(D);
Rafael Espindola70e040d2010-03-02 21:28:26 +0000925 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000926 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
Rafael Espindola70e040d2010-03-02 21:28:26 +0000927 if (DD->isImplicit()) {
Benjamin Kramerf0a0f682010-03-06 09:07:19 +0000928 assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
Eli Friedman84a7e342009-11-26 07:40:08 +0000929 DeferredDeclsToEmit.push_back(D);
Rafael Espindola70e040d2010-03-02 21:28:26 +0000930 }
Eli Friedman84a7e342009-11-26 07:40:08 +0000931 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
Rafael Espindola70e040d2010-03-02 21:28:26 +0000932 if (MD->isCopyAssignment() && MD->isImplicit()) {
Benjamin Kramerf0a0f682010-03-06 09:07:19 +0000933 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000934 DeferredDeclsToEmit.push_back(D);
Rafael Espindola70e040d2010-03-02 21:28:26 +0000935 }
Fariborz Jahanian6f14c732009-07-30 23:22:00 +0000936 }
Chris Lattner45470942009-03-21 09:44:56 +0000937 }
Mike Stump11289f42009-09-09 15:08:12 +0000938
John McCalld06fb862010-04-28 00:00:30 +0000939 // Make sure the result is of the requested type.
940 if (!IsIncompleteFunction) {
941 assert(F->getType()->getElementType() == Ty);
942 return F;
943 }
944
945 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
946 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000947}
948
Chris Lattnerd4808922009-03-22 21:03:39 +0000949/// GetAddrOfFunction - Return the address of the given function. If Ty is
950/// non-null, then this function will use the specified type if it has to
951/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +0000952llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattnerd4808922009-03-22 21:03:39 +0000953 const llvm::Type *Ty) {
954 // If there was no specific requested type, just convert it now.
955 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +0000956 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +0000957
Anders Carlssonea836bc2010-06-22 16:16:50 +0000958 llvm::StringRef MangledName = getMangledName(GD);
John McCall7ec50432010-03-19 23:29:14 +0000959 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattnerd4808922009-03-22 21:03:39 +0000960}
Eli Friedmanc18d9d52008-05-30 19:50:47 +0000961
Chris Lattnerd4808922009-03-22 21:03:39 +0000962/// CreateRuntimeFunction - Create a new runtime function with the specified
963/// type and name.
964llvm::Constant *
965CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCall7ec50432010-03-19 23:29:14 +0000966 llvm::StringRef Name) {
Chris Lattnere0be0df2009-05-12 21:21:08 +0000967 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattnerd4808922009-03-22 21:03:39 +0000968}
Daniel Dunbar9c426522008-07-29 23:18:29 +0000969
Eli Friedmanb095e152009-12-11 21:23:03 +0000970static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall340aafa2010-02-08 21:46:50 +0000971 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +0000972 return false;
973 if (Context.getLangOptions().CPlusPlus &&
974 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
975 // FIXME: We should do something fancier here!
976 return false;
977 }
978 return true;
979}
980
Chris Lattnerd4808922009-03-22 21:03:39 +0000981/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
982/// create and return an llvm GlobalVariable with the specified type. If there
983/// is something in the module with the specified name, return it potentially
984/// bitcasted to the right type.
985///
986/// If D is non-null, it specifies a decl that correspond to this. This is used
987/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000988llvm::Constant *
989CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
990 const llvm::PointerType *Ty,
991 const VarDecl *D) {
Daniel Dunbar829e9882008-08-05 23:31:02 +0000992 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000993 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +0000994 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000995 if (WeakRefReferences.count(Entry)) {
996 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000997 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000998
999 WeakRefReferences.erase(Entry);
1000 }
1001
Chris Lattnerd4808922009-03-22 21:03:39 +00001002 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001003 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001004
Chris Lattner3bfce182009-03-21 08:03:33 +00001005 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +00001006 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001007 }
Mike Stump11289f42009-09-09 15:08:12 +00001008
Chris Lattner45470942009-03-21 09:44:56 +00001009 // This is the first use or definition of a mangled name. If there is a
1010 // deferred decl with this name, remember that we need to emit it at the end
1011 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001012 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001013 if (DDI != DeferredDecls.end()) {
1014 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1015 // list, and remove it from DeferredDecls (since we don't need it anymore).
1016 DeferredDeclsToEmit.push_back(DDI->second);
1017 DeferredDecls.erase(DDI);
1018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
1020 llvm::GlobalVariable *GV =
1021 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +00001022 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001023 0, MangledName, 0,
Eli Friedman4f856742009-04-19 21:05:03 +00001024 false, Ty->getAddressSpace());
Chris Lattner3bfce182009-03-21 08:03:33 +00001025
1026 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001027 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001028 // FIXME: This code is overly simple and should be merged with other global
1029 // handling.
Eli Friedmanb095e152009-12-11 21:23:03 +00001030 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner3bfce182009-03-21 08:03:33 +00001031
Chris Lattnerd4808922009-03-22 21:03:39 +00001032 // FIXME: Merge with other attribute handling code.
1033 if (D->getStorageClass() == VarDecl::PrivateExtern)
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001034 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Chris Lattner3bfce182009-03-21 08:03:33 +00001035
Mike Stump11289f42009-09-09 15:08:12 +00001036 if (D->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001037 D->hasAttr<WeakImportAttr>())
Chris Lattnerd4808922009-03-22 21:03:39 +00001038 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Eli Friedman4f856742009-04-19 21:05:03 +00001039
1040 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +00001041 }
Mike Stump11289f42009-09-09 15:08:12 +00001042
John McCall7ec50432010-03-19 23:29:14 +00001043 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001044}
1045
Chris Lattnerd4808922009-03-22 21:03:39 +00001046
1047/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1048/// given global variable. If Ty is non-null and if the global doesn't exist,
1049/// then it will be greated with the specified type instead of whatever the
1050/// normal requested type would be.
1051llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1052 const llvm::Type *Ty) {
1053 assert(D->hasGlobalStorage() && "Not a global variable");
1054 QualType ASTTy = D->getType();
1055 if (Ty == 0)
1056 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001057
1058 const llvm::PointerType *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001059 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCall7ec50432010-03-19 23:29:14 +00001060
Anders Carlssonea836bc2010-06-22 16:16:50 +00001061 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001062 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001063}
1064
1065/// CreateRuntimeVariable - Create a new runtime global variable with the
1066/// specified type and name.
1067llvm::Constant *
1068CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCall7ec50432010-03-19 23:29:14 +00001069 llvm::StringRef Name) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001070 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
Chris Lattnerd4808922009-03-22 21:03:39 +00001071}
1072
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001073void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1074 assert(!D->getInit() && "Cannot emit definite definitions here!");
1075
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001076 if (MayDeferGeneration(D)) {
1077 // If we have not seen a reference to this variable yet, place it
1078 // into the deferred declarations table to be emitted if needed
1079 // later.
Anders Carlssonea836bc2010-06-22 16:16:50 +00001080 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001081 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001082 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001083 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001084 }
1085 }
1086
1087 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001088 EmitGlobalVarDefinition(D);
1089}
1090
Douglas Gregor88d292c2010-05-13 16:44:06 +00001091void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1092 if (DefinitionRequired)
1093 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1094}
1095
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001096llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001097CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregor2a34df32010-01-06 22:00:56 +00001098 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1099 return llvm::GlobalVariable::InternalLinkage;
1100
1101 if (const CXXMethodDecl *KeyFunction
1102 = RD->getASTContext().getKeyFunction(RD)) {
1103 // If this class has a key function, use that to determine the linkage of
1104 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001105 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001106 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001107 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001108
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001109 switch (KeyFunction->getTemplateSpecializationKind()) {
1110 case TSK_Undeclared:
1111 case TSK_ExplicitSpecialization:
1112 if (KeyFunction->isInlined())
1113 return llvm::GlobalVariable::WeakODRLinkage;
1114
1115 return llvm::GlobalVariable::ExternalLinkage;
1116
1117 case TSK_ImplicitInstantiation:
1118 case TSK_ExplicitInstantiationDefinition:
1119 return llvm::GlobalVariable::WeakODRLinkage;
1120
1121 case TSK_ExplicitInstantiationDeclaration:
1122 // FIXME: Use available_externally linkage. However, this currently
1123 // breaks LLVM's build due to undefined symbols.
1124 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1125 return llvm::GlobalVariable::WeakODRLinkage;
1126 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001127 }
1128
1129 switch (RD->getTemplateSpecializationKind()) {
1130 case TSK_Undeclared:
1131 case TSK_ExplicitSpecialization:
1132 case TSK_ImplicitInstantiation:
1133 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001134 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor2a34df32010-01-06 22:00:56 +00001135
1136 case TSK_ExplicitInstantiationDeclaration:
1137 // FIXME: Use available_externally linkage. However, this currently
1138 // breaks LLVM's build due to undefined symbols.
1139 // return llvm::GlobalVariable::AvailableExternallyLinkage;
1140 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001141 }
1142
1143 // Silence GCC warning.
1144 return llvm::GlobalVariable::WeakODRLinkage;
1145}
1146
Ken Dyck98ca7942010-01-26 13:48:07 +00001147CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1148 return CharUnits::fromQuantity(
1149 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1150}
1151
Daniel Dunbar9c426522008-07-29 23:18:29 +00001152void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001153 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001154 QualType ASTTy = D->getType();
Eli Friedman5866fe32010-01-08 00:50:11 +00001155 bool NonConstInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001156
Sebastian Redl5ca79842010-02-01 20:16:42 +00001157 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlssonca4a5452010-01-26 17:43:42 +00001158
1159 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001160 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001161 // implicitly initialized with { 0 }.
1162 //
1163 // Note that tentative definitions are only emitted at the end of
1164 // a translation unit, so they should never have incomplete
1165 // type. In addition, EmitTentativeDefinition makes sure that we
1166 // never attempt to emit a tentative definition if a real one
1167 // exists. A use may still exists, however, so we still may need
1168 // to do a RAUW.
1169 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001170 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001171 } else {
Douglas Gregord450f062010-05-05 20:15:55 +00001172 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman719ed1a2009-02-20 01:18:21 +00001173 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001174 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001175 if (D->getType()->isReferenceType())
1176 T = D->getType();
1177
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001178 if (getLangOptions().CPlusPlus) {
Eli Friedman5866fe32010-01-08 00:50:11 +00001179 EmitCXXGlobalVarDeclInitFunc(D);
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001180 Init = EmitNullConstant(T);
Eli Friedman5866fe32010-01-08 00:50:11 +00001181 NonConstInit = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001182 } else {
1183 ErrorUnsupported(D, "static initializer");
1184 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1185 }
John McCall70013b62010-07-15 23:40:35 +00001186 } else {
1187 // We don't need an initializer, so remove the entry for the delayed
1188 // initializer position (just in case this entry was delayed).
1189 if (getLangOptions().CPlusPlus)
1190 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001191 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001192 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001193
Chris Lattner64c55932009-03-21 08:13:05 +00001194 const llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001195 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Chris Lattner149927c2009-03-21 09:16:30 +00001197 // Strip off a bitcast if we got one back.
1198 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001199 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1200 // all zero index gep.
1201 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001202 Entry = CE->getOperand(0);
1203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Chris Lattner149927c2009-03-21 09:16:30 +00001205 // Entry is now either a Function or GlobalVariable.
1206 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001207
Chris Lattner149927c2009-03-21 09:16:30 +00001208 // We have a definition after a declaration with the wrong type.
1209 // We must make a new GlobalVariable* and update everything that used OldGV
1210 // (a declaration or tentative definition) with the new GlobalVariable*
1211 // (which will be a definition).
1212 //
1213 // This happens if there is a prototype for a global (e.g.
1214 // "extern int x[];") and then a definition of a different type (e.g.
1215 // "int x[10];"). This also happens when an initializer has a different type
1216 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001217 if (GV == 0 ||
1218 GV->getType()->getElementType() != InitType ||
1219 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump11289f42009-09-09 15:08:12 +00001220
John McCall7ec50432010-03-19 23:29:14 +00001221 // Move the old entry aside so that we'll create a new one.
1222 Entry->setName(llvm::StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001223
Chris Lattner149927c2009-03-21 09:16:30 +00001224 // Make a new global with the correct type, this is now guaranteed to work.
1225 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001226
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001227 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001228 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001229 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001230 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001231
1232 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001233 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001234 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001235
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001236 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +00001237 SourceManager &SM = Context.getSourceManager();
1238 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +00001239 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begemanfaae0812008-04-19 04:17:09 +00001240 }
1241
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001242 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001243
1244 // If it is safe to mark the global 'constant', do so now.
1245 GV->setConstant(false);
Eli Friedman5866fe32010-01-08 00:50:11 +00001246 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnerf49573d2009-08-05 05:20:29 +00001247 GV->setConstant(true);
Mike Stump11289f42009-09-09 15:08:12 +00001248
Ken Dyck160146e2010-01-27 17:10:57 +00001249 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Eli Friedman174d9c22008-05-29 11:10:27 +00001250
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001251 // Set the llvm linkage type as appropriate.
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001252 GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
Douglas Gregor819c3dd2009-10-14 21:36:34 +00001253 if (Linkage == GVA_Internal)
Chris Lattnerbc22b5b2008-05-04 01:44:26 +00001254 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001255 else if (D->hasAttr<DLLImportAttr>())
Chris Lattner84966392008-03-03 03:28:21 +00001256 GV->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001257 else if (D->hasAttr<DLLExportAttr>())
Chris Lattner84966392008-03-03 03:28:21 +00001258 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001259 else if (D->hasAttr<WeakAttr>()) {
1260 if (GV->isConstant())
1261 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1262 else
1263 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Douglas Gregorb14d1232010-03-13 18:23:07 +00001264 } else if (Linkage == GVA_TemplateInstantiation ||
1265 Linkage == GVA_ExplicitTemplateInstantiation)
1266 // FIXME: It seems like we can provide more specific linkage here
1267 // (LinkOnceODR, WeakODR).
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001268 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Daniel Dunbar2c11cd12009-11-30 08:40:34 +00001269 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
Chris Lattnerc0693bc2009-08-05 04:56:58 +00001270 !D->hasExternalStorage() && !D->getInit() &&
Chris Lattnerf49573d2009-08-05 05:20:29 +00001271 !D->getAttr<SectionAttr>()) {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001272 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001273 // common vars aren't constant even if declared const.
1274 GV->setConstant(false);
1275 } else
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001276 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001277
Daniel Dunbar38932572009-04-14 08:05:55 +00001278 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001279
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001280 // Emit global variable debug information.
Chris Lattner64c55932009-03-21 08:13:05 +00001281 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +00001282 DI->setLocation(D->getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001283 DI->EmitGlobalVariable(GV, D);
1284 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001285}
Chris Lattner09153c02007-06-22 18:48:09 +00001286
Chris Lattner36797ab2009-05-05 06:16:31 +00001287/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1288/// implement a function with no prototype, e.g. "int foo() {}". If there are
1289/// existing call uses of the old function in the module, this adjusts them to
1290/// call the new function directly.
1291///
1292/// This is not just a cleanup: the always_inline pass requires direct calls to
1293/// functions to be able to inline them. If there is a bitcast in the way, it
1294/// won't inline them. Instcombine normally deletes these calls, but it isn't
1295/// run at -O0.
1296static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1297 llvm::Function *NewFn) {
1298 // If we're redefining a global as a function, don't transform it.
1299 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1300 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001301
Chris Lattner36797ab2009-05-05 06:16:31 +00001302 const llvm::Type *NewRetTy = NewFn->getReturnType();
1303 llvm::SmallVector<llvm::Value*, 4> ArgList;
1304
1305 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001306 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001307 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001308 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1309 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greifd394aec2010-04-10 03:45:50 +00001310 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001311 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001312
Chris Lattner36797ab2009-05-05 06:16:31 +00001313 // If the return types don't match exactly, and if the call isn't dead, then
1314 // we can't transform this call.
1315 if (CI->getType() != NewRetTy && !CI->use_empty())
1316 continue;
1317
1318 // If the function was passed too few arguments, don't transform. If extra
1319 // arguments were passed, we silently drop them. If any of the types
1320 // mismatch, we don't transform.
1321 unsigned ArgNo = 0;
1322 bool DontTransform = false;
1323 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1324 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001325 if (CS.arg_size() == ArgNo ||
1326 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001327 DontTransform = true;
1328 break;
1329 }
1330 }
1331 if (DontTransform)
1332 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattner36797ab2009-05-05 06:16:31 +00001334 // Okay, we can transform this. Create the new call instruction and copy
1335 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001336 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattner36797ab2009-05-05 06:16:31 +00001337 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1338 ArgList.end(), "", CI);
1339 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001340 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001341 NewCall->takeName(CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001342 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001343 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001344
1345 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001346 if (!CI->use_empty())
1347 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001348
Chris Lattnere675d0f2010-04-01 06:31:43 +00001349 // Copy debug location attached to CI.
1350 if (!CI->getDebugLoc().isUnknown())
1351 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001352 CI->eraseFromParent();
1353 }
1354}
1355
Daniel Dunbar9c426522008-07-29 23:18:29 +00001356
Chris Lattnere0be0df2009-05-12 21:21:08 +00001357void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001358 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +00001359 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Fariborz Jahanian9eba9df2010-03-04 01:02:03 +00001360 getMangleContext().mangleInitDiscriminator();
Chris Lattnereb7466d2009-05-12 20:58:15 +00001361 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001362 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnera85d68e2009-03-21 09:25:43 +00001364 // Strip off a bitcast if we got one back.
1365 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1366 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1367 Entry = CE->getOperand(0);
1368 }
Mike Stump11289f42009-09-09 15:08:12 +00001369
1370
Chris Lattnera85d68e2009-03-21 09:25:43 +00001371 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001372 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001373
Daniel Dunbar99d28352009-03-09 23:53:08 +00001374 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001375 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001376 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001377
Chris Lattner5eaee562009-03-21 08:38:50 +00001378 // F is the Function* for the one with the wrong type, we must make a new
1379 // Function* and update everything that used F (a declaration) with the new
1380 // Function* (which will be a definition).
1381 //
1382 // This happens if there is a prototype for a function
1383 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001384 // (e.g. "int f(int x)"). Move the old function aside so that it
1385 // doesn't interfere with GetAddrOfFunction.
1386 OldFn->setName(llvm::StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001387 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner36797ab2009-05-05 06:16:31 +00001389 // If this is an implementation of a function without a prototype, try to
1390 // replace any existing uses of the function (which may be calls) with uses
1391 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001392 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001393 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001394 OldFn->removeDeadConstantUsers();
1395 }
Mike Stump11289f42009-09-09 15:08:12 +00001396
Chris Lattner5eaee562009-03-21 08:38:50 +00001397 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001398 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001399 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001400 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001401 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1402 }
Mike Stump11289f42009-09-09 15:08:12 +00001403
Chris Lattner5eaee562009-03-21 08:38:50 +00001404 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001405 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001406
Chris Lattnera85d68e2009-03-21 09:25:43 +00001407 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
Chris Lattnera85d68e2009-03-21 09:25:43 +00001410 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001411 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001412
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001413 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001414
Daniel Dunbar38932572009-04-14 08:05:55 +00001415 SetFunctionDefinitionAttributes(D, Fn);
1416 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001417
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001418 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001419 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001420 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001421 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar9c426522008-07-29 23:18:29 +00001422}
1423
John McCall7ec50432010-03-19 23:29:14 +00001424void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1425 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001426 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001427 assert(AA && "Not an alias?");
1428
Anders Carlssonea836bc2010-06-22 16:16:50 +00001429 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001430
John McCall7ec50432010-03-19 23:29:14 +00001431 // If there is a definition in the module, then it wins over the alias.
1432 // This is dubious, but allow it to be safe. Just ignore the alias.
1433 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1434 if (Entry && !Entry->isDeclaration())
1435 return;
1436
1437 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001438
1439 // Create a reference to the named value. This ensures that it is emitted
1440 // if a deferred decl.
1441 llvm::Constant *Aliasee;
1442 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +00001443 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattner54041692009-03-22 21:47:11 +00001444 else
John McCall7ec50432010-03-19 23:29:14 +00001445 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001446 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001447
1448 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001449 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001450 new llvm::GlobalAlias(Aliasee->getType(),
1451 llvm::Function::ExternalLinkage,
1452 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001453
Chris Lattner54041692009-03-22 21:47:11 +00001454 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001455 assert(Entry->isDeclaration());
1456
Chris Lattner54041692009-03-22 21:47:11 +00001457 // If there is a declaration in the module, then we had an extern followed
1458 // by the alias, as in:
1459 // extern int test6();
1460 // ...
1461 // int test6() __attribute__((alias("test7")));
1462 //
1463 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001464 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001465
Owen Andersonade90fd2009-07-29 18:54:39 +00001466 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001467 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001468 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001469 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001470 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001471 }
Mike Stump11289f42009-09-09 15:08:12 +00001472
Daniel Dunbar38932572009-04-14 08:05:55 +00001473 // Set attributes which are particular to an alias; this is a
1474 // specialization of the attributes which may be set on a global
1475 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001476 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001477 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001479 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001480 GA->setLinkage(llvm::Function::DLLExportLinkage);
1481 } else {
1482 GA->setLinkage(llvm::Function::DLLExportLinkage);
1483 }
Mike Stump11289f42009-09-09 15:08:12 +00001484 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001485 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001486 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001487 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1488 }
1489
1490 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001491}
1492
Chris Lattnere64911a2009-03-22 21:56:56 +00001493/// getBuiltinLibFunction - Given a builtin id for a function like
1494/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001495llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1496 unsigned BuiltinID) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001497 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump11289f42009-09-09 15:08:12 +00001498 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001499 "isn't a lib fn");
Mike Stump11289f42009-09-09 15:08:12 +00001500
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001501 // Get the name, skip over the __builtin_ prefix (if necessary).
1502 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1503 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1504 Name += 10;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Mike Stump11289f42009-09-09 15:08:12 +00001506 const llvm::FunctionType *Ty =
Eli Friedman4f678f32009-12-09 03:05:59 +00001507 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattner1eec6602007-08-31 04:31:45 +00001508
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001509 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattner1eec6602007-08-31 04:31:45 +00001510}
1511
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001512llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1513 unsigned NumTys) {
1514 return llvm::Intrinsic::getDeclaration(&getModule(),
1515 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1516}
Chris Lattner1eec6602007-08-31 04:31:45 +00001517
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001518
1519llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1520 const llvm::Type *SrcType,
1521 const llvm::Type *SizeType) {
1522 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1523 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
Chris Lattner09153c02007-06-22 18:48:09 +00001524}
Anders Carlssonb04ea612007-08-21 00:21:21 +00001525
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001526llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1527 const llvm::Type *SrcType,
1528 const llvm::Type *SizeType) {
1529 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1530 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
Eli Friedmandf649f32008-05-26 12:59:39 +00001531}
1532
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001533llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1534 const llvm::Type *SizeType) {
1535 const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1536 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
Lauro Ramos Venancio91fdb9e2008-02-19 22:01:01 +00001537}
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001538
Daniel Dunbar64509b22009-07-23 22:52:48 +00001539static llvm::StringMapEntry<llvm::Constant*> &
1540GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1541 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001542 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001543 bool &IsUTF16,
1544 unsigned &StringLength) {
Daniel Dunbar5de27da2009-09-22 03:27:52 +00001545 unsigned NumBytes = Literal->getByteLength();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001546
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001547 // Check for simple case.
1548 if (!Literal->containsNonAsciiOrNull()) {
1549 StringLength = NumBytes;
1550 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1551 StringLength));
1552 }
1553
Daniel Dunbar64509b22009-07-23 22:52:48 +00001554 // Otherwise, convert the UTF8 literals into a byte string.
1555 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1556 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1557 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001558
1559 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001560 &ToPtr, ToPtr + NumBytes,
1561 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Daniel Dunbar64509b22009-07-23 22:52:48 +00001563 // Check for conversion failure.
1564 if (Result != conversionOK) {
1565 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1566 // this duplicate code.
1567 assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001568 StringLength = NumBytes;
1569 return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1570 StringLength));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001571 }
1572
Daniel Dunbar91ade142009-07-23 23:41:22 +00001573 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001574 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001575
1576 // Render the UTF-16 string into a byte array and convert to the target byte
1577 // order.
1578 //
1579 // FIXME: This isn't something we should need to do here.
1580 llvm::SmallString<128> AsBytes;
1581 AsBytes.reserve(StringLength * 2);
1582 for (unsigned i = 0; i != StringLength; ++i) {
1583 unsigned short Val = ToBuf[i];
1584 if (TargetIsLSB) {
1585 AsBytes.push_back(Val & 0xFF);
1586 AsBytes.push_back(Val >> 8);
1587 } else {
1588 AsBytes.push_back(Val >> 8);
1589 AsBytes.push_back(Val & 0xFF);
1590 }
1591 }
Daniel Dunbar4d93a4f2009-08-03 21:47:08 +00001592 // Append one extra null character, the second is automatically added by our
1593 // caller.
1594 AsBytes.push_back(0);
Daniel Dunbar91ade142009-07-23 23:41:22 +00001595
Daniel Dunbar64509b22009-07-23 22:52:48 +00001596 IsUTF16 = true;
Daniel Dunbar91ade142009-07-23 23:41:22 +00001597 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001598}
1599
1600llvm::Constant *
1601CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1602 unsigned StringLength = 0;
1603 bool isUTF16 = false;
1604 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001605 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001606 getTargetData().isLittleEndian(),
1607 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001608
Daniel Dunbar64509b22009-07-23 22:52:48 +00001609 if (llvm::Constant *C = Entry.getValue())
1610 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001611
Owen Anderson41a75022009-08-13 21:57:51 +00001612 llvm::Constant *Zero =
1613 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbard644ad62008-08-23 18:37:06 +00001614 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001615
Chris Lattneraa64ca22009-07-16 16:48:25 +00001616 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001617 if (!CFConstantStringClassRef) {
1618 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001619 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001620 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001621 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001622 // Decay array -> ptr
1623 CFConstantStringClassRef =
Owen Andersonade90fd2009-07-29 18:54:39 +00001624 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001625 }
Mike Stump11289f42009-09-09 15:08:12 +00001626
Anders Carlssonc2480a52008-11-15 18:54:24 +00001627 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001628
Mike Stump11289f42009-09-09 15:08:12 +00001629 const llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001630 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1631
Anders Carlsson157c3212009-08-16 05:55:31 +00001632 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor91f84212008-12-11 16:49:14 +00001633
Anders Carlssonb04ea612007-08-21 00:21:21 +00001634 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001635 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001636
Anders Carlssonb04ea612007-08-21 00:21:21 +00001637 // Flags.
Daniel Dunbard644ad62008-08-23 18:37:06 +00001638 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001639 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001640 llvm::ConstantInt::get(Ty, 0x07C8);
1641
Anders Carlssonb04ea612007-08-21 00:21:21 +00001642 // String pointer.
Owen Anderson41a75022009-08-13 21:57:51 +00001643 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001644
Chris Lattner3afa3e12009-07-16 05:03:48 +00001645 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001646 bool isConstant;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001647 if (isUTF16) {
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001648 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00001649 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001650 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1651 // does make plain ascii ones writable.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001652 isConstant = true;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001653 } else {
1654 Linkage = llvm::GlobalValue::PrivateLinkage;
1655 isConstant = !Features.WritableStrings;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001656 }
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001657
Mike Stump11289f42009-09-09 15:08:12 +00001658 llvm::GlobalVariable *GV =
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001659 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1660 ".str");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001661 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00001662 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1663 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001664 }
Anders Carlsson157c3212009-08-16 05:55:31 +00001665 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1666
Anders Carlssonb04ea612007-08-21 00:21:21 +00001667 // String length.
1668 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00001669 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001670
Anders Carlssonb04ea612007-08-21 00:21:21 +00001671 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00001672 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00001673 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1674 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001675 "_unnamed_cfstring_");
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001676 if (const char *Sect = getContext().Target.getCFStringSection())
1677 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00001678 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00001679
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00001680 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00001681}
Chris Lattnerfb300092007-11-28 05:34:05 +00001682
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001683llvm::Constant *
1684CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001685 unsigned StringLength = 0;
1686 bool isUTF16 = false;
1687 llvm::StringMapEntry<llvm::Constant*> &Entry =
1688 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1689 getTargetData().isLittleEndian(),
1690 isUTF16, StringLength);
1691
1692 if (llvm::Constant *C = Entry.getValue())
1693 return C;
1694
1695 llvm::Constant *Zero =
1696 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1697 llvm::Constant *Zeros[] = { Zero, Zero };
1698
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001699 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001700 if (!NSConstantStringClassRef) {
1701 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1702 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001703 llvm::Constant *GV = CreateRuntimeVariable(Ty,
1704 Features.ObjCNonFragileABI ?
1705 "OBJC_CLASS_$_NSConstantString" :
1706 "_NSConstantStringClassReference");
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001707 // Decay array -> ptr
1708 NSConstantStringClassRef =
1709 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1710 }
1711
1712 QualType NSTy = getContext().getNSConstantStringType();
1713
1714 const llvm::StructType *STy =
1715 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1716
1717 std::vector<llvm::Constant*> Fields(3);
1718
1719 // Class pointer.
1720 Fields[0] = NSConstantStringClassRef;
1721
1722 // String pointer.
1723 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1724
1725 llvm::GlobalValue::LinkageTypes Linkage;
1726 bool isConstant;
1727 if (isUTF16) {
1728 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1729 Linkage = llvm::GlobalValue::InternalLinkage;
1730 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1731 // does make plain ascii ones writable.
1732 isConstant = true;
1733 } else {
1734 Linkage = llvm::GlobalValue::PrivateLinkage;
1735 isConstant = !Features.WritableStrings;
1736 }
1737
1738 llvm::GlobalVariable *GV =
1739 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1740 ".str");
1741 if (isUTF16) {
1742 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1743 GV->setAlignment(Align.getQuantity());
1744 }
1745 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1746
1747 // String length.
1748 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1749 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1750
1751 // The struct.
1752 C = llvm::ConstantStruct::get(STy, Fields);
1753 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1754 llvm::GlobalVariable::PrivateLinkage, C,
1755 "_unnamed_nsstring_");
1756 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001757 if (const char *Sect =
1758 Features.ObjCNonFragileABI
1759 ? getContext().Target.getNSStringNonFragileABISection()
1760 : getContext().Target.getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001761 GV->setSection(Sect);
1762 Entry.setValue(GV);
1763
1764 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001765}
1766
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001767/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001768/// string literal, properly padded to match the literal type.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001769std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001770 const char *StrData = E->getStrData();
1771 unsigned Len = E->getByteLength();
1772
1773 const ConstantArrayType *CAT =
1774 getContext().getAsConstantArrayType(E->getType());
1775 assert(CAT && "String isn't pointer or array!");
Mike Stump11289f42009-09-09 15:08:12 +00001776
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001777 // Resize the string to the right size.
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001778 std::string Str(StrData, StrData+Len);
1779 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001780
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001781 if (E->isWide())
1782 RealLen *= getContext().Target.getWCharWidth()/8;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001784 Str.resize(RealLen, '\0');
Mike Stump11289f42009-09-09 15:08:12 +00001785
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001786 return Str;
1787}
1788
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001789/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1790/// constant array for the given string literal.
1791llvm::Constant *
1792CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1793 // FIXME: This can be more efficient.
Eli Friedman49ddc5f2009-11-16 05:55:46 +00001794 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1795 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1796 if (S->isWide()) {
1797 llvm::Type *DestTy =
1798 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1799 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1800 }
1801 return C;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001802}
1803
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001804/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1805/// array for the given ObjCEncodeExpr node.
1806llvm::Constant *
1807CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1808 std::string Str;
1809 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00001810
1811 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001812}
1813
1814
Chris Lattner36fc8792008-02-11 00:02:17 +00001815/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001816static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattnerfb300092007-11-28 05:34:05 +00001817 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001818 CodeGenModule &CGM,
1819 const char *GlobalName) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001820 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00001821 llvm::Constant *C =
1822 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Chris Lattnerfb300092007-11-28 05:34:05 +00001824 // Create a global variable for this string
Mike Stump11289f42009-09-09 15:08:12 +00001825 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001826 llvm::GlobalValue::PrivateLinkage,
Owen Andersonc10c8d32009-07-08 19:05:04 +00001827 C, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001828}
1829
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001830/// GetAddrOfConstantString - Returns a pointer to a character array
1831/// containing the literal. This contents are exactly that of the
1832/// given string, i.e. it will not be null terminated automatically;
1833/// see GetAddrOfConstantCString. Note that whether the result is
1834/// actually a pointer to an LLVM constant depends on
1835/// Feature.WriteableStrings.
1836///
1837/// The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001838llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1839 const char *GlobalName) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001840 bool IsConstant = !Features.WritableStrings;
1841
1842 // Get the default prefix if a name wasn't specified.
1843 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00001844 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001845
1846 // Don't share any string literals if strings aren't constant.
1847 if (!IsConstant)
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001848 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump11289f42009-09-09 15:08:12 +00001849
1850 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner3afa3e12009-07-16 05:03:48 +00001851 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattnerfb300092007-11-28 05:34:05 +00001852
1853 if (Entry.getValue())
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001854 return Entry.getValue();
Chris Lattnerfb300092007-11-28 05:34:05 +00001855
1856 // Create a global variable for this.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001857 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001858 Entry.setValue(C);
1859 return C;
1860}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001861
1862/// GetAddrOfConstantCString - Returns a pointer to a character
1863/// array containing the literal and a terminating '\-'
1864/// character. The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001865llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1866 const char *GlobalName){
Chris Lattner2e41b0e2008-12-09 19:10:54 +00001867 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001868}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001869
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001870/// EmitObjCPropertyImplementations - Emit information for synthesized
1871/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00001872void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001873 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001874 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001875 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001876 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00001877
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001878 // Dynamic is just for type-checking.
1879 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1880 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1881
1882 // Determine which methods need to be implemented, some may have
1883 // been overridden. Note that ::isSynthesized is not the method
1884 // we want, that just indicates if the decl came from a
1885 // property. What we want to know is if the method is defined in
1886 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001887 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001888 CodeGenFunction(*this).GenerateObjCGetter(
1889 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001890 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001891 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001892 CodeGenFunction(*this).GenerateObjCSetter(
1893 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001894 }
1895 }
1896}
1897
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001898/// EmitObjCIvarInitializations - Emit information for ivar initialization
1899/// for an implementation.
1900void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1901 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1902 return;
1903 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1904 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1905 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1906 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1907 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1908 D->getLocation(),
1909 D->getLocation(), cxxSelector,
1910 getContext().VoidTy, 0,
1911 DC, true, false, true,
1912 ObjCMethodDecl::Required);
1913 D->addInstanceMethod(DTORMethod);
1914 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1915
1916 II = &getContext().Idents.get(".cxx_construct");
1917 cxxSelector = getContext().Selectors.getSelector(0, &II);
1918 // The constructor returns 'self'.
1919 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1920 D->getLocation(),
1921 D->getLocation(), cxxSelector,
1922 getContext().getObjCIdType(), 0,
1923 DC, true, false, true,
1924 ObjCMethodDecl::Required);
1925 D->addInstanceMethod(CTORMethod);
1926 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1927
1928
1929}
1930
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001931/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00001932void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001933 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00001934 I != E; ++I)
1935 EmitTopLevelDecl(*I);
1936}
1937
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001938// EmitLinkageSpec - Emit all declarations in a linkage spec.
1939void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00001940 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1941 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001942 ErrorUnsupported(LSD, "linkage spec");
1943 return;
1944 }
1945
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001946 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001947 I != E; ++I)
1948 EmitTopLevelDecl(*I);
1949}
1950
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001951/// EmitTopLevelDecl - Emit code for a single top level declaration.
1952void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1953 // If an error has occurred, stop code generation, but continue
1954 // parsing and semantic analysis (to ensure all warnings and errors
1955 // are emitted).
1956 if (Diags.hasErrorOccurred())
1957 return;
1958
Douglas Gregor70d83e22009-06-29 17:30:29 +00001959 // Ignore dependent declarations.
1960 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1961 return;
Mike Stump11289f42009-09-09 15:08:12 +00001962
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001963 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00001964 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00001965 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001966 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00001967 // Skip function templates
1968 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1969 return;
Mike Stump11289f42009-09-09 15:08:12 +00001970
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001971 EmitGlobal(cast<FunctionDecl>(D));
1972 break;
1973
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001974 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001975 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001976 break;
1977
Anders Carlssonf7475242009-04-15 15:55:24 +00001978 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001979 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00001980 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001981 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00001982 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00001983 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00001984 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00001985 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001986 case Decl::ClassTemplate:
1987 case Decl::FunctionTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00001988 case Decl::NamespaceAlias:
Douglas Gregorfec52632009-06-20 00:51:54 +00001989 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00001990 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00001991 // Skip function templates
1992 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1993 return;
1994
Anders Carlssonf7475242009-04-15 15:55:24 +00001995 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1996 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00001997 case Decl::CXXDestructor:
1998 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1999 break;
Anders Carlsson87835432009-06-11 21:22:55 +00002000
2001 case Decl::StaticAssert:
2002 // Nothing to do.
2003 break;
2004
Anders Carlssonf7475242009-04-15 15:55:24 +00002005 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00002006
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002007 // Forward declarations, no (immediate) code generation.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002008 case Decl::ObjCClass:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002009 case Decl::ObjCForwardProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002010 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002011 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002012 break;
2013
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002014 case Decl::ObjCProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002015 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002016 break;
2017
2018 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002019 // Categories have properties but don't support synthesize so we
2020 // can ignore them here.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002021 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2022 break;
2023
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002024 case Decl::ObjCImplementation: {
2025 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2026 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002027 EmitObjCIvarInitializations(OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002028 Runtime->GenerateClass(OMD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002029 break;
Mike Stump11289f42009-09-09 15:08:12 +00002030 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002031 case Decl::ObjCMethod: {
2032 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2033 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002034 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002035 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2036 break;
2037 }
Mike Stump11289f42009-09-09 15:08:12 +00002038 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian17290c32009-01-08 01:10:55 +00002039 // compatibility-alias is a directive and has no code gen.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002040 break;
2041
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002042 case Decl::LinkageSpec:
2043 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002044 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002045
2046 case Decl::FileScopeAsm: {
2047 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002048 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002049
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002050 const std::string &S = getModule().getModuleInlineAsm();
2051 if (S.empty())
2052 getModule().setModuleInlineAsm(AsmString);
2053 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002054 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002055 break;
2056 }
Mike Stump11289f42009-09-09 15:08:12 +00002057
2058 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002059 // Make sure we handled everything we should, every other kind is a
2060 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2061 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002062 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2063 }
2064}
John McCall09ae0322010-07-06 23:57:41 +00002065
2066/// Turns the given pointer into a constant.
2067static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2068 const void *Ptr) {
2069 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2070 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2071 return llvm::ConstantInt::get(i64, PtrInt);
2072}
2073
2074static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2075 llvm::NamedMDNode *&GlobalMetadata,
2076 GlobalDecl D,
2077 llvm::GlobalValue *Addr) {
2078 if (!GlobalMetadata)
2079 GlobalMetadata =
2080 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2081
2082 // TODO: should we report variant information for ctors/dtors?
2083 llvm::Value *Ops[] = {
2084 Addr,
2085 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2086 };
2087 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2088}
2089
2090/// Emits metadata nodes associating all the global values in the
2091/// current module with the Decls they came from. This is useful for
2092/// projects using IR gen as a subroutine.
2093///
2094/// Since there's currently no way to associate an MDNode directly
2095/// with an llvm::GlobalValue, we create a global named metadata
2096/// with the name 'clang.global.decl.ptrs'.
2097void CodeGenModule::EmitDeclMetadata() {
2098 llvm::NamedMDNode *GlobalMetadata = 0;
2099
2100 // StaticLocalDeclMap
2101 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2102 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2103 I != E; ++I) {
2104 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2105 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2106 }
2107}
2108
2109/// Emits metadata nodes for all the local variables in the current
2110/// function.
2111void CodeGenFunction::EmitDeclMetadata() {
2112 if (LocalDeclMap.empty()) return;
2113
2114 llvm::LLVMContext &Context = getLLVMContext();
2115
2116 // Find the unique metadata ID for this name.
2117 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2118
2119 llvm::NamedMDNode *GlobalMetadata = 0;
2120
2121 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2122 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2123 const Decl *D = I->first;
2124 llvm::Value *Addr = I->second;
2125
2126 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2127 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2128 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2129 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2130 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2131 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2132 }
2133 }
2134}