blob: 21f67901d12e1bd5e506f04b9469b314ed864969 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor3556bc72009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000022#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000023#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000026#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000027#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000029#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Mike Stumpd6d0ebe2009-03-04 18:47:42 +000037 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
Mike Stump1f010b52009-03-04 18:17:45 +000038 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
39 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000040
Chris Lattner08b05eb2009-03-21 07:12:05 +000041 if (!Features.ObjC1)
42 Runtime = 0;
43 else if (!Features.NeXTRuntime)
44 Runtime = CreateGNUObjCRuntime(*this);
45 else if (Features.ObjCNonFragileABI)
46 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
47 else
48 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000049
50 // If debug info generation is enabled, create the CGDebugInfo object.
Mike Stumpef2c82f2009-02-13 18:36:05 +000051 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000052}
53
54CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000055 delete Runtime;
56 delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
Daniel Dunbar566a6502008-09-08 23:44:31 +000060 EmitAliases();
Chris Lattner13137542009-03-22 21:21:57 +000061 EmitDeferred();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000062 if (Runtime)
63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000065 EmitCtorList(GlobalCtors, "llvm.global_ctors");
66 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000067 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000068 EmitLLVMUsed();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000069}
70
Daniel Dunbar9503b782008-08-16 00:56:44 +000071/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000072/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000073void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
74 bool OmitOnError) {
75 if (OmitOnError && getDiags().hasErrorOccurred())
76 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000077 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000078 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +000079 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000080 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
81 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +000082}
Chris Lattner0e4755d2007-12-02 06:27:33 +000083
Daniel Dunbar9503b782008-08-16 00:56:44 +000084/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000085/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000086void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
87 bool OmitOnError) {
88 if (OmitOnError && getDiags().hasErrorOccurred())
89 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000090 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000091 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +000092 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000093 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +000094}
95
Daniel Dunbar27250d32008-08-15 23:26:23 +000096/// setGlobalVisibility - Set the visibility for the given LLVM
97/// GlobalValue according to the given clang AST visibility value.
98static void setGlobalVisibility(llvm::GlobalValue *GV,
99 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000100 switch (Vis) {
101 default: assert(0 && "Unknown visibility!");
102 case VisibilityAttr::DefaultVisibility:
103 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
104 break;
105 case VisibilityAttr::HiddenVisibility:
106 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
107 break;
108 case VisibilityAttr::ProtectedVisibility:
109 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
110 break;
111 }
112}
113
Douglas Gregor3556bc72009-02-13 00:10:09 +0000114/// \brief Retrieves the mangled name for the given declaration.
115///
116/// If the given declaration requires a mangled name, returns an
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000117/// const char* containing the mangled name. Otherwise, returns
118/// the unmangled name.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000119///
120/// FIXME: Returning an IdentifierInfo* here is a total hack. We
121/// really need some kind of string abstraction that either stores a
122/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbar7b7f4f42009-02-18 22:52:09 +0000123/// changes to the GlobalDeclMap, too. (I disagree, I think what we
124/// actually need is for Sema to provide some notion of which Decls
125/// refer to the same semantic decl. We shouldn't need to mangle the
126/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor3556bc72009-02-13 00:10:09 +0000127///
128/// FIXME: Performance here is going to be terribly until we start
129/// caching mangled names. However, we should fix the problem above
130/// first.
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000131const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000132 // In C, functions with no attributes never need to be mangled. Fastpath them.
133 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
134 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000135 return ND->getNameAsCString();
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000136 }
137
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000138 llvm::SmallString<256> Name;
139 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000140 if (!mangleName(ND, Context, Out)) {
141 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000142 return ND->getNameAsCString();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000143 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000144
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000145 Name += '\0';
Chris Lattner08b05eb2009-03-21 07:12:05 +0000146 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000147}
148
Chris Lattner753d2592008-03-14 17:18:18 +0000149/// AddGlobalCtor - Add a function to the list that will be called before
150/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000151void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000152 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000153 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000154}
155
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000156/// AddGlobalDtor - Add a function to the list that will be called
157/// when the module is unloaded.
158void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000159 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000160 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
161}
162
163void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
164 // Ctor function type is void()*.
165 llvm::FunctionType* CtorFTy =
166 llvm::FunctionType::get(llvm::Type::VoidTy,
167 std::vector<const llvm::Type*>(),
168 false);
169 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
170
171 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000172 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000173 llvm::StructType::get(llvm::Type::Int32Ty,
174 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000175
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000176 // Construct the constructor and destructor arrays.
177 std::vector<llvm::Constant*> Ctors;
178 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
179 std::vector<llvm::Constant*> S;
180 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
181 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
182 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000183 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000184
185 if (!Ctors.empty()) {
186 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
187 new llvm::GlobalVariable(AT, false,
188 llvm::GlobalValue::AppendingLinkage,
189 llvm::ConstantArray::get(AT, Ctors),
190 GlobalName,
191 &TheModule);
192 }
Chris Lattner753d2592008-03-14 17:18:18 +0000193}
194
Nate Begeman52da5c72008-04-18 23:43:57 +0000195void CodeGenModule::EmitAnnotations() {
196 if (Annotations.empty())
197 return;
198
199 // Create a new global variable for the ConstantStruct in the Module.
200 llvm::Constant *Array =
201 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
202 Annotations.size()),
203 Annotations);
204 llvm::GlobalValue *gv =
205 new llvm::GlobalVariable(Array->getType(), false,
206 llvm::GlobalValue::AppendingLinkage, Array,
207 "llvm.global.annotations", &TheModule);
208 gv->setSection("llvm.metadata");
209}
210
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000211void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
212 bool IsInternal,
213 bool IsInline,
214 llvm::GlobalValue *GV,
215 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000216 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000217 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000218 if (!ForDefinition) {
219 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000220 if (D->getAttr<DLLImportAttr>()) {
221 // The dllimport attribute is overridden by a subsequent declaration as
222 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000223 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000224 // dllimport attribute can be applied only to function decls, not to
225 // definitions.
226 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
227 if (!FD->getBody())
228 GV->setLinkage(llvm::Function::DLLImportLinkage);
229 } else
230 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000231 }
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000232 } else if (D->getAttr<WeakAttr>() ||
233 D->getAttr<WeakImportAttr>()) {
234 // "extern_weak" is overloaded in LLVM; we probably should have
235 // separate linkage types for this.
Duncan Sands9aa5c262009-03-11 08:40:02 +0000236 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000237 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000238 } else {
239 if (IsInternal) {
240 GV->setLinkage(llvm::Function::InternalLinkage);
241 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000242 if (D->getAttr<DLLExportAttr>()) {
243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244 // The dllexport attribute is ignored for undefined symbols.
245 if (FD->getBody())
246 GV->setLinkage(llvm::Function::DLLExportLinkage);
247 } else
248 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000249 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
250 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000251 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000252 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000253 }
Nuno Lopes78534382008-06-08 15:45:52 +0000254
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000255 // FIXME: Figure out the relative priority of the attribute,
256 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000257 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000258 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000259 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000260
Daniel Dunbar97509722009-02-12 17:28:23 +0000261 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
262 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000263
264 // Only add to llvm.used when we see a definition, otherwise we
265 // might add multiple times or risk the value being replaced by a
266 // subsequent RAUW.
267 if (ForDefinition) {
268 if (D->getAttr<UsedAttr>())
269 AddUsedGlobal(GV);
270 }
Nuno Lopes78534382008-06-08 15:45:52 +0000271}
272
Devang Patela85a9ef2008-09-25 21:02:23 +0000273void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000274 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000275 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000276 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000277 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000278
Devang Patela85a9ef2008-09-25 21:02:23 +0000279 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
280 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000281
282 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000283 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000284 F->setCallingConv(llvm::CallingConv::X86_FastCall);
285
286 if (D->getAttr<StdCallAttr>())
287 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000288}
289
290/// SetFunctionAttributesForDefinition - Set function attributes
291/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000292void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
293 llvm::Function *F) {
294 if (isa<ObjCMethodDecl>(D)) {
295 SetGlobalValueAttributes(D, true, false, F, true);
296 } else {
297 const FunctionDecl *FD = cast<FunctionDecl>(D);
298 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
299 FD->isInline(), F, true);
300 }
301
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000302 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000303 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000304
305 if (D->getAttr<AlwaysInlineAttr>())
306 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000307
308 if (D->getAttr<NoinlineAttr>())
309 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000310}
311
312void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
313 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000314 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000315
Daniel Dunbar566a6502008-09-08 23:44:31 +0000316 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000317}
318
319void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
320 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000321 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000322
Daniel Dunbar566a6502008-09-08 23:44:31 +0000323 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
324 FD->isInline(), F, false);
325}
326
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000327
Daniel Dunbar566a6502008-09-08 23:44:31 +0000328void CodeGenModule::EmitAliases() {
329 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
Daniel Dunbar36acae42009-03-19 08:27:24 +0000330 const ValueDecl *D = Aliases[i];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000331 const AliasAttr *AA = D->getAttr<AliasAttr>();
332
333 // This is something of a hack, if the FunctionDecl got overridden
334 // then its attributes will be moved to the new declaration. In
335 // this case the current decl has no alias attribute, but we will
336 // eventually see it.
337 if (!AA)
338 continue;
339
Chris Lattner13137542009-03-22 21:21:57 +0000340 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
341
342 // Unique the name through the identifier table.
343 const char *AliaseeName = AA->getAliasee().c_str();
344 AliaseeName = getContext().Idents.get(AliaseeName).getName();
345
Chris Lattner9b011e62009-03-22 21:39:12 +0000346 // Create a reference to the named value. This ensures that it is emitted
347 // if a deferred decl.
Chris Lattner13137542009-03-22 21:21:57 +0000348 llvm::Constant *Aliasee;
349 if (isa<llvm::FunctionType>(DeclTy))
350 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
351 else
352 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
353 llvm::PointerType::getUnqual(DeclTy), 0);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000354
Chris Lattner9b011e62009-03-22 21:39:12 +0000355 // Create the new alias itself, but don't set a name yet.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000356 llvm::GlobalValue *GA =
Chris Lattner13137542009-03-22 21:21:57 +0000357 new llvm::GlobalAlias(Aliasee->getType(),
Daniel Dunbar566a6502008-09-08 23:44:31 +0000358 llvm::Function::ExternalLinkage,
Chris Lattner9b011e62009-03-22 21:39:12 +0000359 "", Aliasee, &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000360
Chris Lattner9b011e62009-03-22 21:39:12 +0000361 // See if there is already something with the alias' name in the module.
362 const char *MangledName = getMangledName(D);
Chris Lattner0b506252009-03-21 08:06:59 +0000363 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner9b011e62009-03-22 21:39:12 +0000364
365 if (Entry && !Entry->isDeclaration()) {
366 // If there is a definition in the module, then it wins over the alias.
367 // This is dubious, but allow it to be safe. Just ignore the alias.
368 delete GA;
369 continue;
Daniel Dunbar566a6502008-09-08 23:44:31 +0000370 }
Chris Lattner9b011e62009-03-22 21:39:12 +0000371
372 if (Entry) {
373 // If there is a declaration in the module, then we had an extern followed
374 // by the alias, as in:
375 // extern int test6();
376 // ...
377 // int test6() __attribute__((alias("test7")));
378 //
379 // Remove it and replace uses of it with the alias.
380
381 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
382 Entry->getType()));
383 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
384 Entry->eraseFromParent();
385 }
386
387 // Now we know that there is no conflict, set the name.
388 Entry = GA;
389 GA->setName(MangledName);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000390
391 // Alias should never be internal or inline.
392 SetGlobalValueAttributes(D, false, false, GA, true);
393 }
Eli Friedman9be42212008-06-01 15:54:49 +0000394}
395
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000396void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
397 assert(!GV->isDeclaration() &&
398 "Only globals with definition can force usage.");
399 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
400 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
401}
402
403void CodeGenModule::EmitLLVMUsed() {
404 // Don't create llvm.used if there is no need.
405 if (LLVMUsed.empty())
406 return;
407
408 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
409 LLVMUsed.size());
410 llvm::GlobalVariable *GV =
411 new llvm::GlobalVariable(ATy, false,
412 llvm::GlobalValue::AppendingLinkage,
413 llvm::ConstantArray::get(ATy, LLVMUsed),
414 "llvm.used", &getModule());
415
416 GV->setSection("llvm.metadata");
417}
418
419void CodeGenModule::EmitDeferred() {
Chris Lattner38837f92009-03-21 09:44:56 +0000420 // Emit code for any potentially referenced deferred decls. Since a
421 // previously unused static decl may become used during the generation of code
422 // for a static function, iterate until no changes are made.
423 while (!DeferredDeclsToEmit.empty()) {
424 const ValueDecl *D = DeferredDeclsToEmit.back();
425 DeferredDeclsToEmit.pop_back();
426
427 // The mangled name for the decl must have been emitted in GlobalDeclMap.
428 // Look it up to see if it was defined with a stronger definition (e.g. an
429 // extern inline function with a strong function redefinition). If so,
430 // just ignore the deferred decl.
431 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
432 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlsson2e427d52009-01-04 02:08:04 +0000433
Chris Lattner38837f92009-03-21 09:44:56 +0000434 if (!CGRef->isDeclaration())
435 continue;
436
437 // Otherwise, emit the definition and move on to the next one.
438 EmitGlobalDefinition(D);
439 }
Chris Lattner4b009652007-07-25 00:24:17 +0000440}
441
Nate Begeman8a704172008-04-19 04:17:09 +0000442/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
443/// annotation information for a given GlobalValue. The annotation struct is
444/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000445/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000446/// created from the AnnotateAttr's annotation. The third field is a constant
447/// string containing the name of the translation unit. The fourth field is
448/// the line number in the file of the annotated value declaration.
449///
450/// FIXME: this does not unique the annotation string constants, as llvm-gcc
451/// appears to.
452///
453llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
454 const AnnotateAttr *AA,
455 unsigned LineNo) {
456 llvm::Module *M = &getModule();
457
458 // get [N x i8] constants for the annotation string, and the filename string
459 // which are the 2nd and 3rd elements of the global annotation structure.
460 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
461 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
462 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
463 true);
464
465 // Get the two global values corresponding to the ConstantArrays we just
466 // created to hold the bytes of the strings.
467 llvm::GlobalValue *annoGV =
468 new llvm::GlobalVariable(anno->getType(), false,
469 llvm::GlobalValue::InternalLinkage, anno,
470 GV->getName() + ".str", M);
471 // translation unit name string, emitted into the llvm.metadata section.
472 llvm::GlobalValue *unitGV =
473 new llvm::GlobalVariable(unit->getType(), false,
474 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
475
476 // Create the ConstantStruct that is the global annotion.
477 llvm::Constant *Fields[4] = {
478 llvm::ConstantExpr::getBitCast(GV, SBP),
479 llvm::ConstantExpr::getBitCast(annoGV, SBP),
480 llvm::ConstantExpr::getBitCast(unitGV, SBP),
481 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
482 };
483 return llvm::ConstantStruct::get(Fields, 4, false);
484}
485
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000486bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000487 // Never defer when EmitAllDecls is specified or the decl has
488 // attribute used.
489 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000490 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000491
492 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000493 // Constructors and destructors should never be deferred.
494 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
495 return false;
496
Chris Lattner7e5888f2009-03-21 08:03:33 +0000497 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000498 if (FD->getStorageClass() != FunctionDecl::Static)
499 return false;
500 } else {
501 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000502 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000503
504 if (VD->getStorageClass() != VarDecl::Static)
505 return false;
506 }
507
508 return true;
509}
510
511void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Daniel Dunbar36acae42009-03-19 08:27:24 +0000512 // Aliases are deferred until code for everything else has been
513 // emitted.
514 if (Global->getAttr<AliasAttr>()) {
515 Aliases.push_back(Global);
516 return;
517 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000518
Chris Lattner38837f92009-03-21 09:44:56 +0000519 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar36acae42009-03-19 08:27:24 +0000520 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000521 // Forward declarations are emitted lazily on first use.
522 if (!FD->isThisDeclarationADefinition())
523 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000524 } else {
525 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000526 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
527
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000528 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000529 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000530 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000531 }
532
Chris Lattner38837f92009-03-21 09:44:56 +0000533 // Defer code generation when possible if this is a static definition, inline
534 // function etc. These we only want to emit if they are used.
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000535 if (MayDeferGeneration(Global)) {
Chris Lattner38837f92009-03-21 09:44:56 +0000536 // If the value has already been used, add it directly to the
537 // DeferredDeclsToEmit list.
538 const char *MangledName = getMangledName(Global);
539 if (GlobalDeclMap.count(MangledName))
540 DeferredDeclsToEmit.push_back(Global);
541 else {
542 // Otherwise, remember that we saw a deferred decl with this name. The
543 // first use of the mangled name will cause it to move into
544 // DeferredDeclsToEmit.
545 DeferredDecls[MangledName] = Global;
546 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000547 return;
548 }
549
550 // Otherwise emit the definition.
551 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000552}
553
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000554void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
556 EmitGlobalFunctionDefinition(FD);
557 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
558 EmitGlobalVarDefinition(VD);
559 } else {
560 assert(0 && "Invalid argument to EmitGlobalDefinition()");
561 }
562}
563
Chris Lattneraea1aee2009-03-22 21:03:39 +0000564/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
565/// module, create and return an llvm Function with the specified type. If there
566/// is something in the module with the specified name, return it potentially
567/// bitcasted to the right type.
568///
569/// If D is non-null, it specifies a decl that correspond to this. This is used
570/// to set the attributes on the function when it is first created.
571llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
572 const llvm::Type *Ty,
573 const FunctionDecl *D) {
Chris Lattner5dd030f2009-03-21 09:25:43 +0000574 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000575 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
576 if (Entry) {
577 if (Entry->getType()->getElementType() == Ty)
578 return Entry;
579
580 // Make sure the result is of the correct type.
581 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
582 return llvm::ConstantExpr::getBitCast(Entry, PTy);
583 }
584
Chris Lattner38837f92009-03-21 09:44:56 +0000585 // This is the first use or definition of a mangled name. If there is a
586 // deferred decl with this name, remember that we need to emit it at the end
587 // of the file.
588 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000589 DeferredDecls.find(MangledName);
Chris Lattner38837f92009-03-21 09:44:56 +0000590 if (DDI != DeferredDecls.end()) {
591 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
592 // list, and remove it from DeferredDecls (since we don't need it anymore).
593 DeferredDeclsToEmit.push_back(DDI->second);
594 DeferredDecls.erase(DDI);
595 }
596
Chris Lattner5dd030f2009-03-21 09:25:43 +0000597 // This function doesn't have a complete type (for example, the return
598 // type is an incomplete struct). Use a fake type instead, and make
599 // sure not to try to set attributes.
600 bool ShouldSetAttributes = true;
601 if (!isa<llvm::FunctionType>(Ty)) {
602 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
603 std::vector<const llvm::Type*>(), false);
604 ShouldSetAttributes = false;
605 }
606 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
607 llvm::Function::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000608 "", &getModule());
609 F->setName(MangledName);
Chris Lattneraea1aee2009-03-22 21:03:39 +0000610 if (D && ShouldSetAttributes)
Chris Lattner5dd030f2009-03-21 09:25:43 +0000611 SetFunctionAttributes(D, F);
612 Entry = F;
613 return F;
614}
615
Chris Lattneraea1aee2009-03-22 21:03:39 +0000616/// GetAddrOfFunction - Return the address of the given function. If Ty is
617/// non-null, then this function will use the specified type if it has to
618/// create it (this occurs when we see a definition of the function).
619llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
620 const llvm::Type *Ty) {
621 // If there was no specific requested type, just convert it now.
622 if (!Ty)
623 Ty = getTypes().ConvertType(D->getType());
624 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
625}
Eli Friedman43a0ce82008-05-30 19:50:47 +0000626
Chris Lattneraea1aee2009-03-22 21:03:39 +0000627/// CreateRuntimeFunction - Create a new runtime function with the specified
628/// type and name.
629llvm::Constant *
630CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
631 const char *Name) {
632 // Convert Name to be a uniqued string from the IdentifierInfo table.
633 Name = getContext().Idents.get(Name).getName();
634 return GetOrCreateLLVMFunction(Name, FTy, 0);
635}
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000636
Chris Lattneraea1aee2009-03-22 21:03:39 +0000637/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
638/// create and return an llvm GlobalVariable with the specified type. If there
639/// is something in the module with the specified name, return it potentially
640/// bitcasted to the right type.
641///
642/// If D is non-null, it specifies a decl that correspond to this. This is used
643/// to set the attributes on the global when it is first created.
644llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
645 const llvm::PointerType*Ty,
646 const VarDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000647 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000648 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000649 if (Entry) {
Chris Lattneraea1aee2009-03-22 21:03:39 +0000650 if (Entry->getType() == Ty)
Chris Lattnera6984932009-03-21 09:16:30 +0000651 return Entry;
652
Chris Lattner7e5888f2009-03-21 08:03:33 +0000653 // Make sure the result is of the correct type.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000654 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000655 }
Chris Lattner38837f92009-03-21 09:44:56 +0000656
657 // This is the first use or definition of a mangled name. If there is a
658 // deferred decl with this name, remember that we need to emit it at the end
659 // of the file.
660 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
661 DeferredDecls.find(MangledName);
662 if (DDI != DeferredDecls.end()) {
663 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
664 // list, and remove it from DeferredDecls (since we don't need it anymore).
665 DeferredDeclsToEmit.push_back(DDI->second);
666 DeferredDecls.erase(DDI);
667 }
668
Chris Lattner7e5888f2009-03-21 08:03:33 +0000669 llvm::GlobalVariable *GV =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000670 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner7e5888f2009-03-21 08:03:33 +0000671 llvm::GlobalValue::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000672 0, "", &getModule(),
Chris Lattneraea1aee2009-03-22 21:03:39 +0000673 0, Ty->getAddressSpace());
Chris Lattner68306b32009-03-22 00:12:30 +0000674 GV->setName(MangledName);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000675
676 // Handle things which are present even on external declarations.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000677 if (D) {
678 // FIXME: This code is overly simple and should be merged with
679 // other global handling.
680 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner7e5888f2009-03-21 08:03:33 +0000681
Chris Lattneraea1aee2009-03-22 21:03:39 +0000682 // FIXME: Merge with other attribute handling code.
683 if (D->getStorageClass() == VarDecl::PrivateExtern)
684 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000685
Chris Lattneraea1aee2009-03-22 21:03:39 +0000686 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
687 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
688 }
689
Chris Lattner7e5888f2009-03-21 08:03:33 +0000690 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000691}
692
Chris Lattneraea1aee2009-03-22 21:03:39 +0000693
694/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
695/// given global variable. If Ty is non-null and if the global doesn't exist,
696/// then it will be greated with the specified type instead of whatever the
697/// normal requested type would be.
698llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
699 const llvm::Type *Ty) {
700 assert(D->hasGlobalStorage() && "Not a global variable");
701 QualType ASTTy = D->getType();
702 if (Ty == 0)
703 Ty = getTypes().ConvertTypeForMem(ASTTy);
704
705 const llvm::PointerType *PTy =
706 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
707 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
708}
709
710/// CreateRuntimeVariable - Create a new runtime global variable with the
711/// specified type and name.
712llvm::Constant *
713CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
714 const char *Name) {
715 // Convert Name to be a uniqued string from the IdentifierInfo table.
716 Name = getContext().Idents.get(Name).getName();
717 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
718}
719
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000720void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000721 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000722 QualType ASTTy = D->getType();
Eli Friedman43a0ce82008-05-30 19:50:47 +0000723
Chris Lattner4b009652007-07-25 00:24:17 +0000724 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000725 // This is a tentative definition; tentative definitions are
726 // implicitly initialized with { 0 }
Chris Lattnera6984932009-03-21 09:16:30 +0000727 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000728 if (ASTTy->isIncompleteArrayType()) {
729 // An incomplete array is normally [ TYPE x 0 ], but we need
730 // to fix it to [ TYPE x 1 ].
Chris Lattnera6984932009-03-21 09:16:30 +0000731 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000732 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000733 }
734 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000735 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000736 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000737 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000738 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000739 QualType T = D->getInit()->getType();
740 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
741 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000742 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000743
Chris Lattner23afd5b2009-03-21 08:13:05 +0000744 const llvm::Type* InitType = Init->getType();
Chris Lattnera6984932009-03-21 09:16:30 +0000745 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000746
Chris Lattnera6984932009-03-21 09:16:30 +0000747 // Strip off a bitcast if we got one back.
748 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
749 assert(CE->getOpcode() == llvm::Instruction::BitCast);
750 Entry = CE->getOperand(0);
751 }
752
753 // Entry is now either a Function or GlobalVariable.
754 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
755
756 // If we already have this global and it has an initializer, then
757 // we are in the rare situation where we emitted the defining
758 // declaration of the global and are now being asked to emit a
759 // definition which would be common. This occurs, for example, in
760 // the following situation because statics can be emitted out of
761 // order:
762 //
763 // static int x;
764 // static int *y = &x;
765 // static int x = 10;
766 // int **z = &y;
767 //
768 // Bail here so we don't blow away the definition. Note that if we
769 // can't distinguish here if we emitted a definition with a null
770 // initializer, but this case is safe.
771 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000772 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
773 return;
Chris Lattnera6984932009-03-21 09:16:30 +0000774 }
775
776 // We have a definition after a declaration with the wrong type.
777 // We must make a new GlobalVariable* and update everything that used OldGV
778 // (a declaration or tentative definition) with the new GlobalVariable*
779 // (which will be a definition).
780 //
781 // This happens if there is a prototype for a global (e.g.
782 // "extern int x[];") and then a definition of a different type (e.g.
783 // "int x[10];"). This also happens when an initializer has a different type
784 // from the type of the global (this happens with unions).
785 //
786 // FIXME: This also ends up happening if there's a definition followed by
787 // a tentative definition! (Although Sema rejects that construct
788 // at the moment.)
789 if (GV == 0 ||
790 GV->getType()->getElementType() != InitType ||
791 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
792
793 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
794 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000795
Chris Lattnera6984932009-03-21 09:16:30 +0000796 // Make a new global with the correct type, this is now guaranteed to work.
797 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000798 GV->takeName(cast<llvm::GlobalValue>(Entry));
799
Eli Friedman43a0ce82008-05-30 19:50:47 +0000800 // Replace all uses of the old global with the new global
801 llvm::Constant *NewPtrForOldDecl =
Chris Lattnera6984932009-03-21 09:16:30 +0000802 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
803 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000804
805 // Erase the old global, since it is no longer used.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000806 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed.
Chris Lattnera6984932009-03-21 09:16:30 +0000807 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000808 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000809
Nate Begeman8a704172008-04-19 04:17:09 +0000810 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
811 SourceManager &SM = Context.getSourceManager();
812 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000813 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000814 }
815
Chris Lattner4b009652007-07-25 00:24:17 +0000816 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000817 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000818 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000819
Chris Lattner402b3372008-03-03 03:28:21 +0000820 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000821 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000822 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000823
Chris Lattner4b009652007-07-25 00:24:17 +0000824 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000825 if (D->getStorageClass() == VarDecl::Static)
826 GV->setLinkage(llvm::Function::InternalLinkage);
827 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000828 GV->setLinkage(llvm::Function::DLLImportLinkage);
829 else if (D->getAttr<DLLExportAttr>())
830 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000831 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000832 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000833 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000834 // FIXME: This isn't right. This should handle common linkage and other
835 // stuff.
836 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000837 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000838 case VarDecl::Auto:
839 case VarDecl::Register:
840 assert(0 && "Can't have auto or register globals");
841 case VarDecl::None:
842 if (!D->getInit())
Duncan Sands78c33cc2009-03-11 20:15:27 +0000843 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000844 else
845 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000846 break;
847 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000848 // FIXME: common
849 break;
850
Chris Lattner402b3372008-03-03 03:28:21 +0000851 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000852 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
853 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000854 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000855 }
Chris Lattner4b009652007-07-25 00:24:17 +0000856 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000857
Daniel Dunbar97509722009-02-12 17:28:23 +0000858 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
859 GV->setSection(SA->getName());
860
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000861 if (D->getAttr<UsedAttr>())
862 AddUsedGlobal(GV);
863
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000864 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000865 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000866 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000867 DI->EmitGlobalVariable(GV, D);
868 }
Chris Lattner4b009652007-07-25 00:24:17 +0000869}
870
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000871
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000872void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000873 const llvm::FunctionType *Ty =
874 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
875
876 // As a special case, make sure that definitions of K&R function
877 // "type foo()" aren't declared as varargs (which forces the backend
878 // to do unnecessary work).
Chris Lattnerb7cee972009-03-22 19:35:37 +0000879 if (D->getType()->isFunctionNoProtoType()) {
880 assert(Ty->isVarArg() && "Didn't lower type as expected");
881 // Due to stret, the lowered function could have arguments. Just create the
882 // same type as was lowered by ConvertType but strip off the varargs bit.
883 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
884 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
885 }
Daniel Dunbar3f197842009-02-19 07:15:39 +0000886
Chris Lattnerd26784e2009-03-21 08:53:37 +0000887 // Get or create the prototype for teh function.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000888 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattnerd26784e2009-03-21 08:53:37 +0000889
Chris Lattner5dd030f2009-03-21 09:25:43 +0000890 // Strip off a bitcast if we got one back.
891 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
892 assert(CE->getOpcode() == llvm::Instruction::BitCast);
893 Entry = CE->getOperand(0);
894 }
895
896
897 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000898 // If the types mismatch then we have to rewrite the definition.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000899 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
900 "Shouldn't replace non-declaration");
Chris Lattnerd26784e2009-03-21 08:53:37 +0000901
Chris Lattnere28718c2009-03-21 08:38:50 +0000902 // F is the Function* for the one with the wrong type, we must make a new
903 // Function* and update everything that used F (a declaration) with the new
904 // Function* (which will be a definition).
905 //
906 // This happens if there is a prototype for a function
907 // (e.g. "int f()") and then a definition of a different type
908 // (e.g. "int f(int x)"). Start by making a new function of the
909 // correct type, RAUW, then steal the name.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000910 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000911 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
912 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattnere28718c2009-03-21 08:38:50 +0000913
914 // Replace uses of F with the Function we will endow with a body.
915 llvm::Constant *NewPtrForOldDecl =
Chris Lattner5dd030f2009-03-21 09:25:43 +0000916 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
917 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnere28718c2009-03-21 08:38:50 +0000918
919 // Ok, delete the old function now, which is dead.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000920 // FIXME: If it was attribute(used) the pointer will dangle from the
921 // LLVMUsed array!
Chris Lattner5dd030f2009-03-21 09:25:43 +0000922 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattnere28718c2009-03-21 08:38:50 +0000923
Chris Lattner5dd030f2009-03-21 09:25:43 +0000924 Entry = NewFn;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000925 }
Chris Lattner5dd030f2009-03-21 09:25:43 +0000926
927 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000928
Daniel Dunbar566a6502008-09-08 23:44:31 +0000929 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000930
Daniel Dunbar566a6502008-09-08 23:44:31 +0000931 SetFunctionAttributesForDefinition(D, Fn);
932
Chris Lattnerd26784e2009-03-21 08:53:37 +0000933 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000934 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattnerd26784e2009-03-21 08:53:37 +0000935 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000936 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000937}
938
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000939void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
940 // Make sure that this type is translated.
941 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000942}
943
944
Chris Lattnerab862cc2007-08-31 04:31:45 +0000945/// getBuiltinLibFunction
Mike Stump96b7a152009-02-27 22:42:30 +0000946llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000947 if (BuiltinID > BuiltinFunctions.size())
948 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000949
Chris Lattner9f2d6892007-12-13 00:38:03 +0000950 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
951 // a slot for it.
952 assert(BuiltinID && "Invalid Builtin ID");
Mike Stump96b7a152009-02-27 22:42:30 +0000953 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000954 if (FunctionSlot)
955 return FunctionSlot;
956
Douglas Gregor411889e2009-02-13 23:20:09 +0000957 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
958 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
959 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000960
Douglas Gregor411889e2009-02-13 23:20:09 +0000961 // Get the name, skip over the __builtin_ prefix (if necessary).
962 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
963 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
964 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000965
966 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000967 Builtin::Context::GetBuiltinTypeError Error;
968 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
969 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
970
Chris Lattnerab862cc2007-08-31 04:31:45 +0000971 const llvm::FunctionType *Ty =
972 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
973
974 // FIXME: This has a serious problem with code like this:
975 // void abs() {}
976 // ... __builtin_abs(x);
977 // The two versions of abs will collide. The fix is for the builtin to win,
978 // and for the existing one to be turned into a constantexpr cast of the
979 // builtin. In the case where the existing one is a static function, it
980 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000981 if (llvm::Function *Existing = getModule().getFunction(Name)) {
982 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
983 return FunctionSlot = Existing;
984 assert(Existing == 0 && "FIXME: Name collision");
985 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000986
Chris Lattner72cdb962009-03-01 18:47:06 +0000987 llvm::GlobalValue *&ExistingFn =
988 GlobalDeclMap[getContext().Idents.get(Name).getName()];
Chris Lattner71fc5812009-03-21 06:58:21 +0000989 assert(!ExistingFn && "Asking for the same builtin multiple times?");
Mike Stump96b7a152009-02-27 22:42:30 +0000990
Chris Lattnerab862cc2007-08-31 04:31:45 +0000991 // FIXME: param attributes for sext/zext etc.
Chris Lattner72cdb962009-03-01 18:47:06 +0000992 return FunctionSlot = ExistingFn =
Nate Begemanad320b62008-04-20 06:29:50 +0000993 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
994 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000995}
996
Chris Lattner4b23f942007-12-18 00:25:38 +0000997llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
998 unsigned NumTys) {
999 return llvm::Intrinsic::getDeclaration(&getModule(),
1000 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1001}
Chris Lattnerab862cc2007-08-31 04:31:45 +00001002
Chris Lattner4b009652007-07-25 00:24:17 +00001003llvm::Function *CodeGenModule::getMemCpyFn() {
1004 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +00001005 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1006 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +00001007}
Anders Carlsson36a04872007-08-21 00:21:21 +00001008
Eli Friedman8f08a252008-05-26 12:59:39 +00001009llvm::Function *CodeGenModule::getMemMoveFn() {
1010 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +00001011 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1012 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +00001013}
1014
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +00001015llvm::Function *CodeGenModule::getMemSetFn() {
1016 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +00001017 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1018 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +00001019}
Chris Lattner4b23f942007-12-18 00:25:38 +00001020
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001021static void appendFieldAndPadding(CodeGenModule &CGM,
1022 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +00001023 FieldDecl *FieldD, FieldDecl *NextFieldD,
1024 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +00001025 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001026 // Append the field.
1027 Fields.push_back(Field);
1028
Douglas Gregor8acb7272008-12-11 16:49:14 +00001029 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001030
1031 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001032 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001033 NextStructFieldNo = STy->getNumElements();
1034 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001035 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001036 }
1037
1038 // Append padding
1039 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1040 llvm::Constant *C =
1041 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1042
1043 Fields.push_back(C);
1044 }
1045}
1046
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001047// We still need to work out the details of handling UTF-16.
1048// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001049llvm::Constant *CodeGenModule::
1050GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001051 llvm::StringMapEntry<llvm::Constant *> &Entry =
1052 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1053
1054 if (Entry.getValue())
1055 return Entry.getValue();
1056
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001057 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1058 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001059
1060 if (!CFConstantStringClassRef) {
1061 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1062 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001063
1064 // FIXME: This is fairly broken if
1065 // __CFConstantStringClassReference is already defined, in that it
1066 // will get renamed and the user will most likely see an opaque
1067 // error message. This is a general issue with relying on
1068 // particular names.
1069 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001070 new llvm::GlobalVariable(Ty, false,
1071 llvm::GlobalVariable::ExternalLinkage, 0,
1072 "__CFConstantStringClassReference",
1073 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001074
1075 // Decay array -> ptr
1076 CFConstantStringClassRef =
1077 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001078 }
1079
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001080 QualType CFTy = getContext().getCFConstantStringType();
1081 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001082
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001083 const llvm::StructType *STy =
1084 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1085
1086 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001087 RecordDecl::field_iterator Field = CFRD->field_begin();
1088
Anders Carlsson36a04872007-08-21 00:21:21 +00001089 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001090 FieldDecl *CurField = *Field++;
1091 FieldDecl *NextField = *Field++;
1092 appendFieldAndPadding(*this, Fields, CurField, NextField,
1093 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001094
1095 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001096 CurField = NextField;
1097 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001098 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001099 appendFieldAndPadding(*this, Fields, CurField, NextField,
1100 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001101
1102 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001103 CurField = NextField;
1104 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001105 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001106 C = new llvm::GlobalVariable(C->getType(), true,
1107 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001108 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001109 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001110 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1111 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001112
1113 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001114 CurField = NextField;
1115 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001116 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001117 appendFieldAndPadding(*this, Fields, CurField, NextField,
1118 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001119
1120 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001121 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001122 llvm::GlobalVariable *GV =
1123 new llvm::GlobalVariable(C->getType(), true,
1124 llvm::GlobalVariable::InternalLinkage,
1125 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001126
Anders Carlsson9be009e2007-11-01 00:41:52 +00001127 GV->setSection("__DATA,__cfstring");
1128 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001129
Anders Carlsson9be009e2007-11-01 00:41:52 +00001130 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001131}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001132
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001133/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001134/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001135std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001136 const char *StrData = E->getStrData();
1137 unsigned Len = E->getByteLength();
1138
1139 const ConstantArrayType *CAT =
1140 getContext().getAsConstantArrayType(E->getType());
1141 assert(CAT && "String isn't pointer or array!");
1142
Chris Lattner14032222009-02-26 23:01:51 +00001143 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001144 std::string Str(StrData, StrData+Len);
1145 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001146
1147 if (E->isWide())
1148 RealLen *= getContext().Target.getWCharWidth()/8;
1149
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001150 Str.resize(RealLen, '\0');
1151
1152 return Str;
1153}
1154
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001155/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1156/// constant array for the given string literal.
1157llvm::Constant *
1158CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1159 // FIXME: This can be more efficient.
1160 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1161}
1162
Chris Lattnerc5d32632009-02-24 22:18:39 +00001163/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1164/// array for the given ObjCEncodeExpr node.
1165llvm::Constant *
1166CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1167 std::string Str;
1168 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001169
1170 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001171}
1172
1173
Chris Lattnera6dcce32008-02-11 00:02:17 +00001174/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001175static llvm::Constant *GenerateStringLiteral(const std::string &str,
1176 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001177 CodeGenModule &CGM,
1178 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001179 // Create Constant for this string literal. Don't add a '\0'.
1180 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001181
1182 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001183 return new llvm::GlobalVariable(C->getType(), constant,
1184 llvm::GlobalValue::InternalLinkage,
1185 C, GlobalName ? GlobalName : ".str",
1186 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001187}
1188
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001189/// GetAddrOfConstantString - Returns a pointer to a character array
1190/// containing the literal. This contents are exactly that of the
1191/// given string, i.e. it will not be null terminated automatically;
1192/// see GetAddrOfConstantCString. Note that whether the result is
1193/// actually a pointer to an LLVM constant depends on
1194/// Feature.WriteableStrings.
1195///
1196/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001197llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1198 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001199 // Don't share any string literals if writable-strings is turned on.
1200 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001201 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001202
1203 llvm::StringMapEntry<llvm::Constant *> &Entry =
1204 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1205
1206 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001207 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001208
1209 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001210 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001211 Entry.setValue(C);
1212 return C;
1213}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001214
1215/// GetAddrOfConstantCString - Returns a pointer to a character
1216/// array containing the literal and a terminating '\-'
1217/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001218llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1219 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001220 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001221}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001222
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001223/// EmitObjCPropertyImplementations - Emit information for synthesized
1224/// properties for an implementation.
1225void CodeGenModule::EmitObjCPropertyImplementations(const
1226 ObjCImplementationDecl *D) {
1227 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1228 e = D->propimpl_end(); i != e; ++i) {
1229 ObjCPropertyImplDecl *PID = *i;
1230
1231 // Dynamic is just for type-checking.
1232 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1233 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1234
1235 // Determine which methods need to be implemented, some may have
1236 // been overridden. Note that ::isSynthesized is not the method
1237 // we want, that just indicates if the decl came from a
1238 // property. What we want to know is if the method is defined in
1239 // this implementation.
1240 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001241 CodeGenFunction(*this).GenerateObjCGetter(
1242 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001243 if (!PD->isReadOnly() &&
1244 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001245 CodeGenFunction(*this).GenerateObjCSetter(
1246 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001247 }
1248 }
1249}
1250
Daniel Dunbar27250d32008-08-15 23:26:23 +00001251/// EmitTopLevelDecl - Emit code for a single top level declaration.
1252void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1253 // If an error has occurred, stop code generation, but continue
1254 // parsing and semantic analysis (to ensure all warnings and errors
1255 // are emitted).
1256 if (Diags.hasErrorOccurred())
1257 return;
1258
1259 switch (D->getKind()) {
1260 case Decl::Function:
1261 case Decl::Var:
1262 EmitGlobal(cast<ValueDecl>(D));
1263 break;
1264
1265 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001266 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001267 break;
1268
1269 // Objective-C Decls
1270
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001271 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001272 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001273 case Decl::ObjCForwardProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001274 case Decl::ObjCCategory:
1275 case Decl::ObjCInterface:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001276 break;
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001277
Daniel Dunbar27250d32008-08-15 23:26:23 +00001278 case Decl::ObjCProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001279 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001280 break;
1281
1282 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001283 // Categories have properties but don't support synthesize so we
1284 // can ignore them here.
1285
Daniel Dunbar27250d32008-08-15 23:26:23 +00001286 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1287 break;
1288
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001289 case Decl::ObjCImplementation: {
1290 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1291 EmitObjCPropertyImplementations(OMD);
1292 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001293 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001294 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001295 case Decl::ObjCMethod: {
1296 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1297 // If this is not a prototype, emit the body.
1298 if (OMD->getBody())
1299 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1300 break;
1301 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001302 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001303 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001304 break;
1305
1306 case Decl::LinkageSpec: {
1307 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1308 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001309 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001310 // FIXME: implement C++ linkage, C linkage works mostly by C
1311 // language reuse already.
1312 break;
1313 }
1314
1315 case Decl::FileScopeAsm: {
1316 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1317 std::string AsmString(AD->getAsmString()->getStrData(),
1318 AD->getAsmString()->getByteLength());
1319
1320 const std::string &S = getModule().getModuleInlineAsm();
1321 if (S.empty())
1322 getModule().setModuleInlineAsm(AsmString);
1323 else
1324 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1325 break;
1326 }
1327
1328 default:
1329 // Make sure we handled everything we should, every other kind is
1330 // a non-top-level decl. FIXME: Would be nice to have an
1331 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1332 // that easily.
1333 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1334 }
1335}