blob: 9ac68718a5c1a6945e29ccd65e92e00b4bc1861e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5f2bfd42009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000025#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000026#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000028#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000029#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000030#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000032#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033using namespace clang;
34using namespace CodeGen;
35
36
Chris Lattnerbd360642009-03-26 05:00:52 +000037CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattnerfb97b032007-12-02 01:40:18 +000038 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerbd360642009-03-26 05:00:52 +000039 Diagnostic &diags)
40 : BlockModule(C, M, TD, Types, *this), Context(C),
41 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
Mike Stump2a998142009-03-04 18:17:45 +000042 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
43 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000044
Chris Lattner3c8f1532009-03-21 07:12:05 +000045 if (!Features.ObjC1)
46 Runtime = 0;
47 else if (!Features.NeXTRuntime)
48 Runtime = CreateGNUObjCRuntime(*this);
49 else if (Features.ObjCNonFragileABI)
50 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
51 else
52 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000053
54 // If debug info generation is enabled, create the CGDebugInfo object.
Devang Patel61b5f3e2009-07-14 02:47:58 +000055 DebugInfo = 0;
56 if (CompileOpts.DebugInfo)
57 DebugInfo = new CGDebugInfo(this, &Context.Target);
Chris Lattner2b94fe32008-03-01 08:45:05 +000058}
59
60CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000061 delete Runtime;
62 delete DebugInfo;
63}
64
65void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +000066 EmitDeferred();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000067 if (Runtime)
68 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
69 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000070 EmitCtorList(GlobalCtors, "llvm.global_ctors");
71 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000072 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000073 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000074}
75
Daniel Dunbar488e9932008-08-16 00:56:44 +000076/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000077/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000078void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
79 bool OmitOnError) {
80 if (OmitOnError && getDiags().hasErrorOccurred())
81 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000082 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000083 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +000084 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000085 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
86 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +000087}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000088
Daniel Dunbar488e9932008-08-16 00:56:44 +000089/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000090/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000091void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
92 bool OmitOnError) {
93 if (OmitOnError && getDiags().hasErrorOccurred())
94 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000095 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000096 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +000097 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000098 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +000099}
100
Daniel Dunbar04d40782009-04-14 06:00:08 +0000101LangOptions::VisibilityMode
102CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
103 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
104 if (VD->getStorageClass() == VarDecl::PrivateExtern)
105 return LangOptions::Hidden;
106
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000107 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000108 switch (attr->getVisibility()) {
109 default: assert(0 && "Unknown visibility!");
110 case VisibilityAttr::DefaultVisibility:
111 return LangOptions::Default;
112 case VisibilityAttr::HiddenVisibility:
113 return LangOptions::Hidden;
114 case VisibilityAttr::ProtectedVisibility:
115 return LangOptions::Protected;
116 }
117 }
118
119 return getLangOptions().getVisibilityMode();
120}
121
122void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
123 const Decl *D) const {
124 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000125 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000126 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000127 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000128 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000129
Daniel Dunbar04d40782009-04-14 06:00:08 +0000130 switch (getDeclVisibilityMode(D)) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000131 default: assert(0 && "Unknown visibility!");
Daniel Dunbar04d40782009-04-14 06:00:08 +0000132 case LangOptions::Default:
133 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
134 case LangOptions::Hidden:
135 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
136 case LangOptions::Protected:
137 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
Dan Gohman4f8d1232008-05-22 00:50:06 +0000138 }
139}
140
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000141const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
142 const NamedDecl *ND = GD.getDecl();
143
144 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
145 return getMangledCXXCtorName(D, GD.getCtorType());
146 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
147 return getMangledCXXDtorName(D, GD.getDtorType());
148
149 return getMangledName(ND);
150}
151
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000152/// \brief Retrieves the mangled name for the given declaration.
153///
154/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000155/// const char* containing the mangled name. Otherwise, returns
156/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000157///
Douglas Gregor6ec36682009-02-18 23:53:56 +0000158const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000159 // In C, functions with no attributes never need to be mangled. Fastpath them.
160 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
161 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000162 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000163 }
164
Douglas Gregor6ec36682009-02-18 23:53:56 +0000165 llvm::SmallString<256> Name;
166 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000167 if (!mangleName(ND, Context, Out)) {
168 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000169 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000170 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000171
Douglas Gregor6ec36682009-02-18 23:53:56 +0000172 Name += '\0';
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000173 return UniqueMangledName(Name.begin(), Name.end());
174}
175
176const char *CodeGenModule::UniqueMangledName(const char *NameStart,
177 const char *NameEnd) {
178 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
179
180 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000181}
182
Chris Lattner6d397602008-03-14 17:18:18 +0000183/// AddGlobalCtor - Add a function to the list that will be called before
184/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000185void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000186 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000187 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000188}
189
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000190/// AddGlobalDtor - Add a function to the list that will be called
191/// when the module is unloaded.
192void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000193 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000194 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
195}
196
197void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
198 // Ctor function type is void()*.
199 llvm::FunctionType* CtorFTy =
200 llvm::FunctionType::get(llvm::Type::VoidTy,
201 std::vector<const llvm::Type*>(),
202 false);
203 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
204
205 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000206 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000207 llvm::StructType::get(llvm::Type::Int32Ty,
208 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000209
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000210 // Construct the constructor and destructor arrays.
211 std::vector<llvm::Constant*> Ctors;
212 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
213 std::vector<llvm::Constant*> S;
214 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
215 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
216 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000217 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000218
219 if (!Ctors.empty()) {
220 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000221 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000222 llvm::GlobalValue::AppendingLinkage,
223 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000224 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000225 }
Chris Lattner6d397602008-03-14 17:18:18 +0000226}
227
Nate Begeman532485c2008-04-18 23:43:57 +0000228void CodeGenModule::EmitAnnotations() {
229 if (Annotations.empty())
230 return;
231
232 // Create a new global variable for the ConstantStruct in the Module.
233 llvm::Constant *Array =
234 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
235 Annotations.size()),
236 Annotations);
237 llvm::GlobalValue *gv =
Owen Anderson1c431b32009-07-08 19:05:04 +0000238 new llvm::GlobalVariable(TheModule, Array->getType(), false,
Nate Begeman532485c2008-04-18 23:43:57 +0000239 llvm::GlobalValue::AppendingLinkage, Array,
Owen Anderson1c431b32009-07-08 19:05:04 +0000240 "llvm.global.annotations");
Nate Begeman532485c2008-04-18 23:43:57 +0000241 gv->setSection("llvm.metadata");
242}
243
Chris Lattner86daeee2009-04-14 16:44:36 +0000244static CodeGenModule::GVALinkage
Douglas Gregor68584ed2009-06-18 16:11:24 +0000245GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
246 const LangOptions &Features) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000247 // The kind of external linkage this function will have, if it is not
248 // inline or static.
249 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
250 if (Context.getLangOptions().CPlusPlus &&
251 (FD->getPrimaryTemplate() || FD->getInstantiatedFromMemberFunction()) &&
252 !FD->isExplicitSpecialization())
253 External = CodeGenModule::GVA_TemplateInstantiation;
254
Anders Carlsson167b8242009-05-15 18:35:39 +0000255 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
256 // C++ member functions defined inside the class are always inline.
Argyrios Kyrtzidisf5cecfb2009-06-17 22:49:50 +0000257 if (MD->isInline() || !MD->isOutOfLine())
Anders Carlsson167b8242009-05-15 18:35:39 +0000258 return CodeGenModule::GVA_CXXInline;
259
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000260 return External;
Anders Carlsson167b8242009-05-15 18:35:39 +0000261 }
262
Eli Friedman43907e82009-05-03 19:01:39 +0000263 // "static" functions get internal linkage.
Eli Friedman5e222132009-05-03 18:13:43 +0000264 if (FD->getStorageClass() == FunctionDecl::Static)
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000265 return CodeGenModule::GVA_Internal;
266
Chris Lattner005eedc2009-05-12 20:26:52 +0000267 if (!FD->isInline())
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000268 return External;
Chris Lattner86daeee2009-04-14 16:44:36 +0000269
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000270 // If the inline function explicitly has the GNU inline attribute on it, or if
271 // this is C89 mode, we use to GNU semantics.
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000272 if (!Features.C99 && !Features.CPlusPlus) {
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000273 // extern inline in GNU mode is like C99 inline.
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000274 if (FD->getStorageClass() == FunctionDecl::Extern)
275 return CodeGenModule::GVA_C99Inline;
276 // Normal inline is a strong symbol.
277 return CodeGenModule::GVA_StrongExternal;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000278 } else if (FD->hasActiveGNUInlineAttribute(Context)) {
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000279 // GCC in C99 mode seems to use a different decision-making
280 // process for extern inline, which factors in previous
281 // declarations.
Douglas Gregor68584ed2009-06-18 16:11:24 +0000282 if (FD->isExternGNUInline(Context))
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000283 return CodeGenModule::GVA_C99Inline;
284 // Normal inline is a strong symbol.
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000285 return External;
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000286 }
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000287
Chris Lattner86daeee2009-04-14 16:44:36 +0000288 // The definition of inline changes based on the language. Note that we
289 // have already handled "static inline" above, with the GVA_Internal case.
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000290 if (Features.CPlusPlus) // inline and extern inline.
Chris Lattner86daeee2009-04-14 16:44:36 +0000291 return CodeGenModule::GVA_CXXInline;
292
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000293 assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode");
Douglas Gregorb3efa982009-04-23 18:22:55 +0000294 if (FD->isC99InlineDefinition())
295 return CodeGenModule::GVA_C99Inline;
296
297 return CodeGenModule::GVA_StrongExternal;
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000298}
299
300/// SetFunctionDefinitionAttributes - Set attributes for a global.
Daniel Dunbarb97b6922009-04-14 06:19:49 +0000301///
Mike Stumpf5408fe2009-05-16 07:57:57 +0000302/// FIXME: This is currently only done for aliases and functions, but not for
303/// variables (these details are set in EmitGlobalVarDefinition for variables).
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000304void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
305 llvm::GlobalValue *GV) {
Douglas Gregor68584ed2009-06-18 16:11:24 +0000306 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000307
Daniel Dunbar55d6f502009-04-14 07:19:20 +0000308 if (Linkage == GVA_Internal) {
Chris Lattner9f942792009-04-14 05:33:52 +0000309 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000310 } else if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000311 GV->setLinkage(llvm::Function::DLLExportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000312 } else if (D->hasAttr<WeakAttr>()) {
Chris Lattner44b0bc02009-04-14 06:04:17 +0000313 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000314 } else if (Linkage == GVA_C99Inline) {
315 // In C99 mode, 'inline' functions are guaranteed to have a strong
316 // definition somewhere else, so we can use available_externally linkage.
Chris Lattnerd9d049a2009-04-14 06:27:57 +0000317 GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000318 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
Chris Lattner86daeee2009-04-14 16:44:36 +0000319 // In C++, the compiler has to emit a definition in every translation unit
320 // that references the function. We should use linkonce_odr because
321 // a) if all references in this translation unit are optimized away, we
322 // don't need to codegen it. b) if the function persists, it needs to be
323 // merged with other definitions. c) C++ has the ODR, so we know the
324 // definition is dependable.
325 GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000326 } else {
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000327 assert(Linkage == GVA_StrongExternal);
328 // Otherwise, we have strong external linkage.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000329 GV->setLinkage(llvm::Function::ExternalLinkage);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000330 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000331
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000332 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000333}
334
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000335void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
336 const CGFunctionInfo &Info,
337 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000338 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000339 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000340
Devang Patel761d7f72008-09-25 21:02:23 +0000341 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
342 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000343
344 // Set the appropriate calling convention for the Function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000345 if (D->hasAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000346 F->setCallingConv(llvm::CallingConv::X86_FastCall);
347
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000348 if (D->hasAttr<StdCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000349 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000350}
351
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000352void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
353 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000354 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000355 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000356
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000357 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000358 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000359
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000360 if (D->hasAttr<NoinlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000361 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000362}
363
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000364void CodeGenModule::SetCommonAttributes(const Decl *D,
365 llvm::GlobalValue *GV) {
366 setGlobalVisibility(GV, D);
367
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000368 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000369 AddUsedGlobal(GV);
370
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000371 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000372 GV->setSection(SA->getName());
373}
374
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000375void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
376 llvm::Function *F,
377 const CGFunctionInfo &FI) {
378 SetLLVMFunctionAttributes(D, FI, F);
379 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000380
381 F->setLinkage(llvm::Function::InternalLinkage);
382
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000383 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000384}
385
386void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000387 llvm::Function *F,
388 bool IsIncompleteFunction) {
389 if (!IsIncompleteFunction)
390 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000391
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000392 // Only a few attributes are set on declarations; these may later be
393 // overridden by a definition.
394
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000395 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000396 F->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000397 } else if (FD->hasAttr<WeakAttr>() ||
398 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000399 // "extern_weak" is overloaded in LLVM; we probably should have
400 // separate linkage types for this.
401 F->setLinkage(llvm::Function::ExternalWeakLinkage);
402 } else {
403 F->setLinkage(llvm::Function::ExternalLinkage);
404 }
405
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000406 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000407 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000408}
409
Daniel Dunbar02698712009-02-13 20:29:50 +0000410void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
411 assert(!GV->isDeclaration() &&
412 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000413 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000414}
415
416void CodeGenModule::EmitLLVMUsed() {
417 // Don't create llvm.used if there is no need.
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000418 // FIXME. Runtime indicates that there might be more 'used' symbols; but not
419 // necessariy. So, this test is not accurate for emptiness.
420 if (LLVMUsed.empty() && !Runtime)
Daniel Dunbar02698712009-02-13 20:29:50 +0000421 return;
422
Chris Lattner35f38a22009-03-31 22:37:52 +0000423 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Chris Lattner35f38a22009-03-31 22:37:52 +0000424
425 // Convert LLVMUsed to what ConstantArray needs.
426 std::vector<llvm::Constant*> UsedArray;
427 UsedArray.resize(LLVMUsed.size());
428 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
429 UsedArray[i] =
430 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
431 }
432
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000433 if (Runtime)
434 Runtime->MergeMetadataGlobals(UsedArray);
435 if (UsedArray.empty())
436 return;
437 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
438
Daniel Dunbar02698712009-02-13 20:29:50 +0000439 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +0000440 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000441 llvm::GlobalValue::AppendingLinkage,
Chris Lattner35f38a22009-03-31 22:37:52 +0000442 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000443 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000444
445 GV->setSection("llvm.metadata");
446}
447
448void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000449 // Emit code for any potentially referenced deferred decls. Since a
450 // previously unused static decl may become used during the generation of code
451 // for a static function, iterate until no changes are made.
452 while (!DeferredDeclsToEmit.empty()) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000453 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000454 DeferredDeclsToEmit.pop_back();
455
456 // The mangled name for the decl must have been emitted in GlobalDeclMap.
457 // Look it up to see if it was defined with a stronger definition (e.g. an
458 // extern inline function with a strong function redefinition). If so,
459 // just ignore the deferred decl.
460 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
461 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000462
Chris Lattner67b00522009-03-21 09:44:56 +0000463 if (!CGRef->isDeclaration())
464 continue;
465
466 // Otherwise, emit the definition and move on to the next one.
467 EmitGlobalDefinition(D);
468 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000469}
470
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000471/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
472/// annotation information for a given GlobalValue. The annotation struct is
473/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000474/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000475/// created from the AnnotateAttr's annotation. The third field is a constant
476/// string containing the name of the translation unit. The fourth field is
477/// the line number in the file of the annotated value declaration.
478///
479/// FIXME: this does not unique the annotation string constants, as llvm-gcc
480/// appears to.
481///
482llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
483 const AnnotateAttr *AA,
484 unsigned LineNo) {
485 llvm::Module *M = &getModule();
486
487 // get [N x i8] constants for the annotation string, and the filename string
488 // which are the 2nd and 3rd elements of the global annotation structure.
489 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
490 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
491 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
492 true);
493
494 // Get the two global values corresponding to the ConstantArrays we just
495 // created to hold the bytes of the strings.
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000496 const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000497 llvm::GlobalValue *annoGV =
Owen Anderson1c431b32009-07-08 19:05:04 +0000498 new llvm::GlobalVariable(*M, anno->getType(), false,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000499 llvm::GlobalValue::InternalLinkage, anno,
Owen Anderson1c431b32009-07-08 19:05:04 +0000500 GV->getName() + StringPrefix);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000501 // translation unit name string, emitted into the llvm.metadata section.
502 llvm::GlobalValue *unitGV =
Owen Anderson1c431b32009-07-08 19:05:04 +0000503 new llvm::GlobalVariable(*M, unit->getType(), false,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000504 llvm::GlobalValue::InternalLinkage, unit,
Owen Anderson1c431b32009-07-08 19:05:04 +0000505 StringPrefix);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000506
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000507 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000508 llvm::Constant *Fields[4] = {
509 llvm::ConstantExpr::getBitCast(GV, SBP),
510 llvm::ConstantExpr::getBitCast(annoGV, SBP),
511 llvm::ConstantExpr::getBitCast(unitGV, SBP),
512 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
513 };
514 return llvm::ConstantStruct::get(Fields, 4, false);
515}
516
Daniel Dunbar73241df2009-02-13 21:18:01 +0000517bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000518 // Never defer when EmitAllDecls is specified or the decl has
519 // attribute used.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000520 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000521 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000522
523 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000524 // Constructors and destructors should never be deferred.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000525 if (FD->hasAttr<ConstructorAttr>() ||
526 FD->hasAttr<DestructorAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000527 return false;
528
Douglas Gregor68584ed2009-06-18 16:11:24 +0000529 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000530
531 // static, static inline, always_inline, and extern inline functions can
Chris Lattner86daeee2009-04-14 16:44:36 +0000532 // always be deferred. Normal inline functions can be deferred in C99/C++.
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000533 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
534 Linkage == GVA_CXXInline)
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000535 return true;
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000536 return false;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000537 }
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000538
539 const VarDecl *VD = cast<VarDecl>(Global);
540 assert(VD->isFileVarDecl() && "Invalid decl");
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000541
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000542 return VD->getStorageClass() == VarDecl::Static;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000543}
544
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000545void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000546 const ValueDecl *Global = GD.getDecl();
547
Chris Lattnerbd532712009-03-22 21:47:11 +0000548 // If this is an alias definition (which otherwise looks like a declaration)
549 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000550 if (Global->hasAttr<AliasAttr>())
Chris Lattnerbd532712009-03-22 21:47:11 +0000551 return EmitAliasDefinition(Global);
Daniel Dunbar219df662008-09-08 23:44:31 +0000552
Chris Lattner67b00522009-03-21 09:44:56 +0000553 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000554 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000555 // Forward declarations are emitted lazily on first use.
556 if (!FD->isThisDeclarationADefinition())
557 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000558 } else {
559 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000560 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
561
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000562 // In C++, if this is marked "extern", defer code generation.
Anders Carlsson2928c212009-05-16 21:02:39 +0000563 if (getLangOptions().CPlusPlus && !VD->getInit() &&
564 (VD->getStorageClass() == VarDecl::Extern ||
565 VD->isExternC(getContext())))
Daniel Dunbar73241df2009-02-13 21:18:01 +0000566 return;
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000567
568 // In C, if this isn't a definition, defer code generation.
569 if (!getLangOptions().CPlusPlus && !VD->getInit())
570 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000571 }
572
Chris Lattner67b00522009-03-21 09:44:56 +0000573 // Defer code generation when possible if this is a static definition, inline
574 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000575 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000576 // If the value has already been used, add it directly to the
577 // DeferredDeclsToEmit list.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000578 const char *MangledName = getMangledName(GD);
Chris Lattner67b00522009-03-21 09:44:56 +0000579 if (GlobalDeclMap.count(MangledName))
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000580 DeferredDeclsToEmit.push_back(GD);
Chris Lattner67b00522009-03-21 09:44:56 +0000581 else {
582 // Otherwise, remember that we saw a deferred decl with this name. The
583 // first use of the mangled name will cause it to move into
584 // DeferredDeclsToEmit.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000585 DeferredDecls[MangledName] = GD;
Chris Lattner67b00522009-03-21 09:44:56 +0000586 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000587 return;
588 }
589
590 // Otherwise emit the definition.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000591 EmitGlobalDefinition(GD);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000592}
593
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000594void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000595 const ValueDecl *D = GD.getDecl();
596
597 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
598 EmitCXXConstructor(CD, GD.getCtorType());
Anders Carlsson7267c162009-05-29 21:03:38 +0000599 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
600 EmitCXXDestructor(DD, GD.getDtorType());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000601 else if (isa<FunctionDecl>(D))
602 EmitGlobalFunctionDefinition(GD);
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000603 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000604 EmitGlobalVarDefinition(VD);
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000605 else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000606 assert(0 && "Invalid argument to EmitGlobalDefinition()");
607 }
608}
609
Chris Lattner74391b42009-03-22 21:03:39 +0000610/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
611/// module, create and return an llvm Function with the specified type. If there
612/// is something in the module with the specified name, return it potentially
613/// bitcasted to the right type.
614///
615/// If D is non-null, it specifies a decl that correspond to this. This is used
616/// to set the attributes on the function when it is first created.
617llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
618 const llvm::Type *Ty,
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000619 GlobalDecl D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000620 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0558e792009-03-21 09:25:43 +0000621 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
622 if (Entry) {
623 if (Entry->getType()->getElementType() == Ty)
624 return Entry;
625
626 // Make sure the result is of the correct type.
627 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
628 return llvm::ConstantExpr::getBitCast(Entry, PTy);
629 }
630
Chris Lattner67b00522009-03-21 09:44:56 +0000631 // This is the first use or definition of a mangled name. If there is a
632 // deferred decl with this name, remember that we need to emit it at the end
633 // of the file.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000634 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
Chris Lattner9fa959d2009-05-12 20:58:15 +0000635 DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000636 if (DDI != DeferredDecls.end()) {
637 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
638 // list, and remove it from DeferredDecls (since we don't need it anymore).
639 DeferredDeclsToEmit.push_back(DDI->second);
640 DeferredDecls.erase(DDI);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000641 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
Chris Lattner0c337ed2009-05-12 21:02:27 +0000642 // If this the first reference to a C++ inline function in a class, queue up
643 // the deferred function body for emission. These are not seen as
644 // top-level declarations.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000645 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
646 DeferredDeclsToEmit.push_back(D);
Chris Lattner67b00522009-03-21 09:44:56 +0000647 }
648
Chris Lattner0558e792009-03-21 09:25:43 +0000649 // This function doesn't have a complete type (for example, the return
650 // type is an incomplete struct). Use a fake type instead, and make
651 // sure not to try to set attributes.
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000652 bool IsIncompleteFunction = false;
Chris Lattner0558e792009-03-21 09:25:43 +0000653 if (!isa<llvm::FunctionType>(Ty)) {
654 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
655 std::vector<const llvm::Type*>(), false);
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000656 IsIncompleteFunction = true;
Chris Lattner0558e792009-03-21 09:25:43 +0000657 }
658 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
659 llvm::Function::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000660 "", &getModule());
661 F->setName(MangledName);
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000662 if (D.getDecl())
663 SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F,
664 IsIncompleteFunction);
Chris Lattner0558e792009-03-21 09:25:43 +0000665 Entry = F;
666 return F;
667}
668
Chris Lattner74391b42009-03-22 21:03:39 +0000669/// GetAddrOfFunction - Return the address of the given function. If Ty is
670/// non-null, then this function will use the specified type if it has to
671/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000672llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner74391b42009-03-22 21:03:39 +0000673 const llvm::Type *Ty) {
674 // If there was no specific requested type, just convert it now.
675 if (!Ty)
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000676 Ty = getTypes().ConvertType(GD.getDecl()->getType());
677 return GetOrCreateLLVMFunction(getMangledName(GD.getDecl()), Ty, GD);
Chris Lattner74391b42009-03-22 21:03:39 +0000678}
Eli Friedman77ba7082008-05-30 19:50:47 +0000679
Chris Lattner74391b42009-03-22 21:03:39 +0000680/// CreateRuntimeFunction - Create a new runtime function with the specified
681/// type and name.
682llvm::Constant *
683CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
684 const char *Name) {
685 // Convert Name to be a uniqued string from the IdentifierInfo table.
686 Name = getContext().Idents.get(Name).getName();
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000687 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattner74391b42009-03-22 21:03:39 +0000688}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000689
Chris Lattner74391b42009-03-22 21:03:39 +0000690/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
691/// create and return an llvm GlobalVariable with the specified type. If there
692/// is something in the module with the specified name, return it potentially
693/// bitcasted to the right type.
694///
695/// If D is non-null, it specifies a decl that correspond to this. This is used
696/// to set the attributes on the global when it is first created.
697llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
698 const llvm::PointerType*Ty,
699 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000700 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000701 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000702 if (Entry) {
Chris Lattner74391b42009-03-22 21:03:39 +0000703 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000704 return Entry;
705
Chris Lattner99b53612009-03-21 08:03:33 +0000706 // Make sure the result is of the correct type.
Chris Lattner74391b42009-03-22 21:03:39 +0000707 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000708 }
Chris Lattner67b00522009-03-21 09:44:56 +0000709
710 // This is the first use or definition of a mangled name. If there is a
711 // deferred decl with this name, remember that we need to emit it at the end
712 // of the file.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000713 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
Chris Lattner67b00522009-03-21 09:44:56 +0000714 DeferredDecls.find(MangledName);
715 if (DDI != DeferredDecls.end()) {
716 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
717 // list, and remove it from DeferredDecls (since we don't need it anymore).
718 DeferredDeclsToEmit.push_back(DDI->second);
719 DeferredDecls.erase(DDI);
720 }
721
Chris Lattner99b53612009-03-21 08:03:33 +0000722 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +0000723 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000724 llvm::GlobalValue::ExternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000725 0, "", 0,
Eli Friedman56ebe502009-04-19 21:05:03 +0000726 false, Ty->getAddressSpace());
Chris Lattnerd9726782009-03-22 00:12:30 +0000727 GV->setName(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000728
729 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000730 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000731 // FIXME: This code is overly simple and should be merged with other global
732 // handling.
Chris Lattner74391b42009-03-22 21:03:39 +0000733 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner99b53612009-03-21 08:03:33 +0000734
Chris Lattner74391b42009-03-22 21:03:39 +0000735 // FIXME: Merge with other attribute handling code.
736 if (D->getStorageClass() == VarDecl::PrivateExtern)
Daniel Dunbar04d40782009-04-14 06:00:08 +0000737 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +0000738
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000739 if (D->hasAttr<WeakAttr>() ||
740 D->hasAttr<WeakImportAttr>())
Chris Lattner74391b42009-03-22 21:03:39 +0000741 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Eli Friedman56ebe502009-04-19 21:05:03 +0000742
743 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +0000744 }
745
Chris Lattner99b53612009-03-21 08:03:33 +0000746 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000747}
748
Chris Lattner74391b42009-03-22 21:03:39 +0000749
750/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
751/// given global variable. If Ty is non-null and if the global doesn't exist,
752/// then it will be greated with the specified type instead of whatever the
753/// normal requested type would be.
754llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
755 const llvm::Type *Ty) {
756 assert(D->hasGlobalStorage() && "Not a global variable");
757 QualType ASTTy = D->getType();
758 if (Ty == 0)
759 Ty = getTypes().ConvertTypeForMem(ASTTy);
760
761 const llvm::PointerType *PTy =
762 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
763 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
764}
765
766/// CreateRuntimeVariable - Create a new runtime global variable with the
767/// specified type and name.
768llvm::Constant *
769CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
770 const char *Name) {
771 // Convert Name to be a uniqued string from the IdentifierInfo table.
772 Name = getContext().Idents.get(Name).getName();
773 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
774}
775
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000776void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
777 assert(!D->getInit() && "Cannot emit definite definitions here!");
778
Douglas Gregor7520bd12009-04-21 19:28:58 +0000779 if (MayDeferGeneration(D)) {
780 // If we have not seen a reference to this variable yet, place it
781 // into the deferred declarations table to be emitted if needed
782 // later.
783 const char *MangledName = getMangledName(D);
784 if (GlobalDeclMap.count(MangledName) == 0) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000785 DeferredDecls[MangledName] = GlobalDecl(D);
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000786 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +0000787 }
788 }
789
790 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000791 EmitGlobalVarDefinition(D);
792}
793
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000794void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000795 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000796 QualType ASTTy = D->getType();
Chris Lattnerb75863d2009-04-10 00:35:59 +0000797
Chris Lattner8f32f712007-07-14 00:23:28 +0000798 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000799 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000800 // implicitly initialized with { 0 }.
801 //
802 // Note that tentative definitions are only emitted at the end of
803 // a translation unit, so they should never have incomplete
804 // type. In addition, EmitTentativeDefinition makes sure that we
805 // never attempt to emit a tentative definition if a real one
806 // exists. A use may still exists, however, so we still may need
807 // to do a RAUW.
808 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Owen Anderson69243822009-07-13 04:10:07 +0000809 Init = getLLVMContext().getNullValue(getTypes().ConvertTypeForMem(ASTTy));
Eli Friedman77ba7082008-05-30 19:50:47 +0000810 } else {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000811 Init = EmitConstantExpr(D->getInit(), D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +0000812 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000813 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000814 QualType T = D->getInit()->getType();
815 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
816 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000817 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000818
Chris Lattner2d584062009-03-21 08:13:05 +0000819 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000820 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000821
Chris Lattner570585c2009-03-21 09:16:30 +0000822 // Strip off a bitcast if we got one back.
823 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
824 assert(CE->getOpcode() == llvm::Instruction::BitCast);
825 Entry = CE->getOperand(0);
826 }
827
828 // Entry is now either a Function or GlobalVariable.
829 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
830
Chris Lattner570585c2009-03-21 09:16:30 +0000831 // We have a definition after a declaration with the wrong type.
832 // We must make a new GlobalVariable* and update everything that used OldGV
833 // (a declaration or tentative definition) with the new GlobalVariable*
834 // (which will be a definition).
835 //
836 // This happens if there is a prototype for a global (e.g.
837 // "extern int x[];") and then a definition of a different type (e.g.
838 // "int x[10];"). This also happens when an initializer has a different type
839 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +0000840 if (GV == 0 ||
841 GV->getType()->getElementType() != InitType ||
842 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
843
844 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
845 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000846
Chris Lattner570585c2009-03-21 09:16:30 +0000847 // Make a new global with the correct type, this is now guaranteed to work.
848 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000849 GV->takeName(cast<llvm::GlobalValue>(Entry));
850
Eli Friedman77ba7082008-05-30 19:50:47 +0000851 // Replace all uses of the old global with the new global
852 llvm::Constant *NewPtrForOldDecl =
Chris Lattner570585c2009-03-21 09:16:30 +0000853 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
854 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000855
856 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +0000857 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000858 }
Devang Patel8e53e722007-10-26 16:31:40 +0000859
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000860 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000861 SourceManager &SM = Context.getSourceManager();
862 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000863 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000864 }
865
Chris Lattner88a69ad2007-07-13 05:13:43 +0000866 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000867 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000868 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000869
Chris Lattner88a69ad2007-07-13 05:13:43 +0000870 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000871 if (D->getStorageClass() == VarDecl::Static)
872 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000873 else if (D->hasAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000874 GV->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000875 else if (D->hasAttr<DLLExportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000876 GV->setLinkage(llvm::Function::DLLExportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000877 else if (D->hasAttr<WeakAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000878 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Daniel Dunbar04d40782009-04-14 06:00:08 +0000879 else if (!CompileOpts.NoCommon &&
880 (!D->hasExternalStorage() && !D->getInit()))
881 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000882 else
Daniel Dunbar04d40782009-04-14 06:00:08 +0000883 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000884
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000885 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +0000886
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000887 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000888 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000889 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000890 DI->EmitGlobalVariable(GV, D);
891 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000892}
Reid Spencer5f016e22007-07-11 17:01:13 +0000893
Chris Lattnerbdb01322009-05-05 06:16:31 +0000894/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
895/// implement a function with no prototype, e.g. "int foo() {}". If there are
896/// existing call uses of the old function in the module, this adjusts them to
897/// call the new function directly.
898///
899/// This is not just a cleanup: the always_inline pass requires direct calls to
900/// functions to be able to inline them. If there is a bitcast in the way, it
901/// won't inline them. Instcombine normally deletes these calls, but it isn't
902/// run at -O0.
903static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
904 llvm::Function *NewFn) {
905 // If we're redefining a global as a function, don't transform it.
906 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
907 if (OldFn == 0) return;
908
909 const llvm::Type *NewRetTy = NewFn->getReturnType();
910 llvm::SmallVector<llvm::Value*, 4> ArgList;
911
912 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
913 UI != E; ) {
914 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Chris Lattner08c93a72009-06-04 16:47:43 +0000915 unsigned OpNo = UI.getOperandNo();
Chris Lattnerbdb01322009-05-05 06:16:31 +0000916 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
Chris Lattner08c93a72009-06-04 16:47:43 +0000917 if (!CI || OpNo != 0) continue;
Chris Lattnerbdb01322009-05-05 06:16:31 +0000918
919 // If the return types don't match exactly, and if the call isn't dead, then
920 // we can't transform this call.
921 if (CI->getType() != NewRetTy && !CI->use_empty())
922 continue;
923
924 // If the function was passed too few arguments, don't transform. If extra
925 // arguments were passed, we silently drop them. If any of the types
926 // mismatch, we don't transform.
927 unsigned ArgNo = 0;
928 bool DontTransform = false;
929 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
930 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
931 if (CI->getNumOperands()-1 == ArgNo ||
932 CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
933 DontTransform = true;
934 break;
935 }
936 }
937 if (DontTransform)
938 continue;
939
940 // Okay, we can transform this. Create the new call instruction and copy
941 // over the required information.
942 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
943 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
944 ArgList.end(), "", CI);
945 ArgList.clear();
946 if (NewCall->getType() != llvm::Type::VoidTy)
947 NewCall->takeName(CI);
948 NewCall->setCallingConv(CI->getCallingConv());
949 NewCall->setAttributes(CI->getAttributes());
950
951 // Finally, remove the old call, replacing any uses with the new one.
952 if (!CI->use_empty())
953 CI->replaceAllUsesWith(NewCall);
954 CI->eraseFromParent();
955 }
956}
957
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000958
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000959void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000960 const llvm::FunctionType *Ty;
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000961 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
962
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000963 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
964 bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
965
966 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
967 } else {
968 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
969
970 // As a special case, make sure that definitions of K&R function
971 // "type foo()" aren't declared as varargs (which forces the backend
972 // to do unnecessary work).
973 if (D->getType()->isFunctionNoProtoType()) {
974 assert(Ty->isVarArg() && "Didn't lower type as expected");
975 // Due to stret, the lowered function could have arguments.
976 // Just create the same type as was lowered by ConvertType
977 // but strip off the varargs bit.
978 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
979 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
980 }
Chris Lattnerff75e1d2009-03-22 19:35:37 +0000981 }
Daniel Dunbard5d31802009-02-19 07:15:39 +0000982
Chris Lattner9fa959d2009-05-12 20:58:15 +0000983 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000984 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000985
Chris Lattner0558e792009-03-21 09:25:43 +0000986 // Strip off a bitcast if we got one back.
987 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
988 assert(CE->getOpcode() == llvm::Instruction::BitCast);
989 Entry = CE->getOperand(0);
990 }
991
992
993 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +0000994 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
995
Daniel Dunbar42745812009-03-09 23:53:08 +0000996 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +0000997 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +0000998 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +0000999
Chris Lattner62b33ea2009-03-21 08:38:50 +00001000 // F is the Function* for the one with the wrong type, we must make a new
1001 // Function* and update everything that used F (a declaration) with the new
1002 // Function* (which will be a definition).
1003 //
1004 // This happens if there is a prototype for a function
1005 // (e.g. "int f()") and then a definition of a different type
1006 // (e.g. "int f(int x)"). Start by making a new function of the
1007 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +00001008 GlobalDeclMap.erase(getMangledName(D));
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001009 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Chris Lattnerbdb01322009-05-05 06:16:31 +00001010 NewFn->takeName(OldFn);
1011
1012 // If this is an implementation of a function without a prototype, try to
1013 // replace any existing uses of the function (which may be calls) with uses
1014 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001015 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001016 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001017 OldFn->removeDeadConstantUsers();
1018 }
Chris Lattner62b33ea2009-03-21 08:38:50 +00001019
1020 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001021 if (!Entry->use_empty()) {
1022 llvm::Constant *NewPtrForOldDecl =
1023 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1024 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1025 }
Chris Lattner62b33ea2009-03-21 08:38:50 +00001026
1027 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001028 OldFn->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +00001029
Chris Lattner0558e792009-03-21 09:25:43 +00001030 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001031 }
Chris Lattner0558e792009-03-21 09:25:43 +00001032
1033 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001034
Daniel Dunbar219df662008-09-08 23:44:31 +00001035 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001036
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001037 SetFunctionDefinitionAttributes(D, Fn);
1038 SetLLVMFunctionAttributesForDefinition(D, Fn);
Daniel Dunbar219df662008-09-08 23:44:31 +00001039
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001040 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001041 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001042 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001043 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001044}
1045
Chris Lattnerbd532712009-03-22 21:47:11 +00001046void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001047 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001048 assert(AA && "Not an alias?");
1049
1050 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1051
1052 // Unique the name through the identifier table.
1053 const char *AliaseeName = AA->getAliasee().c_str();
1054 AliaseeName = getContext().Idents.get(AliaseeName).getName();
1055
1056 // Create a reference to the named value. This ensures that it is emitted
1057 // if a deferred decl.
1058 llvm::Constant *Aliasee;
1059 if (isa<llvm::FunctionType>(DeclTy))
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001060 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
Chris Lattnerbd532712009-03-22 21:47:11 +00001061 else
1062 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1063 llvm::PointerType::getUnqual(DeclTy), 0);
1064
1065 // Create the new alias itself, but don't set a name yet.
1066 llvm::GlobalValue *GA =
1067 new llvm::GlobalAlias(Aliasee->getType(),
1068 llvm::Function::ExternalLinkage,
1069 "", Aliasee, &getModule());
1070
1071 // See if there is already something with the alias' name in the module.
1072 const char *MangledName = getMangledName(D);
1073 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1074
1075 if (Entry && !Entry->isDeclaration()) {
1076 // If there is a definition in the module, then it wins over the alias.
1077 // This is dubious, but allow it to be safe. Just ignore the alias.
1078 GA->eraseFromParent();
1079 return;
1080 }
1081
1082 if (Entry) {
1083 // If there is a declaration in the module, then we had an extern followed
1084 // by the alias, as in:
1085 // extern int test6();
1086 // ...
1087 // int test6() __attribute__((alias("test7")));
1088 //
1089 // Remove it and replace uses of it with the alias.
1090
1091 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1092 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001093 Entry->eraseFromParent();
1094 }
1095
1096 // Now we know that there is no conflict, set the name.
1097 Entry = GA;
1098 GA->setName(MangledName);
1099
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001100 // Set attributes which are particular to an alias; this is a
1101 // specialization of the attributes which may be set on a global
1102 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001103 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001104 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1105 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001106 if (FD->getBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001107 GA->setLinkage(llvm::Function::DLLExportLinkage);
1108 } else {
1109 GA->setLinkage(llvm::Function::DLLExportLinkage);
1110 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001111 } else if (D->hasAttr<WeakAttr>() ||
1112 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001113 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1114 }
1115
1116 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001117}
1118
Chris Lattnerb808c952009-03-22 21:56:56 +00001119/// getBuiltinLibFunction - Given a builtin id for a function like
1120/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stumpc136e6c2009-02-27 22:42:30 +00001121llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001122 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1123 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1124 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001125
Douglas Gregor3e41d602009-02-13 23:20:09 +00001126 // Get the name, skip over the __builtin_ prefix (if necessary).
1127 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1128 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1129 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001130
1131 // Get the type for the builtin.
Chris Lattner86df27b2009-06-14 00:45:47 +00001132 ASTContext::GetBuiltinTypeError Error;
1133 QualType Type = Context.GetBuiltinType(BuiltinID, Error);
1134 assert(Error == ASTContext::GE_None && "Can't get builtin type");
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001135
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001136 const llvm::FunctionType *Ty =
1137 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1138
Chris Lattnerb808c952009-03-22 21:56:56 +00001139 // Unique the name through the identifier table.
1140 Name = getContext().Idents.get(Name).getName();
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001141 // FIXME: param attributes for sext/zext etc.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001142 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001143}
1144
Chris Lattner7acda7c2007-12-18 00:25:38 +00001145llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1146 unsigned NumTys) {
1147 return llvm::Intrinsic::getDeclaration(&getModule(),
1148 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1149}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001150
Reid Spencer5f016e22007-07-11 17:01:13 +00001151llvm::Function *CodeGenModule::getMemCpyFn() {
1152 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001153 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1154 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001155}
Anders Carlssonc9e20912007-08-21 00:21:21 +00001156
Eli Friedman0c995092008-05-26 12:59:39 +00001157llvm::Function *CodeGenModule::getMemMoveFn() {
1158 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001159 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1160 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +00001161}
1162
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001163llvm::Function *CodeGenModule::getMemSetFn() {
1164 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001165 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1166 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001167}
Chris Lattner7acda7c2007-12-18 00:25:38 +00001168
Anders Carlssone3daa762008-11-15 18:54:24 +00001169static void appendFieldAndPadding(CodeGenModule &CGM,
1170 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +00001171 FieldDecl *FieldD, FieldDecl *NextFieldD,
1172 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +00001173 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001174 // Append the field.
1175 Fields.push_back(Field);
1176
Douglas Gregor44b43212008-12-11 16:49:14 +00001177 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001178
1179 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +00001180 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001181 NextStructFieldNo = STy->getNumElements();
1182 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +00001183 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001184 }
1185
1186 // Append padding
1187 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1188 llvm::Constant *C =
Owen Anderson69243822009-07-13 04:10:07 +00001189 CGM.getLLVMContext().getNullValue(STy->getElementType(StructFieldNo + 1));
Anders Carlssone3daa762008-11-15 18:54:24 +00001190
1191 Fields.push_back(C);
1192 }
1193}
1194
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001195llvm::Constant *CodeGenModule::
Steve Naroff8d4141f2009-04-01 13:55:36 +00001196GetAddrOfConstantCFString(const StringLiteral *Literal) {
Steve Naroffb59212a2009-04-01 21:16:31 +00001197 std::string str;
Chris Lattner271474e2009-04-19 06:59:18 +00001198 unsigned StringLength = 0;
Steve Naroffb59212a2009-04-01 21:16:31 +00001199
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001200 bool isUTF16 = false;
1201 if (Literal->containsNonAsciiOrNull()) {
1202 // Convert from UTF-8 to UTF-16.
1203 llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1204 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1205 UTF16 *ToPtr = &ToBuf[0];
1206
1207 ConversionResult Result;
1208 Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1209 &ToPtr, ToPtr+Literal->getByteLength(),
1210 strictConversion);
Steve Naroffaa4a7562009-04-13 19:08:08 +00001211 if (Result == conversionOK) {
1212 // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1213 // without doing more surgery to this routine. Since we aren't explicitly
1214 // checking for endianness here, it's also a bug (when generating code for
1215 // a target that doesn't match the host endianness). Modeling this as an
1216 // i16 array is likely the cleanest solution.
1217 StringLength = ToPtr-&ToBuf[0];
1218 str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1219 isUTF16 = true;
1220 } else if (Result == sourceIllegal) {
Steve Narofffd942622009-04-13 20:26:29 +00001221 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
Steve Naroffaa4a7562009-04-13 19:08:08 +00001222 str.assign(Literal->getStrData(), Literal->getByteLength());
1223 StringLength = str.length();
1224 } else
1225 assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
Steve Naroffb59212a2009-04-01 21:16:31 +00001226
Steve Naroffb59212a2009-04-01 21:16:31 +00001227 } else {
1228 str.assign(Literal->getStrData(), Literal->getByteLength());
1229 StringLength = str.length();
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001230 }
Anders Carlssonc9e20912007-08-21 00:21:21 +00001231 llvm::StringMapEntry<llvm::Constant *> &Entry =
1232 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1233
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001234 if (llvm::Constant *C = Entry.getValue())
1235 return C;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001236
Owen Anderson69243822009-07-13 04:10:07 +00001237 llvm::Constant *Zero = getLLVMContext().getNullValue(llvm::Type::Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001238 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001239
1240 if (!CFConstantStringClassRef) {
1241 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1242 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001243
Mike Stumpf5408fe2009-05-16 07:57:57 +00001244 // FIXME: This is fairly broken if __CFConstantStringClassReference is
1245 // already defined, in that it will get renamed and the user will most
1246 // likely see an opaque error message. This is a general issue with relying
1247 // on particular names.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001248 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00001249 new llvm::GlobalVariable(getModule(), Ty, false,
Anders Carlssonc9e20912007-08-21 00:21:21 +00001250 llvm::GlobalVariable::ExternalLinkage, 0,
Owen Anderson1c431b32009-07-08 19:05:04 +00001251 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001252
1253 // Decay array -> ptr
1254 CFConstantStringClassRef =
1255 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001256 }
1257
Anders Carlssone3daa762008-11-15 18:54:24 +00001258 QualType CFTy = getContext().getCFConstantStringType();
1259 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001260
Anders Carlssone3daa762008-11-15 18:54:24 +00001261 const llvm::StructType *STy =
1262 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1263
1264 std::vector<llvm::Constant*> Fields;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001265 RecordDecl::field_iterator Field = CFRD->field_begin();
Douglas Gregor44b43212008-12-11 16:49:14 +00001266
Anders Carlssonc9e20912007-08-21 00:21:21 +00001267 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001268 FieldDecl *CurField = *Field++;
1269 FieldDecl *NextField = *Field++;
1270 appendFieldAndPadding(*this, Fields, CurField, NextField,
1271 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001272
1273 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001274 CurField = NextField;
1275 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001276 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001277 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001278 isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1279 : llvm::ConstantInt::get(Ty, 0x07C8),
1280 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001281
1282 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001283 CurField = NextField;
1284 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001285 llvm::Constant *C = llvm::ConstantArray::get(str);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001286
1287 const char *Sect, *Prefix;
1288 bool isConstant;
1289 if (isUTF16) {
1290 Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1291 Sect = getContext().Target.getUnicodeStringSection();
1292 // FIXME: Why does GCC not set constant here?
1293 isConstant = false;
1294 } else {
1295 Prefix = getContext().Target.getStringSymbolPrefix(true);
1296 Sect = getContext().Target.getCFStringDataSection();
1297 // FIXME: -fwritable-strings should probably affect this, but we
1298 // are following gcc here.
1299 isConstant = true;
1300 }
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001301 llvm::GlobalVariable *GV =
Owen Anderson1c431b32009-07-08 19:05:04 +00001302 new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001303 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00001304 C, Prefix);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001305 if (Sect)
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001306 GV->setSection(Sect);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001307 if (isUTF16) {
1308 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1309 GV->setAlignment(Align);
1310 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001311 appendFieldAndPadding(*this, Fields, CurField, NextField,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001312 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
Anders Carlssone3daa762008-11-15 18:54:24 +00001313 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001314
1315 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001316 CurField = NextField;
1317 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001318 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001319 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroffb59212a2009-04-01 21:16:31 +00001320 llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001321
1322 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001323 C = llvm::ConstantStruct::get(STy, Fields);
Owen Anderson1c431b32009-07-08 19:05:04 +00001324 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001325 llvm::GlobalVariable::InternalLinkage, C,
Owen Anderson1c431b32009-07-08 19:05:04 +00001326 getContext().Target.getCFStringSymbolPrefix());
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001327 if (const char *Sect = getContext().Target.getCFStringSection())
1328 GV->setSection(Sect);
Anders Carlsson0c678292007-11-01 00:41:52 +00001329 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001330
Anders Carlsson0c678292007-11-01 00:41:52 +00001331 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001332}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001333
Daniel Dunbar61432932008-08-13 23:20:05 +00001334/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001335/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001336std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001337 const char *StrData = E->getStrData();
1338 unsigned Len = E->getByteLength();
1339
1340 const ConstantArrayType *CAT =
1341 getContext().getAsConstantArrayType(E->getType());
1342 assert(CAT && "String isn't pointer or array!");
1343
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001344 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001345 std::string Str(StrData, StrData+Len);
1346 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001347
1348 if (E->isWide())
1349 RealLen *= getContext().Target.getWCharWidth()/8;
1350
Daniel Dunbar1e049762008-08-10 20:25:57 +00001351 Str.resize(RealLen, '\0');
1352
1353 return Str;
1354}
1355
Daniel Dunbar61432932008-08-13 23:20:05 +00001356/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1357/// constant array for the given string literal.
1358llvm::Constant *
1359CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1360 // FIXME: This can be more efficient.
1361 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1362}
1363
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001364/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1365/// array for the given ObjCEncodeExpr node.
1366llvm::Constant *
1367CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1368 std::string Str;
1369 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001370
1371 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001372}
1373
1374
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001375/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001376static llvm::Constant *GenerateStringLiteral(const std::string &str,
1377 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001378 CodeGenModule &CGM,
1379 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001380 // Create Constant for this string literal. Don't add a '\0'.
1381 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001382
1383 // Create a global variable for this string
Owen Anderson1c431b32009-07-08 19:05:04 +00001384 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001385 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +00001386 C, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001387}
1388
Daniel Dunbar61432932008-08-13 23:20:05 +00001389/// GetAddrOfConstantString - Returns a pointer to a character array
1390/// containing the literal. This contents are exactly that of the
1391/// given string, i.e. it will not be null terminated automatically;
1392/// see GetAddrOfConstantCString. Note that whether the result is
1393/// actually a pointer to an LLVM constant depends on
1394/// Feature.WriteableStrings.
1395///
1396/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001397llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1398 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001399 bool IsConstant = !Features.WritableStrings;
1400
1401 // Get the default prefix if a name wasn't specified.
1402 if (!GlobalName)
1403 GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1404
1405 // Don't share any string literals if strings aren't constant.
1406 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001407 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001408
1409 llvm::StringMapEntry<llvm::Constant *> &Entry =
1410 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1411
1412 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001413 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001414
1415 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001416 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001417 Entry.setValue(C);
1418 return C;
1419}
Daniel Dunbar61432932008-08-13 23:20:05 +00001420
1421/// GetAddrOfConstantCString - Returns a pointer to a character
1422/// array containing the literal and a terminating '\-'
1423/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001424llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1425 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001426 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001427}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001428
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001429/// EmitObjCPropertyImplementations - Emit information for synthesized
1430/// properties for an implementation.
1431void CodeGenModule::EmitObjCPropertyImplementations(const
1432 ObjCImplementationDecl *D) {
Douglas Gregor653f1b12009-04-23 01:02:12 +00001433 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001434 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001435 ObjCPropertyImplDecl *PID = *i;
1436
1437 // Dynamic is just for type-checking.
1438 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1439 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1440
1441 // Determine which methods need to be implemented, some may have
1442 // been overridden. Note that ::isSynthesized is not the method
1443 // we want, that just indicates if the decl came from a
1444 // property. What we want to know is if the method is defined in
1445 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001446 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001447 CodeGenFunction(*this).GenerateObjCGetter(
1448 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001449 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001450 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001451 CodeGenFunction(*this).GenerateObjCSetter(
1452 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001453 }
1454 }
1455}
1456
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001457/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001458void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001459 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00001460 I != E; ++I)
1461 EmitTopLevelDecl(*I);
1462}
1463
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001464// EmitLinkageSpec - Emit all declarations in a linkage spec.
1465void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1466 if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1467 ErrorUnsupported(LSD, "linkage spec");
1468 return;
1469 }
1470
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001471 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001472 I != E; ++I)
1473 EmitTopLevelDecl(*I);
1474}
1475
Daniel Dunbar41071de2008-08-15 23:26:23 +00001476/// EmitTopLevelDecl - Emit code for a single top level declaration.
1477void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1478 // If an error has occurred, stop code generation, but continue
1479 // parsing and semantic analysis (to ensure all warnings and errors
1480 // are emitted).
1481 if (Diags.hasErrorOccurred())
1482 return;
1483
Douglas Gregor16e8be22009-06-29 17:30:29 +00001484 // Ignore dependent declarations.
1485 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1486 return;
1487
Daniel Dunbar41071de2008-08-15 23:26:23 +00001488 switch (D->getKind()) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +00001489 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001490 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00001491 // Skip function templates
1492 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1493 return;
1494
1495 // Fall through
1496
Daniel Dunbar41071de2008-08-15 23:26:23 +00001497 case Decl::Var:
Anders Carlsson2a131fb2009-05-05 04:44:02 +00001498 EmitGlobal(GlobalDecl(cast<ValueDecl>(D)));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001499 break;
1500
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001501 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001502 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00001503 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001504 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001505 // No code generation needed.
1506 case Decl::Using:
Douglas Gregor127102b2009-06-29 20:59:39 +00001507 case Decl::ClassTemplate:
1508 case Decl::FunctionTemplate:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001509 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001510 case Decl::CXXConstructor:
1511 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1512 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00001513 case Decl::CXXDestructor:
1514 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1515 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00001516
1517 case Decl::StaticAssert:
1518 // Nothing to do.
1519 break;
1520
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001521 // Objective-C Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001522
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001523 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001524 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001525 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001526 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00001527 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00001528 break;
1529
Daniel Dunbar41071de2008-08-15 23:26:23 +00001530 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001531 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001532 break;
1533
1534 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001535 // Categories have properties but don't support synthesize so we
1536 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001537 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1538 break;
1539
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001540 case Decl::ObjCImplementation: {
1541 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1542 EmitObjCPropertyImplementations(OMD);
1543 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001544 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001545 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001546 case Decl::ObjCMethod: {
1547 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1548 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001549 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00001550 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1551 break;
1552 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001553 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001554 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001555 break;
1556
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001557 case Decl::LinkageSpec:
1558 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001559 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00001560
1561 case Decl::FileScopeAsm: {
1562 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1563 std::string AsmString(AD->getAsmString()->getStrData(),
1564 AD->getAsmString()->getByteLength());
1565
1566 const std::string &S = getModule().getModuleInlineAsm();
1567 if (S.empty())
1568 getModule().setModuleInlineAsm(AsmString);
1569 else
1570 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1571 break;
1572 }
1573
1574 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00001575 // Make sure we handled everything we should, every other kind is a
1576 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
1577 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001578 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1579 }
1580}