blob: efa50ba3387cde577e5050ba0ddefa0c3c677f7e [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.
Chris Lattnerbd360642009-03-26 05:00:52 +000055 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000056}
57
58CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000059 delete Runtime;
60 delete DebugInfo;
61}
62
63void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +000064 EmitDeferred();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000065 if (Runtime)
66 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
67 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000068 EmitCtorList(GlobalCtors, "llvm.global_ctors");
69 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000070 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000071 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000072}
73
Daniel Dunbar488e9932008-08-16 00:56:44 +000074/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000075/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000076void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
77 bool OmitOnError) {
78 if (OmitOnError && getDiags().hasErrorOccurred())
79 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000080 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000081 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +000082 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000083 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
84 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +000085}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000086
Daniel Dunbar488e9932008-08-16 00:56:44 +000087/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000088/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000089void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
90 bool OmitOnError) {
91 if (OmitOnError && getDiags().hasErrorOccurred())
92 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000093 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000094 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +000095 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000096 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +000097}
98
Daniel Dunbar04d40782009-04-14 06:00:08 +000099LangOptions::VisibilityMode
100CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
101 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
102 if (VD->getStorageClass() == VarDecl::PrivateExtern)
103 return LangOptions::Hidden;
104
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000105 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000106 switch (attr->getVisibility()) {
107 default: assert(0 && "Unknown visibility!");
108 case VisibilityAttr::DefaultVisibility:
109 return LangOptions::Default;
110 case VisibilityAttr::HiddenVisibility:
111 return LangOptions::Hidden;
112 case VisibilityAttr::ProtectedVisibility:
113 return LangOptions::Protected;
114 }
115 }
116
117 return getLangOptions().getVisibilityMode();
118}
119
120void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
121 const Decl *D) const {
122 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000123 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000124 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000125 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000126 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000127
Daniel Dunbar04d40782009-04-14 06:00:08 +0000128 switch (getDeclVisibilityMode(D)) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000129 default: assert(0 && "Unknown visibility!");
Daniel Dunbar04d40782009-04-14 06:00:08 +0000130 case LangOptions::Default:
131 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
132 case LangOptions::Hidden:
133 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
134 case LangOptions::Protected:
135 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
Dan Gohman4f8d1232008-05-22 00:50:06 +0000136 }
137}
138
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000139const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
140 const NamedDecl *ND = GD.getDecl();
141
142 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
143 return getMangledCXXCtorName(D, GD.getCtorType());
144 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
145 return getMangledCXXDtorName(D, GD.getDtorType());
146
147 return getMangledName(ND);
148}
149
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000150/// \brief Retrieves the mangled name for the given declaration.
151///
152/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000153/// const char* containing the mangled name. Otherwise, returns
154/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000155///
Douglas Gregor6ec36682009-02-18 23:53:56 +0000156const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000157 // In C, functions with no attributes never need to be mangled. Fastpath them.
158 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
159 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000160 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000161 }
162
Douglas Gregor6ec36682009-02-18 23:53:56 +0000163 llvm::SmallString<256> Name;
164 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000165 if (!mangleName(ND, Context, Out)) {
166 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000167 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000168 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000169
Douglas Gregor6ec36682009-02-18 23:53:56 +0000170 Name += '\0';
Anders Carlsson95d4e5d2009-04-15 15:55:24 +0000171 return UniqueMangledName(Name.begin(), Name.end());
172}
173
174const char *CodeGenModule::UniqueMangledName(const char *NameStart,
175 const char *NameEnd) {
176 assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
177
178 return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000179}
180
Chris Lattner6d397602008-03-14 17:18:18 +0000181/// AddGlobalCtor - Add a function to the list that will be called before
182/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000183void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000184 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000185 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000186}
187
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000188/// AddGlobalDtor - Add a function to the list that will be called
189/// when the module is unloaded.
190void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000191 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000192 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
193}
194
195void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
196 // Ctor function type is void()*.
197 llvm::FunctionType* CtorFTy =
198 llvm::FunctionType::get(llvm::Type::VoidTy,
199 std::vector<const llvm::Type*>(),
200 false);
201 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
202
203 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000204 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000205 llvm::StructType::get(llvm::Type::Int32Ty,
206 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000207
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000208 // Construct the constructor and destructor arrays.
209 std::vector<llvm::Constant*> Ctors;
210 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
211 std::vector<llvm::Constant*> S;
212 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
213 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
214 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000215 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000216
217 if (!Ctors.empty()) {
218 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
219 new llvm::GlobalVariable(AT, false,
220 llvm::GlobalValue::AppendingLinkage,
221 llvm::ConstantArray::get(AT, Ctors),
222 GlobalName,
223 &TheModule);
224 }
Chris Lattner6d397602008-03-14 17:18:18 +0000225}
226
Nate Begeman532485c2008-04-18 23:43:57 +0000227void CodeGenModule::EmitAnnotations() {
228 if (Annotations.empty())
229 return;
230
231 // Create a new global variable for the ConstantStruct in the Module.
232 llvm::Constant *Array =
233 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
234 Annotations.size()),
235 Annotations);
236 llvm::GlobalValue *gv =
237 new llvm::GlobalVariable(Array->getType(), false,
238 llvm::GlobalValue::AppendingLinkage, Array,
239 "llvm.global.annotations", &TheModule);
240 gv->setSection("llvm.metadata");
241}
242
Chris Lattner86daeee2009-04-14 16:44:36 +0000243static CodeGenModule::GVALinkage
Douglas Gregor68584ed2009-06-18 16:11:24 +0000244GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
245 const LangOptions &Features) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000246 // The kind of external linkage this function will have, if it is not
247 // inline or static.
248 CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
249 if (Context.getLangOptions().CPlusPlus &&
250 (FD->getPrimaryTemplate() || FD->getInstantiatedFromMemberFunction()) &&
251 !FD->isExplicitSpecialization())
252 External = CodeGenModule::GVA_TemplateInstantiation;
253
Anders Carlsson167b8242009-05-15 18:35:39 +0000254 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
255 // C++ member functions defined inside the class are always inline.
Argyrios Kyrtzidisf5cecfb2009-06-17 22:49:50 +0000256 if (MD->isInline() || !MD->isOutOfLine())
Anders Carlsson167b8242009-05-15 18:35:39 +0000257 return CodeGenModule::GVA_CXXInline;
258
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000259 return External;
Anders Carlsson167b8242009-05-15 18:35:39 +0000260 }
261
Eli Friedman43907e82009-05-03 19:01:39 +0000262 // "static" functions get internal linkage.
Eli Friedman5e222132009-05-03 18:13:43 +0000263 if (FD->getStorageClass() == FunctionDecl::Static)
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000264 return CodeGenModule::GVA_Internal;
265
Chris Lattner005eedc2009-05-12 20:26:52 +0000266 if (!FD->isInline())
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000267 return External;
Chris Lattner86daeee2009-04-14 16:44:36 +0000268
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000269 // If the inline function explicitly has the GNU inline attribute on it, or if
270 // this is C89 mode, we use to GNU semantics.
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000271 if (!Features.C99 && !Features.CPlusPlus) {
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000272 // extern inline in GNU mode is like C99 inline.
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000273 if (FD->getStorageClass() == FunctionDecl::Extern)
274 return CodeGenModule::GVA_C99Inline;
275 // Normal inline is a strong symbol.
276 return CodeGenModule::GVA_StrongExternal;
Douglas Gregor68584ed2009-06-18 16:11:24 +0000277 } else if (FD->hasActiveGNUInlineAttribute(Context)) {
Douglas Gregor9f9bf252009-04-28 06:37:30 +0000278 // GCC in C99 mode seems to use a different decision-making
279 // process for extern inline, which factors in previous
280 // declarations.
Douglas Gregor68584ed2009-06-18 16:11:24 +0000281 if (FD->isExternGNUInline(Context))
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000282 return CodeGenModule::GVA_C99Inline;
283 // Normal inline is a strong symbol.
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000284 return External;
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000285 }
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000286
Chris Lattner86daeee2009-04-14 16:44:36 +0000287 // The definition of inline changes based on the language. Note that we
288 // have already handled "static inline" above, with the GVA_Internal case.
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000289 if (Features.CPlusPlus) // inline and extern inline.
Chris Lattner86daeee2009-04-14 16:44:36 +0000290 return CodeGenModule::GVA_CXXInline;
291
Chris Lattnerd55a71d2009-04-22 00:03:30 +0000292 assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode");
Douglas Gregorb3efa982009-04-23 18:22:55 +0000293 if (FD->isC99InlineDefinition())
294 return CodeGenModule::GVA_C99Inline;
295
296 return CodeGenModule::GVA_StrongExternal;
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000297}
298
299/// SetFunctionDefinitionAttributes - Set attributes for a global.
Daniel Dunbarb97b6922009-04-14 06:19:49 +0000300///
Mike Stumpf5408fe2009-05-16 07:57:57 +0000301/// FIXME: This is currently only done for aliases and functions, but not for
302/// variables (these details are set in EmitGlobalVarDefinition for variables).
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000303void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
304 llvm::GlobalValue *GV) {
Douglas Gregor68584ed2009-06-18 16:11:24 +0000305 GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000306
Daniel Dunbar55d6f502009-04-14 07:19:20 +0000307 if (Linkage == GVA_Internal) {
Chris Lattner9f942792009-04-14 05:33:52 +0000308 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000309 } else if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000310 GV->setLinkage(llvm::Function::DLLExportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000311 } else if (D->hasAttr<WeakAttr>()) {
Chris Lattner44b0bc02009-04-14 06:04:17 +0000312 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000313 } else if (Linkage == GVA_C99Inline) {
314 // In C99 mode, 'inline' functions are guaranteed to have a strong
315 // definition somewhere else, so we can use available_externally linkage.
Chris Lattnerd9d049a2009-04-14 06:27:57 +0000316 GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
Douglas Gregor1fd2dd12009-06-29 22:39:32 +0000317 } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
Chris Lattner86daeee2009-04-14 16:44:36 +0000318 // In C++, the compiler has to emit a definition in every translation unit
319 // that references the function. We should use linkonce_odr because
320 // a) if all references in this translation unit are optimized away, we
321 // don't need to codegen it. b) if the function persists, it needs to be
322 // merged with other definitions. c) C++ has the ODR, so we know the
323 // definition is dependable.
324 GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000325 } else {
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000326 assert(Linkage == GVA_StrongExternal);
327 // Otherwise, we have strong external linkage.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000328 GV->setLinkage(llvm::Function::ExternalLinkage);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000329 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000330
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000331 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000332}
333
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000334void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
335 const CGFunctionInfo &Info,
336 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000337 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000338 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000339
Devang Patel761d7f72008-09-25 21:02:23 +0000340 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
341 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000342
343 // Set the appropriate calling convention for the Function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000344 if (D->hasAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000345 F->setCallingConv(llvm::CallingConv::X86_FastCall);
346
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000347 if (D->hasAttr<StdCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000348 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000349}
350
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000351void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
352 llvm::Function *F) {
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000353 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000354 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000355
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000356 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000357 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000358
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000359 if (D->hasAttr<NoinlineAttr>())
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000360 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000361}
362
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000363void CodeGenModule::SetCommonAttributes(const Decl *D,
364 llvm::GlobalValue *GV) {
365 setGlobalVisibility(GV, D);
366
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000367 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000368 AddUsedGlobal(GV);
369
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000370 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000371 GV->setSection(SA->getName());
372}
373
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000374void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
375 llvm::Function *F,
376 const CGFunctionInfo &FI) {
377 SetLLVMFunctionAttributes(D, FI, F);
378 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000379
380 F->setLinkage(llvm::Function::InternalLinkage);
381
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000382 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000383}
384
385void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000386 llvm::Function *F,
387 bool IsIncompleteFunction) {
388 if (!IsIncompleteFunction)
389 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000390
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000391 // Only a few attributes are set on declarations; these may later be
392 // overridden by a definition.
393
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000394 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000395 F->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000396 } else if (FD->hasAttr<WeakAttr>() ||
397 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000398 // "extern_weak" is overloaded in LLVM; we probably should have
399 // separate linkage types for this.
400 F->setLinkage(llvm::Function::ExternalWeakLinkage);
401 } else {
402 F->setLinkage(llvm::Function::ExternalLinkage);
403 }
404
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000405 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000406 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000407}
408
Daniel Dunbar02698712009-02-13 20:29:50 +0000409void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
410 assert(!GV->isDeclaration() &&
411 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000412 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000413}
414
415void CodeGenModule::EmitLLVMUsed() {
416 // Don't create llvm.used if there is no need.
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000417 // FIXME. Runtime indicates that there might be more 'used' symbols; but not
418 // necessariy. So, this test is not accurate for emptiness.
419 if (LLVMUsed.empty() && !Runtime)
Daniel Dunbar02698712009-02-13 20:29:50 +0000420 return;
421
Chris Lattner35f38a22009-03-31 22:37:52 +0000422 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Chris Lattner35f38a22009-03-31 22:37:52 +0000423
424 // Convert LLVMUsed to what ConstantArray needs.
425 std::vector<llvm::Constant*> UsedArray;
426 UsedArray.resize(LLVMUsed.size());
427 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
428 UsedArray[i] =
429 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
430 }
431
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000432 if (Runtime)
433 Runtime->MergeMetadataGlobals(UsedArray);
434 if (UsedArray.empty())
435 return;
436 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
437
Daniel Dunbar02698712009-02-13 20:29:50 +0000438 llvm::GlobalVariable *GV =
439 new llvm::GlobalVariable(ATy, false,
440 llvm::GlobalValue::AppendingLinkage,
Chris Lattner35f38a22009-03-31 22:37:52 +0000441 llvm::ConstantArray::get(ATy, UsedArray),
Daniel Dunbar02698712009-02-13 20:29:50 +0000442 "llvm.used", &getModule());
443
444 GV->setSection("llvm.metadata");
445}
446
447void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000448 // Emit code for any potentially referenced deferred decls. Since a
449 // previously unused static decl may become used during the generation of code
450 // for a static function, iterate until no changes are made.
451 while (!DeferredDeclsToEmit.empty()) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000452 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000453 DeferredDeclsToEmit.pop_back();
454
455 // The mangled name for the decl must have been emitted in GlobalDeclMap.
456 // Look it up to see if it was defined with a stronger definition (e.g. an
457 // extern inline function with a strong function redefinition). If so,
458 // just ignore the deferred decl.
459 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
460 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000461
Chris Lattner67b00522009-03-21 09:44:56 +0000462 if (!CGRef->isDeclaration())
463 continue;
464
465 // Otherwise, emit the definition and move on to the next one.
466 EmitGlobalDefinition(D);
467 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000468}
469
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000470/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
471/// annotation information for a given GlobalValue. The annotation struct is
472/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000473/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000474/// created from the AnnotateAttr's annotation. The third field is a constant
475/// string containing the name of the translation unit. The fourth field is
476/// the line number in the file of the annotated value declaration.
477///
478/// FIXME: this does not unique the annotation string constants, as llvm-gcc
479/// appears to.
480///
481llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
482 const AnnotateAttr *AA,
483 unsigned LineNo) {
484 llvm::Module *M = &getModule();
485
486 // get [N x i8] constants for the annotation string, and the filename string
487 // which are the 2nd and 3rd elements of the global annotation structure.
488 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
489 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
490 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
491 true);
492
493 // Get the two global values corresponding to the ConstantArrays we just
494 // created to hold the bytes of the strings.
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000495 const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000496 llvm::GlobalValue *annoGV =
497 new llvm::GlobalVariable(anno->getType(), false,
498 llvm::GlobalValue::InternalLinkage, anno,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000499 GV->getName() + StringPrefix, M);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000500 // translation unit name string, emitted into the llvm.metadata section.
501 llvm::GlobalValue *unitGV =
502 new llvm::GlobalVariable(unit->getType(), false,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000503 llvm::GlobalValue::InternalLinkage, unit,
504 StringPrefix, M);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000505
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000506 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000507 llvm::Constant *Fields[4] = {
508 llvm::ConstantExpr::getBitCast(GV, SBP),
509 llvm::ConstantExpr::getBitCast(annoGV, SBP),
510 llvm::ConstantExpr::getBitCast(unitGV, SBP),
511 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
512 };
513 return llvm::ConstantStruct::get(Fields, 4, false);
514}
515
Daniel Dunbar73241df2009-02-13 21:18:01 +0000516bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000517 // Never defer when EmitAllDecls is specified or the decl has
518 // attribute used.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000519 if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000520 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000521
522 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000523 // Constructors and destructors should never be deferred.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000524 if (FD->hasAttr<ConstructorAttr>() ||
525 FD->hasAttr<DestructorAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000526 return false;
527
Douglas Gregor68584ed2009-06-18 16:11:24 +0000528 GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000529
530 // static, static inline, always_inline, and extern inline functions can
Chris Lattner86daeee2009-04-14 16:44:36 +0000531 // always be deferred. Normal inline functions can be deferred in C99/C++.
Chris Lattnercbb8fc12009-04-14 20:25:53 +0000532 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
533 Linkage == GVA_CXXInline)
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000534 return true;
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000535 return false;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000536 }
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000537
538 const VarDecl *VD = cast<VarDecl>(Global);
539 assert(VD->isFileVarDecl() && "Invalid decl");
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000540
Chris Lattnerdbb5a372009-04-14 06:44:48 +0000541 return VD->getStorageClass() == VarDecl::Static;
Daniel Dunbar73241df2009-02-13 21:18:01 +0000542}
543
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000544void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000545 const ValueDecl *Global = GD.getDecl();
546
Chris Lattnerbd532712009-03-22 21:47:11 +0000547 // If this is an alias definition (which otherwise looks like a declaration)
548 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000549 if (Global->hasAttr<AliasAttr>())
Chris Lattnerbd532712009-03-22 21:47:11 +0000550 return EmitAliasDefinition(Global);
Daniel Dunbar219df662008-09-08 23:44:31 +0000551
Chris Lattner67b00522009-03-21 09:44:56 +0000552 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000553 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000554 // Forward declarations are emitted lazily on first use.
555 if (!FD->isThisDeclarationADefinition())
556 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000557 } else {
558 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000559 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
560
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000561 // In C++, if this is marked "extern", defer code generation.
Anders Carlsson2928c212009-05-16 21:02:39 +0000562 if (getLangOptions().CPlusPlus && !VD->getInit() &&
563 (VD->getStorageClass() == VarDecl::Extern ||
564 VD->isExternC(getContext())))
Daniel Dunbar73241df2009-02-13 21:18:01 +0000565 return;
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000566
567 // In C, if this isn't a definition, defer code generation.
568 if (!getLangOptions().CPlusPlus && !VD->getInit())
569 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000570 }
571
Chris Lattner67b00522009-03-21 09:44:56 +0000572 // Defer code generation when possible if this is a static definition, inline
573 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000574 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000575 // If the value has already been used, add it directly to the
576 // DeferredDeclsToEmit list.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000577 const char *MangledName = getMangledName(GD);
Chris Lattner67b00522009-03-21 09:44:56 +0000578 if (GlobalDeclMap.count(MangledName))
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000579 DeferredDeclsToEmit.push_back(GD);
Chris Lattner67b00522009-03-21 09:44:56 +0000580 else {
581 // Otherwise, remember that we saw a deferred decl with this name. The
582 // first use of the mangled name will cause it to move into
583 // DeferredDeclsToEmit.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000584 DeferredDecls[MangledName] = GD;
Chris Lattner67b00522009-03-21 09:44:56 +0000585 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000586 return;
587 }
588
589 // Otherwise emit the definition.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000590 EmitGlobalDefinition(GD);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000591}
592
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000593void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000594 const ValueDecl *D = GD.getDecl();
595
596 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
597 EmitCXXConstructor(CD, GD.getCtorType());
Anders Carlsson7267c162009-05-29 21:03:38 +0000598 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
599 EmitCXXDestructor(DD, GD.getDtorType());
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000600 else if (isa<FunctionDecl>(D))
601 EmitGlobalFunctionDefinition(GD);
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000602 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000603 EmitGlobalVarDefinition(VD);
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000604 else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000605 assert(0 && "Invalid argument to EmitGlobalDefinition()");
606 }
607}
608
Chris Lattner74391b42009-03-22 21:03:39 +0000609/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
610/// module, create and return an llvm Function with the specified type. If there
611/// is something in the module with the specified name, return it potentially
612/// bitcasted to the right type.
613///
614/// If D is non-null, it specifies a decl that correspond to this. This is used
615/// to set the attributes on the function when it is first created.
616llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
617 const llvm::Type *Ty,
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000618 GlobalDecl D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000619 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0558e792009-03-21 09:25:43 +0000620 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
621 if (Entry) {
622 if (Entry->getType()->getElementType() == Ty)
623 return Entry;
624
625 // Make sure the result is of the correct type.
626 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
627 return llvm::ConstantExpr::getBitCast(Entry, PTy);
628 }
629
Chris Lattner67b00522009-03-21 09:44:56 +0000630 // This is the first use or definition of a mangled name. If there is a
631 // deferred decl with this name, remember that we need to emit it at the end
632 // of the file.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000633 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
Chris Lattner9fa959d2009-05-12 20:58:15 +0000634 DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000635 if (DDI != DeferredDecls.end()) {
636 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
637 // list, and remove it from DeferredDecls (since we don't need it anymore).
638 DeferredDeclsToEmit.push_back(DDI->second);
639 DeferredDecls.erase(DDI);
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000640 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
Chris Lattner0c337ed2009-05-12 21:02:27 +0000641 // If this the first reference to a C++ inline function in a class, queue up
642 // the deferred function body for emission. These are not seen as
643 // top-level declarations.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000644 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
645 DeferredDeclsToEmit.push_back(D);
Chris Lattner67b00522009-03-21 09:44:56 +0000646 }
647
Chris Lattner0558e792009-03-21 09:25:43 +0000648 // This function doesn't have a complete type (for example, the return
649 // type is an incomplete struct). Use a fake type instead, and make
650 // sure not to try to set attributes.
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000651 bool IsIncompleteFunction = false;
Chris Lattner0558e792009-03-21 09:25:43 +0000652 if (!isa<llvm::FunctionType>(Ty)) {
653 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
654 std::vector<const llvm::Type*>(), false);
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000655 IsIncompleteFunction = true;
Chris Lattner0558e792009-03-21 09:25:43 +0000656 }
657 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
658 llvm::Function::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000659 "", &getModule());
660 F->setName(MangledName);
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000661 if (D.getDecl())
662 SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F,
663 IsIncompleteFunction);
Chris Lattner0558e792009-03-21 09:25:43 +0000664 Entry = F;
665 return F;
666}
667
Chris Lattner74391b42009-03-22 21:03:39 +0000668/// GetAddrOfFunction - Return the address of the given function. If Ty is
669/// non-null, then this function will use the specified type if it has to
670/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000671llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner74391b42009-03-22 21:03:39 +0000672 const llvm::Type *Ty) {
673 // If there was no specific requested type, just convert it now.
674 if (!Ty)
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000675 Ty = getTypes().ConvertType(GD.getDecl()->getType());
676 return GetOrCreateLLVMFunction(getMangledName(GD.getDecl()), Ty, GD);
Chris Lattner74391b42009-03-22 21:03:39 +0000677}
Eli Friedman77ba7082008-05-30 19:50:47 +0000678
Chris Lattner74391b42009-03-22 21:03:39 +0000679/// CreateRuntimeFunction - Create a new runtime function with the specified
680/// type and name.
681llvm::Constant *
682CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
683 const char *Name) {
684 // Convert Name to be a uniqued string from the IdentifierInfo table.
685 Name = getContext().Idents.get(Name).getName();
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000686 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattner74391b42009-03-22 21:03:39 +0000687}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000688
Chris Lattner74391b42009-03-22 21:03:39 +0000689/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
690/// create and return an llvm GlobalVariable with the specified type. If there
691/// is something in the module with the specified name, return it potentially
692/// bitcasted to the right type.
693///
694/// If D is non-null, it specifies a decl that correspond to this. This is used
695/// to set the attributes on the global when it is first created.
696llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
697 const llvm::PointerType*Ty,
698 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000699 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000700 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000701 if (Entry) {
Chris Lattner74391b42009-03-22 21:03:39 +0000702 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000703 return Entry;
704
Chris Lattner99b53612009-03-21 08:03:33 +0000705 // Make sure the result is of the correct type.
Chris Lattner74391b42009-03-22 21:03:39 +0000706 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000707 }
Chris Lattner67b00522009-03-21 09:44:56 +0000708
709 // This is the first use or definition of a mangled name. If there is a
710 // deferred decl with this name, remember that we need to emit it at the end
711 // of the file.
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000712 llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
Chris Lattner67b00522009-03-21 09:44:56 +0000713 DeferredDecls.find(MangledName);
714 if (DDI != DeferredDecls.end()) {
715 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
716 // list, and remove it from DeferredDecls (since we don't need it anymore).
717 DeferredDeclsToEmit.push_back(DDI->second);
718 DeferredDecls.erase(DDI);
719 }
720
Chris Lattner99b53612009-03-21 08:03:33 +0000721 llvm::GlobalVariable *GV =
Chris Lattner74391b42009-03-22 21:03:39 +0000722 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000723 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000724 0, "", &getModule(),
Eli Friedman56ebe502009-04-19 21:05:03 +0000725 false, Ty->getAddressSpace());
Chris Lattnerd9726782009-03-22 00:12:30 +0000726 GV->setName(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000727
728 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000729 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000730 // FIXME: This code is overly simple and should be merged with other global
731 // handling.
Chris Lattner74391b42009-03-22 21:03:39 +0000732 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner99b53612009-03-21 08:03:33 +0000733
Chris Lattner74391b42009-03-22 21:03:39 +0000734 // FIXME: Merge with other attribute handling code.
735 if (D->getStorageClass() == VarDecl::PrivateExtern)
Daniel Dunbar04d40782009-04-14 06:00:08 +0000736 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +0000737
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000738 if (D->hasAttr<WeakAttr>() ||
739 D->hasAttr<WeakImportAttr>())
Chris Lattner74391b42009-03-22 21:03:39 +0000740 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Eli Friedman56ebe502009-04-19 21:05:03 +0000741
742 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattner74391b42009-03-22 21:03:39 +0000743 }
744
Chris Lattner99b53612009-03-21 08:03:33 +0000745 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000746}
747
Chris Lattner74391b42009-03-22 21:03:39 +0000748
749/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
750/// given global variable. If Ty is non-null and if the global doesn't exist,
751/// then it will be greated with the specified type instead of whatever the
752/// normal requested type would be.
753llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
754 const llvm::Type *Ty) {
755 assert(D->hasGlobalStorage() && "Not a global variable");
756 QualType ASTTy = D->getType();
757 if (Ty == 0)
758 Ty = getTypes().ConvertTypeForMem(ASTTy);
759
760 const llvm::PointerType *PTy =
761 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
762 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
763}
764
765/// CreateRuntimeVariable - Create a new runtime global variable with the
766/// specified type and name.
767llvm::Constant *
768CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
769 const char *Name) {
770 // Convert Name to be a uniqued string from the IdentifierInfo table.
771 Name = getContext().Idents.get(Name).getName();
772 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
773}
774
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000775void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
776 assert(!D->getInit() && "Cannot emit definite definitions here!");
777
Douglas Gregor7520bd12009-04-21 19:28:58 +0000778 if (MayDeferGeneration(D)) {
779 // If we have not seen a reference to this variable yet, place it
780 // into the deferred declarations table to be emitted if needed
781 // later.
782 const char *MangledName = getMangledName(D);
783 if (GlobalDeclMap.count(MangledName) == 0) {
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000784 DeferredDecls[MangledName] = GlobalDecl(D);
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000785 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +0000786 }
787 }
788
789 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000790 EmitGlobalVarDefinition(D);
791}
792
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000793void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000794 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000795 QualType ASTTy = D->getType();
Chris Lattnerb75863d2009-04-10 00:35:59 +0000796
Chris Lattner8f32f712007-07-14 00:23:28 +0000797 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000798 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +0000799 // implicitly initialized with { 0 }.
800 //
801 // Note that tentative definitions are only emitted at the end of
802 // a translation unit, so they should never have incomplete
803 // type. In addition, EmitTentativeDefinition makes sure that we
804 // never attempt to emit a tentative definition if a real one
805 // exists. A use may still exists, however, so we still may need
806 // to do a RAUW.
807 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
808 Init = llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(ASTTy));
Eli Friedman77ba7082008-05-30 19:50:47 +0000809 } else {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000810 Init = EmitConstantExpr(D->getInit(), D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +0000811 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000812 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000813 QualType T = D->getInit()->getType();
814 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
815 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000816 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000817
Chris Lattner2d584062009-03-21 08:13:05 +0000818 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000819 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000820
Chris Lattner570585c2009-03-21 09:16:30 +0000821 // Strip off a bitcast if we got one back.
822 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
823 assert(CE->getOpcode() == llvm::Instruction::BitCast);
824 Entry = CE->getOperand(0);
825 }
826
827 // Entry is now either a Function or GlobalVariable.
828 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
829
Chris Lattner570585c2009-03-21 09:16:30 +0000830 // We have a definition after a declaration with the wrong type.
831 // We must make a new GlobalVariable* and update everything that used OldGV
832 // (a declaration or tentative definition) with the new GlobalVariable*
833 // (which will be a definition).
834 //
835 // This happens if there is a prototype for a global (e.g.
836 // "extern int x[];") and then a definition of a different type (e.g.
837 // "int x[10];"). This also happens when an initializer has a different type
838 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +0000839 if (GV == 0 ||
840 GV->getType()->getElementType() != InitType ||
841 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
842
843 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
844 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000845
Chris Lattner570585c2009-03-21 09:16:30 +0000846 // Make a new global with the correct type, this is now guaranteed to work.
847 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000848 GV->takeName(cast<llvm::GlobalValue>(Entry));
849
Eli Friedman77ba7082008-05-30 19:50:47 +0000850 // Replace all uses of the old global with the new global
851 llvm::Constant *NewPtrForOldDecl =
Chris Lattner570585c2009-03-21 09:16:30 +0000852 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
853 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000854
855 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +0000856 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000857 }
Devang Patel8e53e722007-10-26 16:31:40 +0000858
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000859 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000860 SourceManager &SM = Context.getSourceManager();
861 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000862 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000863 }
864
Chris Lattner88a69ad2007-07-13 05:13:43 +0000865 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000866 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000867 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000868
Chris Lattner88a69ad2007-07-13 05:13:43 +0000869 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000870 if (D->getStorageClass() == VarDecl::Static)
871 GV->setLinkage(llvm::Function::InternalLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000872 else if (D->hasAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000873 GV->setLinkage(llvm::Function::DLLImportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000874 else if (D->hasAttr<DLLExportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000875 GV->setLinkage(llvm::Function::DLLExportLinkage);
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000876 else if (D->hasAttr<WeakAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000877 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Daniel Dunbar04d40782009-04-14 06:00:08 +0000878 else if (!CompileOpts.NoCommon &&
879 (!D->hasExternalStorage() && !D->getInit()))
880 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000881 else
Daniel Dunbar04d40782009-04-14 06:00:08 +0000882 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000883
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000884 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +0000885
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000886 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000887 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000888 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000889 DI->EmitGlobalVariable(GV, D);
890 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000891}
Reid Spencer5f016e22007-07-11 17:01:13 +0000892
Chris Lattnerbdb01322009-05-05 06:16:31 +0000893/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
894/// implement a function with no prototype, e.g. "int foo() {}". If there are
895/// existing call uses of the old function in the module, this adjusts them to
896/// call the new function directly.
897///
898/// This is not just a cleanup: the always_inline pass requires direct calls to
899/// functions to be able to inline them. If there is a bitcast in the way, it
900/// won't inline them. Instcombine normally deletes these calls, but it isn't
901/// run at -O0.
902static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
903 llvm::Function *NewFn) {
904 // If we're redefining a global as a function, don't transform it.
905 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
906 if (OldFn == 0) return;
907
908 const llvm::Type *NewRetTy = NewFn->getReturnType();
909 llvm::SmallVector<llvm::Value*, 4> ArgList;
910
911 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
912 UI != E; ) {
913 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Chris Lattner08c93a72009-06-04 16:47:43 +0000914 unsigned OpNo = UI.getOperandNo();
Chris Lattnerbdb01322009-05-05 06:16:31 +0000915 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
Chris Lattner08c93a72009-06-04 16:47:43 +0000916 if (!CI || OpNo != 0) continue;
Chris Lattnerbdb01322009-05-05 06:16:31 +0000917
918 // If the return types don't match exactly, and if the call isn't dead, then
919 // we can't transform this call.
920 if (CI->getType() != NewRetTy && !CI->use_empty())
921 continue;
922
923 // If the function was passed too few arguments, don't transform. If extra
924 // arguments were passed, we silently drop them. If any of the types
925 // mismatch, we don't transform.
926 unsigned ArgNo = 0;
927 bool DontTransform = false;
928 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
929 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
930 if (CI->getNumOperands()-1 == ArgNo ||
931 CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
932 DontTransform = true;
933 break;
934 }
935 }
936 if (DontTransform)
937 continue;
938
939 // Okay, we can transform this. Create the new call instruction and copy
940 // over the required information.
941 ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
942 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
943 ArgList.end(), "", CI);
944 ArgList.clear();
945 if (NewCall->getType() != llvm::Type::VoidTy)
946 NewCall->takeName(CI);
947 NewCall->setCallingConv(CI->getCallingConv());
948 NewCall->setAttributes(CI->getAttributes());
949
950 // Finally, remove the old call, replacing any uses with the new one.
951 if (!CI->use_empty())
952 CI->replaceAllUsesWith(NewCall);
953 CI->eraseFromParent();
954 }
955}
956
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000957
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000958void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000959 const llvm::FunctionType *Ty;
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000960 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
961
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000962 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
963 bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
964
965 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
966 } else {
967 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
968
969 // As a special case, make sure that definitions of K&R function
970 // "type foo()" aren't declared as varargs (which forces the backend
971 // to do unnecessary work).
972 if (D->getType()->isFunctionNoProtoType()) {
973 assert(Ty->isVarArg() && "Didn't lower type as expected");
974 // Due to stret, the lowered function could have arguments.
975 // Just create the same type as was lowered by ConvertType
976 // but strip off the varargs bit.
977 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
978 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
979 }
Chris Lattnerff75e1d2009-03-22 19:35:37 +0000980 }
Daniel Dunbard5d31802009-02-19 07:15:39 +0000981
Chris Lattner9fa959d2009-05-12 20:58:15 +0000982 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000983 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000984
Chris Lattner0558e792009-03-21 09:25:43 +0000985 // Strip off a bitcast if we got one back.
986 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
987 assert(CE->getOpcode() == llvm::Instruction::BitCast);
988 Entry = CE->getOperand(0);
989 }
990
991
992 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +0000993 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
994
Daniel Dunbar42745812009-03-09 23:53:08 +0000995 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +0000996 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +0000997 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +0000998
Chris Lattner62b33ea2009-03-21 08:38:50 +0000999 // F is the Function* for the one with the wrong type, we must make a new
1000 // Function* and update everything that used F (a declaration) with the new
1001 // Function* (which will be a definition).
1002 //
1003 // This happens if there is a prototype for a function
1004 // (e.g. "int f()") and then a definition of a different type
1005 // (e.g. "int f(int x)"). Start by making a new function of the
1006 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +00001007 GlobalDeclMap.erase(getMangledName(D));
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001008 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Chris Lattnerbdb01322009-05-05 06:16:31 +00001009 NewFn->takeName(OldFn);
1010
1011 // If this is an implementation of a function without a prototype, try to
1012 // replace any existing uses of the function (which may be calls) with uses
1013 // of the new function
Chris Lattner9fa959d2009-05-12 20:58:15 +00001014 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001015 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001016 OldFn->removeDeadConstantUsers();
1017 }
Chris Lattner62b33ea2009-03-21 08:38:50 +00001018
1019 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001020 if (!Entry->use_empty()) {
1021 llvm::Constant *NewPtrForOldDecl =
1022 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1023 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1024 }
Chris Lattner62b33ea2009-03-21 08:38:50 +00001025
1026 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001027 OldFn->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +00001028
Chris Lattner0558e792009-03-21 09:25:43 +00001029 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001030 }
Chris Lattner0558e792009-03-21 09:25:43 +00001031
1032 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001033
Daniel Dunbar219df662008-09-08 23:44:31 +00001034 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001035
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001036 SetFunctionDefinitionAttributes(D, Fn);
1037 SetLLVMFunctionAttributesForDefinition(D, Fn);
Daniel Dunbar219df662008-09-08 23:44:31 +00001038
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001039 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001040 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001041 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001042 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001043}
1044
Chris Lattnerbd532712009-03-22 21:47:11 +00001045void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001046 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00001047 assert(AA && "Not an alias?");
1048
1049 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1050
1051 // Unique the name through the identifier table.
1052 const char *AliaseeName = AA->getAliasee().c_str();
1053 AliaseeName = getContext().Idents.get(AliaseeName).getName();
1054
1055 // Create a reference to the named value. This ensures that it is emitted
1056 // if a deferred decl.
1057 llvm::Constant *Aliasee;
1058 if (isa<llvm::FunctionType>(DeclTy))
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001059 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
Chris Lattnerbd532712009-03-22 21:47:11 +00001060 else
1061 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1062 llvm::PointerType::getUnqual(DeclTy), 0);
1063
1064 // Create the new alias itself, but don't set a name yet.
1065 llvm::GlobalValue *GA =
1066 new llvm::GlobalAlias(Aliasee->getType(),
1067 llvm::Function::ExternalLinkage,
1068 "", Aliasee, &getModule());
1069
1070 // See if there is already something with the alias' name in the module.
1071 const char *MangledName = getMangledName(D);
1072 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1073
1074 if (Entry && !Entry->isDeclaration()) {
1075 // If there is a definition in the module, then it wins over the alias.
1076 // This is dubious, but allow it to be safe. Just ignore the alias.
1077 GA->eraseFromParent();
1078 return;
1079 }
1080
1081 if (Entry) {
1082 // If there is a declaration in the module, then we had an extern followed
1083 // by the alias, as in:
1084 // extern int test6();
1085 // ...
1086 // int test6() __attribute__((alias("test7")));
1087 //
1088 // Remove it and replace uses of it with the alias.
1089
1090 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1091 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00001092 Entry->eraseFromParent();
1093 }
1094
1095 // Now we know that there is no conflict, set the name.
1096 Entry = GA;
1097 GA->setName(MangledName);
1098
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001099 // Set attributes which are particular to an alias; this is a
1100 // specialization of the attributes which may be set on a global
1101 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001102 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001103 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1104 // The dllexport attribute is ignored for undefined symbols.
Douglas Gregor72971342009-04-18 00:02:19 +00001105 if (FD->getBody(getContext()))
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001106 GA->setLinkage(llvm::Function::DLLExportLinkage);
1107 } else {
1108 GA->setLinkage(llvm::Function::DLLExportLinkage);
1109 }
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001110 } else if (D->hasAttr<WeakAttr>() ||
1111 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001112 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1113 }
1114
1115 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00001116}
1117
Chris Lattnerb808c952009-03-22 21:56:56 +00001118/// getBuiltinLibFunction - Given a builtin id for a function like
1119/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stumpc136e6c2009-02-27 22:42:30 +00001120llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00001121 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1122 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1123 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001124
Douglas Gregor3e41d602009-02-13 23:20:09 +00001125 // Get the name, skip over the __builtin_ prefix (if necessary).
1126 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1127 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1128 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001129
1130 // Get the type for the builtin.
Chris Lattner86df27b2009-06-14 00:45:47 +00001131 ASTContext::GetBuiltinTypeError Error;
1132 QualType Type = Context.GetBuiltinType(BuiltinID, Error);
1133 assert(Error == ASTContext::GE_None && "Can't get builtin type");
Douglas Gregor370ab3f2009-02-14 01:52:53 +00001134
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001135 const llvm::FunctionType *Ty =
1136 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1137
Chris Lattnerb808c952009-03-22 21:56:56 +00001138 // Unique the name through the identifier table.
1139 Name = getContext().Idents.get(Name).getName();
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001140 // FIXME: param attributes for sext/zext etc.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001141 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001142}
1143
Chris Lattner7acda7c2007-12-18 00:25:38 +00001144llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1145 unsigned NumTys) {
1146 return llvm::Intrinsic::getDeclaration(&getModule(),
1147 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1148}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001149
Reid Spencer5f016e22007-07-11 17:01:13 +00001150llvm::Function *CodeGenModule::getMemCpyFn() {
1151 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001152 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1153 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001154}
Anders Carlssonc9e20912007-08-21 00:21:21 +00001155
Eli Friedman0c995092008-05-26 12:59:39 +00001156llvm::Function *CodeGenModule::getMemMoveFn() {
1157 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001158 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1159 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +00001160}
1161
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001162llvm::Function *CodeGenModule::getMemSetFn() {
1163 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001164 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1165 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001166}
Chris Lattner7acda7c2007-12-18 00:25:38 +00001167
Anders Carlssone3daa762008-11-15 18:54:24 +00001168static void appendFieldAndPadding(CodeGenModule &CGM,
1169 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +00001170 FieldDecl *FieldD, FieldDecl *NextFieldD,
1171 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +00001172 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001173 // Append the field.
1174 Fields.push_back(Field);
1175
Douglas Gregor44b43212008-12-11 16:49:14 +00001176 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001177
1178 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +00001179 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001180 NextStructFieldNo = STy->getNumElements();
1181 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +00001182 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001183 }
1184
1185 // Append padding
1186 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1187 llvm::Constant *C =
1188 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1189
1190 Fields.push_back(C);
1191 }
1192}
1193
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001194llvm::Constant *CodeGenModule::
Steve Naroff8d4141f2009-04-01 13:55:36 +00001195GetAddrOfConstantCFString(const StringLiteral *Literal) {
Steve Naroffb59212a2009-04-01 21:16:31 +00001196 std::string str;
Chris Lattner271474e2009-04-19 06:59:18 +00001197 unsigned StringLength = 0;
Steve Naroffb59212a2009-04-01 21:16:31 +00001198
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001199 bool isUTF16 = false;
1200 if (Literal->containsNonAsciiOrNull()) {
1201 // Convert from UTF-8 to UTF-16.
1202 llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1203 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1204 UTF16 *ToPtr = &ToBuf[0];
1205
1206 ConversionResult Result;
1207 Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1208 &ToPtr, ToPtr+Literal->getByteLength(),
1209 strictConversion);
Steve Naroffaa4a7562009-04-13 19:08:08 +00001210 if (Result == conversionOK) {
1211 // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1212 // without doing more surgery to this routine. Since we aren't explicitly
1213 // checking for endianness here, it's also a bug (when generating code for
1214 // a target that doesn't match the host endianness). Modeling this as an
1215 // i16 array is likely the cleanest solution.
1216 StringLength = ToPtr-&ToBuf[0];
1217 str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1218 isUTF16 = true;
1219 } else if (Result == sourceIllegal) {
Steve Narofffd942622009-04-13 20:26:29 +00001220 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
Steve Naroffaa4a7562009-04-13 19:08:08 +00001221 str.assign(Literal->getStrData(), Literal->getByteLength());
1222 StringLength = str.length();
1223 } else
1224 assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
Steve Naroffb59212a2009-04-01 21:16:31 +00001225
Steve Naroffb59212a2009-04-01 21:16:31 +00001226 } else {
1227 str.assign(Literal->getStrData(), Literal->getByteLength());
1228 StringLength = str.length();
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001229 }
Anders Carlssonc9e20912007-08-21 00:21:21 +00001230 llvm::StringMapEntry<llvm::Constant *> &Entry =
1231 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1232
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001233 if (llvm::Constant *C = Entry.getValue())
1234 return C;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001235
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001236 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1237 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001238
1239 if (!CFConstantStringClassRef) {
1240 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1241 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001242
Mike Stumpf5408fe2009-05-16 07:57:57 +00001243 // FIXME: This is fairly broken if __CFConstantStringClassReference is
1244 // already defined, in that it will get renamed and the user will most
1245 // likely see an opaque error message. This is a general issue with relying
1246 // on particular names.
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001247 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001248 new llvm::GlobalVariable(Ty, false,
1249 llvm::GlobalVariable::ExternalLinkage, 0,
1250 "__CFConstantStringClassReference",
1251 &getModule());
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;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001265 RecordDecl::field_iterator Field = CFRD->field_begin(getContext());
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 =
Daniel Dunbara9668e02009-04-03 00:57:44 +00001302 new llvm::GlobalVariable(C->getType(), isConstant,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001303 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara9668e02009-04-03 00:57:44 +00001304 C, Prefix, &getModule());
1305 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);
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001324 GV = new llvm::GlobalVariable(C->getType(), true,
1325 llvm::GlobalVariable::InternalLinkage, C,
1326 getContext().Target.getCFStringSymbolPrefix(),
1327 &getModule());
1328 if (const char *Sect = getContext().Target.getCFStringSection())
1329 GV->setSection(Sect);
Anders Carlsson0c678292007-11-01 00:41:52 +00001330 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001331
Anders Carlsson0c678292007-11-01 00:41:52 +00001332 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001333}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001334
Daniel Dunbar61432932008-08-13 23:20:05 +00001335/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001336/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001337std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001338 const char *StrData = E->getStrData();
1339 unsigned Len = E->getByteLength();
1340
1341 const ConstantArrayType *CAT =
1342 getContext().getAsConstantArrayType(E->getType());
1343 assert(CAT && "String isn't pointer or array!");
1344
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001345 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001346 std::string Str(StrData, StrData+Len);
1347 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001348
1349 if (E->isWide())
1350 RealLen *= getContext().Target.getWCharWidth()/8;
1351
Daniel Dunbar1e049762008-08-10 20:25:57 +00001352 Str.resize(RealLen, '\0');
1353
1354 return Str;
1355}
1356
Daniel Dunbar61432932008-08-13 23:20:05 +00001357/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1358/// constant array for the given string literal.
1359llvm::Constant *
1360CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1361 // FIXME: This can be more efficient.
1362 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1363}
1364
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001365/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1366/// array for the given ObjCEncodeExpr node.
1367llvm::Constant *
1368CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1369 std::string Str;
1370 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001371
1372 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001373}
1374
1375
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001376/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001377static llvm::Constant *GenerateStringLiteral(const std::string &str,
1378 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001379 CodeGenModule &CGM,
1380 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001381 // Create Constant for this string literal. Don't add a '\0'.
1382 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001383
1384 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001385 return new llvm::GlobalVariable(C->getType(), constant,
1386 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001387 C, GlobalName, &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001388}
1389
Daniel Dunbar61432932008-08-13 23:20:05 +00001390/// GetAddrOfConstantString - Returns a pointer to a character array
1391/// containing the literal. This contents are exactly that of the
1392/// given string, i.e. it will not be null terminated automatically;
1393/// see GetAddrOfConstantCString. Note that whether the result is
1394/// actually a pointer to an LLVM constant depends on
1395/// Feature.WriteableStrings.
1396///
1397/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001398llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1399 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001400 bool IsConstant = !Features.WritableStrings;
1401
1402 // Get the default prefix if a name wasn't specified.
1403 if (!GlobalName)
1404 GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1405
1406 // Don't share any string literals if strings aren't constant.
1407 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001408 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001409
1410 llvm::StringMapEntry<llvm::Constant *> &Entry =
1411 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1412
1413 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001414 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001415
1416 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001417 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001418 Entry.setValue(C);
1419 return C;
1420}
Daniel Dunbar61432932008-08-13 23:20:05 +00001421
1422/// GetAddrOfConstantCString - Returns a pointer to a character
1423/// array containing the literal and a terminating '\-'
1424/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001425llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1426 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001427 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001428}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001429
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001430/// EmitObjCPropertyImplementations - Emit information for synthesized
1431/// properties for an implementation.
1432void CodeGenModule::EmitObjCPropertyImplementations(const
1433 ObjCImplementationDecl *D) {
Douglas Gregor653f1b12009-04-23 01:02:12 +00001434 for (ObjCImplementationDecl::propimpl_iterator
1435 i = D->propimpl_begin(getContext()),
1436 e = D->propimpl_end(getContext()); i != e; ++i) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001437 ObjCPropertyImplDecl *PID = *i;
1438
1439 // Dynamic is just for type-checking.
1440 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1441 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1442
1443 // Determine which methods need to be implemented, some may have
1444 // been overridden. Note that ::isSynthesized is not the method
1445 // we want, that just indicates if the decl came from a
1446 // property. What we want to know is if the method is defined in
1447 // this implementation.
Douglas Gregor653f1b12009-04-23 01:02:12 +00001448 if (!D->getInstanceMethod(getContext(), PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001449 CodeGenFunction(*this).GenerateObjCGetter(
1450 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001451 if (!PD->isReadOnly() &&
Douglas Gregor653f1b12009-04-23 01:02:12 +00001452 !D->getInstanceMethod(getContext(), PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001453 CodeGenFunction(*this).GenerateObjCSetter(
1454 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001455 }
1456 }
1457}
1458
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001459/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001460void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001461 for (RecordDecl::decl_iterator I = ND->decls_begin(getContext()),
1462 E = ND->decls_end(getContext());
Anders Carlsson984e0682009-04-01 00:58:25 +00001463 I != E; ++I)
1464 EmitTopLevelDecl(*I);
1465}
1466
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001467// EmitLinkageSpec - Emit all declarations in a linkage spec.
1468void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1469 if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1470 ErrorUnsupported(LSD, "linkage spec");
1471 return;
1472 }
1473
Douglas Gregor6ab35242009-04-09 21:40:53 +00001474 for (RecordDecl::decl_iterator I = LSD->decls_begin(getContext()),
1475 E = LSD->decls_end(getContext());
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001476 I != E; ++I)
1477 EmitTopLevelDecl(*I);
1478}
1479
Daniel Dunbar41071de2008-08-15 23:26:23 +00001480/// EmitTopLevelDecl - Emit code for a single top level declaration.
1481void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1482 // If an error has occurred, stop code generation, but continue
1483 // parsing and semantic analysis (to ensure all warnings and errors
1484 // are emitted).
1485 if (Diags.hasErrorOccurred())
1486 return;
1487
Douglas Gregor16e8be22009-06-29 17:30:29 +00001488 // Ignore dependent declarations.
1489 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1490 return;
1491
Daniel Dunbar41071de2008-08-15 23:26:23 +00001492 switch (D->getKind()) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +00001493 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001494 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00001495 // Skip function templates
1496 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1497 return;
1498
1499 // Fall through
1500
Daniel Dunbar41071de2008-08-15 23:26:23 +00001501 case Decl::Var:
Anders Carlsson2a131fb2009-05-05 04:44:02 +00001502 EmitGlobal(GlobalDecl(cast<ValueDecl>(D)));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001503 break;
1504
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001505 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001506 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00001507 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001508 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001509 // No code generation needed.
1510 case Decl::Using:
Douglas Gregor127102b2009-06-29 20:59:39 +00001511 case Decl::ClassTemplate:
1512 case Decl::FunctionTemplate:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001513 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001514 case Decl::CXXConstructor:
1515 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1516 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00001517 case Decl::CXXDestructor:
1518 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1519 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00001520
1521 case Decl::StaticAssert:
1522 // Nothing to do.
1523 break;
1524
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00001525 // Objective-C Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00001526
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001527 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001528 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001529 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001530 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00001531 case Decl::ObjCInterface:
Chris Lattner285d0db2009-04-01 02:36:43 +00001532 break;
1533
Daniel Dunbar41071de2008-08-15 23:26:23 +00001534 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001535 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001536 break;
1537
1538 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001539 // Categories have properties but don't support synthesize so we
1540 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001541 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1542 break;
1543
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001544 case Decl::ObjCImplementation: {
1545 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1546 EmitObjCPropertyImplementations(OMD);
1547 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001548 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001549 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001550 case Decl::ObjCMethod: {
1551 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1552 // If this is not a prototype, emit the body.
Douglas Gregor72971342009-04-18 00:02:19 +00001553 if (OMD->getBody(getContext()))
Daniel Dunbar41071de2008-08-15 23:26:23 +00001554 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1555 break;
1556 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001557 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001558 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001559 break;
1560
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001561 case Decl::LinkageSpec:
1562 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001563 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00001564
1565 case Decl::FileScopeAsm: {
1566 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1567 std::string AsmString(AD->getAsmString()->getStrData(),
1568 AD->getAsmString()->getByteLength());
1569
1570 const std::string &S = getModule().getModuleInlineAsm();
1571 if (S.empty())
1572 getModule().setModuleInlineAsm(AsmString);
1573 else
1574 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1575 break;
1576 }
1577
1578 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00001579 // Make sure we handled everything we should, every other kind is a
1580 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
1581 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001582 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1583 }
1584}