blob: 953413d82476b2225ac485cb679981e1d3f1beff [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
41 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000042 if (Features.NeXTRuntime) {
Fariborz Jahaniand0374812009-01-22 23:02:58 +000043 Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
Fariborz Jahanian48543f52009-01-21 22:04:16 +000044 : CreateMacObjCRuntime(*this);
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000045 } else {
46 Runtime = CreateGNUObjCRuntime(*this);
47 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000048 }
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 Dunbar21f3cf72009-02-13 20:29:50 +000060 EmitDeferred();
Daniel Dunbar566a6502008-09-08 23:44:31 +000061 EmitAliases();
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 BindRuntimeFunctions();
Chris Lattnercbfb5512008-03-01 08:45:05 +000070}
Chris Lattner4b009652007-07-25 00:24:17 +000071
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000072void CodeGenModule::BindRuntimeFunctions() {
73 // Deal with protecting runtime function names.
74 for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
75 llvm::Function *Fn = RuntimeFunctions[i].first;
76 const std::string &Name = RuntimeFunctions[i].second;
77
Daniel Dunbarfc1543e2008-11-19 06:15:35 +000078 // Discard unused runtime functions.
79 if (Fn->use_empty()) {
80 Fn->eraseFromParent();
81 continue;
82 }
83
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000084 // See if there is a conflict against a function.
85 llvm::Function *Conflict = TheModule.getFunction(Name);
86 if (Conflict) {
87 // Decide which version to take. If the conflict is a definition
88 // we are forced to take that, otherwise assume the runtime
89 // knows best.
90 if (!Conflict->isDeclaration()) {
91 llvm::Value *Casted =
92 llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
93 Fn->replaceAllUsesWith(Casted);
94 Fn->eraseFromParent();
95 } else {
96 Fn->takeName(Conflict);
97 llvm::Value *Casted =
98 llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
99 Conflict->replaceAllUsesWith(Casted);
100 Conflict->eraseFromParent();
101 }
102 } else {
103 // FIXME: There still may be conflicts with aliases and
104 // variables.
105 Fn->setName(Name);
106 }
107 }
108}
109
Daniel Dunbar9503b782008-08-16 00:56:44 +0000110/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000111/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000112void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
113 bool OmitOnError) {
114 if (OmitOnError && getDiags().hasErrorOccurred())
115 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000116 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000117 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000118 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000119 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
120 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000121}
Chris Lattner0e4755d2007-12-02 06:27:33 +0000122
Daniel Dunbar9503b782008-08-16 00:56:44 +0000123/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +0000124/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000125void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
126 bool OmitOnError) {
127 if (OmitOnError && getDiags().hasErrorOccurred())
128 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +0000129 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +0000130 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +0000131 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +0000132 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +0000133}
134
Daniel Dunbar27250d32008-08-15 23:26:23 +0000135/// setGlobalVisibility - Set the visibility for the given LLVM
136/// GlobalValue according to the given clang AST visibility value.
137static void setGlobalVisibility(llvm::GlobalValue *GV,
138 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000139 switch (Vis) {
140 default: assert(0 && "Unknown visibility!");
141 case VisibilityAttr::DefaultVisibility:
142 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
143 break;
144 case VisibilityAttr::HiddenVisibility:
145 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
146 break;
147 case VisibilityAttr::ProtectedVisibility:
148 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
149 break;
150 }
151}
152
Douglas Gregor3556bc72009-02-13 00:10:09 +0000153/// \brief Retrieves the mangled name for the given declaration.
154///
155/// If the given declaration requires a mangled name, returns an
156/// IdentifierInfo* containing the mangled name. Otherwise, returns
157/// the name of the declaration as an identifier.
158///
159/// FIXME: Returning an IdentifierInfo* here is a total hack. We
160/// really need some kind of string abstraction that either stores a
161/// mangled name or stores an IdentifierInfo*. This will require
Daniel Dunbar7b7f4f42009-02-18 22:52:09 +0000162/// changes to the GlobalDeclMap, too. (I disagree, I think what we
163/// actually need is for Sema to provide some notion of which Decls
164/// refer to the same semantic decl. We shouldn't need to mangle the
165/// names and see what comes out the same to figure this out. - DWD)
Douglas Gregor3556bc72009-02-13 00:10:09 +0000166///
167/// FIXME: Performance here is going to be terribly until we start
168/// caching mangled names. However, we should fix the problem above
169/// first.
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000170const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
171 llvm::SmallString<256> Name;
172 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000173 if (!mangleName(ND, Context, Out)) {
174 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000175 return ND->getIdentifier()->getName();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000176 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000177
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000178 Name += '\0';
179 return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
180 .getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000181}
182
Chris Lattner753d2592008-03-14 17:18:18 +0000183/// AddGlobalCtor - Add a function to the list that will be called before
184/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000185void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000186 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000187 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000188}
189
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000190/// AddGlobalDtor - Add a function to the list that will be called
191/// when the module is unloaded.
192void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000193 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000194 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
195}
196
197void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
198 // Ctor function type is void()*.
199 llvm::FunctionType* CtorFTy =
200 llvm::FunctionType::get(llvm::Type::VoidTy,
201 std::vector<const llvm::Type*>(),
202 false);
203 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
204
205 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000206 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000207 llvm::StructType::get(llvm::Type::Int32Ty,
208 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000209
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000210 // Construct the constructor and destructor arrays.
211 std::vector<llvm::Constant*> Ctors;
212 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
213 std::vector<llvm::Constant*> S;
214 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
215 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
216 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000217 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000218
219 if (!Ctors.empty()) {
220 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
221 new llvm::GlobalVariable(AT, false,
222 llvm::GlobalValue::AppendingLinkage,
223 llvm::ConstantArray::get(AT, Ctors),
224 GlobalName,
225 &TheModule);
226 }
Chris Lattner753d2592008-03-14 17:18:18 +0000227}
228
Nate Begeman52da5c72008-04-18 23:43:57 +0000229void CodeGenModule::EmitAnnotations() {
230 if (Annotations.empty())
231 return;
232
233 // Create a new global variable for the ConstantStruct in the Module.
234 llvm::Constant *Array =
235 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
236 Annotations.size()),
237 Annotations);
238 llvm::GlobalValue *gv =
239 new llvm::GlobalVariable(Array->getType(), false,
240 llvm::GlobalValue::AppendingLinkage, Array,
241 "llvm.global.annotations", &TheModule);
242 gv->setSection("llvm.metadata");
243}
244
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000245void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
246 bool IsInternal,
247 bool IsInline,
248 llvm::GlobalValue *GV,
249 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000250 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000251 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000252 if (!ForDefinition) {
253 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000254 if (D->getAttr<DLLImportAttr>()) {
255 // The dllimport attribute is overridden by a subsequent declaration as
256 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000257 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000258 // dllimport attribute can be applied only to function decls, not to
259 // definitions.
260 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
261 if (!FD->getBody())
262 GV->setLinkage(llvm::Function::DLLImportLinkage);
263 } else
264 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000265 }
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000266 } else if (D->getAttr<WeakAttr>() ||
267 D->getAttr<WeakImportAttr>()) {
268 // "extern_weak" is overloaded in LLVM; we probably should have
269 // separate linkage types for this.
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000270 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000271 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000272 } else {
273 if (IsInternal) {
274 GV->setLinkage(llvm::Function::InternalLinkage);
275 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000276 if (D->getAttr<DLLExportAttr>()) {
277 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
278 // The dllexport attribute is ignored for undefined symbols.
279 if (FD->getBody())
280 GV->setLinkage(llvm::Function::DLLExportLinkage);
281 } else
282 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000283 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
284 IsInline)
Daniel Dunbar566a6502008-09-08 23:44:31 +0000285 GV->setLinkage(llvm::Function::WeakLinkage);
286 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000287 }
Nuno Lopes78534382008-06-08 15:45:52 +0000288
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000289 // FIXME: Figure out the relative priority of the attribute,
290 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000291 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000292 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000293 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000294
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000295 // Prefaced with special LLVM marker to indicate that the name
296 // should not be munged.
297 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
Daniel Dunbarced89142008-08-06 00:03:29 +0000298 GV->setName("\01" + ALA->getLabel());
Daniel Dunbar97509722009-02-12 17:28:23 +0000299
300 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
301 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000302
303 // Only add to llvm.used when we see a definition, otherwise we
304 // might add multiple times or risk the value being replaced by a
305 // subsequent RAUW.
306 if (ForDefinition) {
307 if (D->getAttr<UsedAttr>())
308 AddUsedGlobal(GV);
309 }
Nuno Lopes78534382008-06-08 15:45:52 +0000310}
311
Devang Patela85a9ef2008-09-25 21:02:23 +0000312void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000313 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000314 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000315 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000316 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000317
Devang Patela85a9ef2008-09-25 21:02:23 +0000318 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
319 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000320
321 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000322 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000323 F->setCallingConv(llvm::CallingConv::X86_FastCall);
324
325 if (D->getAttr<StdCallAttr>())
326 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000327}
328
329/// SetFunctionAttributesForDefinition - Set function attributes
330/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000331void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
332 llvm::Function *F) {
333 if (isa<ObjCMethodDecl>(D)) {
334 SetGlobalValueAttributes(D, true, false, F, true);
335 } else {
336 const FunctionDecl *FD = cast<FunctionDecl>(D);
337 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
338 FD->isInline(), F, true);
339 }
340
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000341 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000342 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000343
344 if (D->getAttr<AlwaysInlineAttr>())
345 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000346
347 if (D->getAttr<NoinlineAttr>())
348 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000349}
350
351void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
352 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000353 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000354
Daniel Dunbar566a6502008-09-08 23:44:31 +0000355 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000356}
357
358void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
359 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000360 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000361
Daniel Dunbar566a6502008-09-08 23:44:31 +0000362 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
363 FD->isInline(), F, false);
364}
365
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000366
Daniel Dunbar566a6502008-09-08 23:44:31 +0000367void CodeGenModule::EmitAliases() {
368 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
369 const FunctionDecl *D = Aliases[i];
370 const AliasAttr *AA = D->getAttr<AliasAttr>();
371
372 // This is something of a hack, if the FunctionDecl got overridden
373 // then its attributes will be moved to the new declaration. In
374 // this case the current decl has no alias attribute, but we will
375 // eventually see it.
376 if (!AA)
377 continue;
378
379 const std::string& aliaseeName = AA->getAliasee();
380 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
381 if (!aliasee) {
382 // FIXME: This isn't unsupported, this is just an error, which
383 // sema should catch, but...
384 ErrorUnsupported(D, "alias referencing a missing function");
385 continue;
386 }
387
388 llvm::GlobalValue *GA =
389 new llvm::GlobalAlias(aliasee->getType(),
390 llvm::Function::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000391 getMangledName(D), aliasee,
Douglas Gregor3556bc72009-02-13 00:10:09 +0000392 &getModule());
Daniel Dunbar566a6502008-09-08 23:44:31 +0000393
Douglas Gregor3556bc72009-02-13 00:10:09 +0000394 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar566a6502008-09-08 23:44:31 +0000395 if (Entry) {
396 // If we created a dummy function for this then replace it.
397 GA->takeName(Entry);
398
399 llvm::Value *Casted =
400 llvm::ConstantExpr::getBitCast(GA, Entry->getType());
401 Entry->replaceAllUsesWith(Casted);
402 Entry->eraseFromParent();
403
404 Entry = GA;
405 }
406
407 // Alias should never be internal or inline.
408 SetGlobalValueAttributes(D, false, false, GA, true);
409 }
Eli Friedman9be42212008-06-01 15:54:49 +0000410}
411
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000412void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
413 assert(!GV->isDeclaration() &&
414 "Only globals with definition can force usage.");
415 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
416 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
417}
418
419void CodeGenModule::EmitLLVMUsed() {
420 // Don't create llvm.used if there is no need.
421 if (LLVMUsed.empty())
422 return;
423
424 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
425 LLVMUsed.size());
426 llvm::GlobalVariable *GV =
427 new llvm::GlobalVariable(ATy, false,
428 llvm::GlobalValue::AppendingLinkage,
429 llvm::ConstantArray::get(ATy, LLVMUsed),
430 "llvm.used", &getModule());
431
432 GV->setSection("llvm.metadata");
433}
434
435void CodeGenModule::EmitDeferred() {
436 // Emit code for any deferred decl which was used. Since a
437 // previously unused static decl may become used during the
438 // generation of code for a static function, iterate until no
439 // changes are made.
Nate Begemanad320b62008-04-20 06:29:50 +0000440 bool Changed;
441 do {
442 Changed = false;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000443
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000444 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
445 e = DeferredDecls.end(); i != e; ) {
Anders Carlsson2e427d52009-01-04 02:08:04 +0000446 const ValueDecl *D = *i;
447
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000448 // Check if we have used a decl with the same name
449 // FIXME: The AST should have some sort of aggregate decls or
450 // global symbol map.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000451 // FIXME: This is missing some important cases. For example, we
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000452 // need to check for uses in an alias.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000453 if (!GlobalDeclMap.count(getMangledName(D))) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000454 ++i;
Daniel Dunbarced89142008-08-06 00:03:29 +0000455 continue;
Anders Carlsson2e427d52009-01-04 02:08:04 +0000456 }
457
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000458 // Emit the definition.
459 EmitGlobalDefinition(D);
460
Nate Begemanad320b62008-04-20 06:29:50 +0000461 // Erase the used decl from the list.
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000462 i = DeferredDecls.erase(i);
Anders Carlsson2e427d52009-01-04 02:08:04 +0000463
Nate Begemanad320b62008-04-20 06:29:50 +0000464 // Remember that we made a change.
465 Changed = true;
466 }
467 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000468}
469
Nate Begeman8a704172008-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 Dunbara31eaf72008-08-05 23:31:02 +0000473/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-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.
495 llvm::GlobalValue *annoGV =
496 new llvm::GlobalVariable(anno->getType(), false,
497 llvm::GlobalValue::InternalLinkage, anno,
498 GV->getName() + ".str", M);
499 // translation unit name string, emitted into the llvm.metadata section.
500 llvm::GlobalValue *unitGV =
501 new llvm::GlobalVariable(unit->getType(), false,
502 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
503
504 // Create the ConstantStruct that is the global annotion.
505 llvm::Constant *Fields[4] = {
506 llvm::ConstantExpr::getBitCast(GV, SBP),
507 llvm::ConstantExpr::getBitCast(annoGV, SBP),
508 llvm::ConstantExpr::getBitCast(unitGV, SBP),
509 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
510 };
511 return llvm::ConstantStruct::get(Fields, 4, false);
512}
513
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000514bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000515 // Never defer when EmitAllDecls is specified or the decl has
516 // attribute used.
517 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000518 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000519
520 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000521 // Constructors and destructors should never be deferred.
522 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
523 return false;
524
525 if (FD->getStorageClass() != FunctionDecl::Static)
526 return false;
527 } else {
528 const VarDecl *VD = cast<VarDecl>(Global);
529 assert(VD->isFileVarDecl() && "Invalid decl.");
530
531 if (VD->getStorageClass() != VarDecl::Static)
532 return false;
533 }
534
535 return true;
536}
537
538void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
539 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar566a6502008-09-08 23:44:31 +0000540 // Aliases are deferred until code for everything else has been
541 // emitted.
542 if (FD->getAttr<AliasAttr>()) {
543 assert(!FD->isThisDeclarationADefinition() &&
544 "Function alias cannot have a definition!");
545 Aliases.push_back(FD);
546 return;
547 }
548
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000549 // Forward declarations are emitted lazily on first use.
550 if (!FD->isThisDeclarationADefinition())
551 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000552 } else {
553 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000554 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
555
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000556 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000557 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000558 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000559 }
560
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000561 // Defer code generation when possible.
562 if (MayDeferGeneration(Global)) {
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000563 DeferredDecls.push_back(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000564 return;
565 }
566
567 // Otherwise emit the definition.
568 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000569}
570
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000571void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
572 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
573 EmitGlobalFunctionDefinition(FD);
574 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
575 EmitGlobalVarDefinition(VD);
576 } else {
577 assert(0 && "Invalid argument to EmitGlobalDefinition()");
578 }
579}
580
Daniel Dunbar2188c532008-07-30 16:32:24 +0000581 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000582 assert(D->hasGlobalStorage() && "Not a global variable");
583
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000584 QualType ASTTy = D->getType();
585 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000586 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000587
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000588 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000589 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000590 if (!Entry) {
591 llvm::GlobalVariable *GV =
592 new llvm::GlobalVariable(Ty, false,
593 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000594 0, getMangledName(D), &getModule(),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000595 0, ASTTy.getAddressSpace());
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000596 Entry = GV;
597
598 // Handle things which are present even on external declarations.
599
600 // FIXME: This code is overly simple and should be merged with
601 // other global handling.
602
603 GV->setConstant(D->getType().isConstant(Context));
604
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000605 // FIXME: Merge with other attribute handling code.
606
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000607 if (D->getStorageClass() == VarDecl::PrivateExtern)
608 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000609
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000610 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Daniel Dunbar9fe04112009-02-21 00:24:10 +0000611 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Daniel Dunbar7cbac842009-03-04 17:31:19 +0000612
613 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
614 // Prefaced with special LLVM marker to indicate that the name
615 // should not be munged.
616 GV->setName("\01" + ALA->getLabel());
617 }
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000618 }
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000619
Daniel Dunbar2188c532008-07-30 16:32:24 +0000620 // Make sure the result is of the correct type.
621 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000622}
623
624void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000625 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000626 QualType ASTTy = D->getType();
627 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000628
Chris Lattner4b009652007-07-25 00:24:17 +0000629 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000630 // This is a tentative definition; tentative definitions are
631 // implicitly initialized with { 0 }
632 const llvm::Type* InitTy;
633 if (ASTTy->isIncompleteArrayType()) {
634 // An incomplete array is normally [ TYPE x 0 ], but we need
635 // to fix it to [ TYPE x 1 ].
636 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
637 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
638 } else {
639 InitTy = VarTy;
640 }
641 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000642 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000643 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000644 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000645 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000646 QualType T = D->getInit()->getType();
647 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
648 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000649 }
650 const llvm::Type* InitType = Init->getType();
651
Douglas Gregor3556bc72009-02-13 00:10:09 +0000652 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000653 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
654
Eli Friedman43a0ce82008-05-30 19:50:47 +0000655 if (!GV) {
656 GV = new llvm::GlobalVariable(InitType, false,
657 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000658 0, getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000659 &getModule(), 0, ASTTy.getAddressSpace());
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000660
661 } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
662 // If we already have this global and it has an initializer, then
663 // we are in the rare situation where we emitted the defining
664 // declaration of the global and are now being asked to emit a
665 // definition which would be common. This occurs, for example, in
666 // the following situation because statics can be emitted out of
667 // order:
668 //
669 // static int x;
670 // static int *y = &x;
671 // static int x = 10;
672 // int **z = &y;
673 //
674 // Bail here so we don't blow away the definition. Note that if we
675 // can't distinguish here if we emitted a definition with a null
676 // initializer, but this case is safe.
677 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
678 return;
679
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000680 } else if (GV->getType() !=
681 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000682 // We have a definition after a prototype with the wrong type.
683 // We must make a new GlobalVariable* and update everything that used OldGV
684 // (a declaration or tentative definition) with the new GlobalVariable*
685 // (which will be a definition).
686 //
687 // This happens if there is a prototype for a global (e.g. "extern int x[];")
688 // and then a definition of a different type (e.g. "int x[10];"). This also
689 // happens when an initializer has a different type from the type of the
690 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000691 //
692 // FIXME: This also ends up happening if there's a definition followed by
693 // a tentative definition! (Although Sema rejects that construct
694 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000695
696 // Save the old global
697 llvm::GlobalVariable *OldGV = GV;
698
699 // Make a new global with the correct type
700 GV = new llvm::GlobalVariable(InitType, false,
701 llvm::GlobalValue::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000702 0, getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000703 &getModule(), 0, ASTTy.getAddressSpace());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000704 // Steal the name of the old global
705 GV->takeName(OldGV);
706
707 // Replace all uses of the old global with the new global
708 llvm::Constant *NewPtrForOldDecl =
709 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
710 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000711
712 // Erase the old global, since it is no longer used.
713 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000714 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000715
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000716 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000717
Nate Begeman8a704172008-04-19 04:17:09 +0000718 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
719 SourceManager &SM = Context.getSourceManager();
720 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000721 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000722 }
723
Chris Lattner4b009652007-07-25 00:24:17 +0000724 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000725 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000726 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000727
Chris Lattner402b3372008-03-03 03:28:21 +0000728 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000729 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000730 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000731
732 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
733 // Prefaced with special LLVM marker to indicate that the name
734 // should not be munged.
735 GV->setName("\01" + ALA->getLabel());
736 }
Chris Lattner4b009652007-07-25 00:24:17 +0000737
738 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000739 if (D->getStorageClass() == VarDecl::Static)
740 GV->setLinkage(llvm::Function::InternalLinkage);
741 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000742 GV->setLinkage(llvm::Function::DLLImportLinkage);
743 else if (D->getAttr<DLLExportAttr>())
744 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000745 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000746 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000747 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000748 // FIXME: This isn't right. This should handle common linkage and other
749 // stuff.
750 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000751 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000752 case VarDecl::Auto:
753 case VarDecl::Register:
754 assert(0 && "Can't have auto or register globals");
755 case VarDecl::None:
756 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000757 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000758 else
759 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000760 break;
761 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000762 // FIXME: common
763 break;
764
Chris Lattner402b3372008-03-03 03:28:21 +0000765 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000766 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
767 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000768 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000769 }
Chris Lattner4b009652007-07-25 00:24:17 +0000770 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000771
Daniel Dunbar97509722009-02-12 17:28:23 +0000772 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
773 GV->setSection(SA->getName());
774
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000775 if (D->getAttr<UsedAttr>())
776 AddUsedGlobal(GV);
777
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000778 // Emit global variable debug information.
779 CGDebugInfo *DI = getDebugInfo();
780 if(DI) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000781 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000782 DI->EmitGlobalVariable(GV, D);
783 }
Chris Lattner4b009652007-07-25 00:24:17 +0000784}
785
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000786llvm::GlobalValue *
Daniel Dunbar3f197842009-02-19 07:15:39 +0000787CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
788 const llvm::Type *Ty) {
Eli Friedman040f4db2009-03-05 04:18:07 +0000789 bool DoSetAttributes = true;
790 if (!Ty) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000791 Ty = getTypes().ConvertType(D->getType());
Eli Friedman040f4db2009-03-05 04:18:07 +0000792 if (!isa<llvm::FunctionType>(Ty)) {
793 // This function doesn't have a complete type (for example, the return
794 // type is an incomplete struct). Use a fake type instead, and make
795 // sure not to try to set attributes.
796 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
797 std::vector<const llvm::Type*>(), false);
798 DoSetAttributes = false;
799 }
800 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000801 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
802 llvm::Function::ExternalLinkage,
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000803 getMangledName(D),
Douglas Gregor3556bc72009-02-13 00:10:09 +0000804 &getModule());
Eli Friedman040f4db2009-03-05 04:18:07 +0000805 if (DoSetAttributes)
806 SetFunctionAttributes(D, F);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000807 return F;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000808}
809
810llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000811 QualType ASTTy = D->getType();
812 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
813 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000814
815 // Lookup the entry, lazily creating it if necessary.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000816 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000817 if (!Entry)
Daniel Dunbar3f197842009-02-19 07:15:39 +0000818 Entry = EmitForwardFunctionDefinition(D, 0);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000819
Daniel Dunbar2188c532008-07-30 16:32:24 +0000820 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000821}
822
823void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000824 const llvm::FunctionType *Ty =
825 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
826
827 // As a special case, make sure that definitions of K&R function
828 // "type foo()" aren't declared as varargs (which forces the backend
829 // to do unnecessary work).
830 if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
831 Ty = llvm::FunctionType::get(Ty->getReturnType(),
832 std::vector<const llvm::Type*>(),
833 false);
834
Douglas Gregor3556bc72009-02-13 00:10:09 +0000835 llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000836 if (!Entry) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000837 Entry = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000838 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000839 // If the types mismatch then we have to rewrite the definition.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000840 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000841 // Otherwise, we have a definition after a prototype with the
842 // wrong type. F is the Function* for the one with the wrong
843 // type, we must make a new Function* and update everything that
844 // used F (a declaration) with the new Function* (which will be
845 // a definition).
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000846 //
Daniel Dunbar3f197842009-02-19 07:15:39 +0000847 // This happens if there is a prototype for a function
848 // (e.g. "int f()") and then a definition of a different type
849 // (e.g. "int f(int x)"). Start by making a new function of the
850 // correct type, RAUW, then steal the name.
851 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000852 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000853
854 // Replace uses of F with the Function we will endow with a body.
855 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000856 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
857 Entry->replaceAllUsesWith(NewPtrForOldDecl);
858
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000859 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000860 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
Daniel Dunbar566a6502008-09-08 23:44:31 +0000861 Entry->eraseFromParent();
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000862
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000863 Entry = NewFn;
864 }
865 }
866
Daniel Dunbar566a6502008-09-08 23:44:31 +0000867 llvm::Function *Fn = cast<llvm::Function>(Entry);
868 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000869
Daniel Dunbar566a6502008-09-08 23:44:31 +0000870 SetFunctionAttributesForDefinition(D, Fn);
871
872 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
873 AddGlobalCtor(Fn, CA->getPriority());
874 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
875 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000876 }
877}
878
Daniel Dunbar18c2ec62008-10-01 00:49:24 +0000879llvm::Function *
880CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
881 const std::string &Name) {
882 llvm::Function *Fn = llvm::Function::Create(FTy,
883 llvm::Function::ExternalLinkage,
884 "", &TheModule);
885 RuntimeFunctions.push_back(std::make_pair(Fn, Name));
886 return Fn;
887}
888
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000889void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
890 // Make sure that this type is translated.
891 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000892}
893
894
Chris Lattnerab862cc2007-08-31 04:31:45 +0000895/// getBuiltinLibFunction
Mike Stump96b7a152009-02-27 22:42:30 +0000896llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000897 if (BuiltinID > BuiltinFunctions.size())
898 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000899
Chris Lattner9f2d6892007-12-13 00:38:03 +0000900 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
901 // a slot for it.
902 assert(BuiltinID && "Invalid Builtin ID");
Mike Stump96b7a152009-02-27 22:42:30 +0000903 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000904 if (FunctionSlot)
905 return FunctionSlot;
906
Douglas Gregor411889e2009-02-13 23:20:09 +0000907 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
908 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
909 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000910
Douglas Gregor411889e2009-02-13 23:20:09 +0000911 // Get the name, skip over the __builtin_ prefix (if necessary).
912 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
913 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
914 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000915
916 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000917 Builtin::Context::GetBuiltinTypeError Error;
918 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
919 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
920
Chris Lattnerab862cc2007-08-31 04:31:45 +0000921 const llvm::FunctionType *Ty =
922 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
923
924 // FIXME: This has a serious problem with code like this:
925 // void abs() {}
926 // ... __builtin_abs(x);
927 // The two versions of abs will collide. The fix is for the builtin to win,
928 // and for the existing one to be turned into a constantexpr cast of the
929 // builtin. In the case where the existing one is a static function, it
930 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000931 if (llvm::Function *Existing = getModule().getFunction(Name)) {
932 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
933 return FunctionSlot = Existing;
934 assert(Existing == 0 && "FIXME: Name collision");
935 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000936
Chris Lattner72cdb962009-03-01 18:47:06 +0000937 llvm::GlobalValue *&ExistingFn =
938 GlobalDeclMap[getContext().Idents.get(Name).getName()];
939 if (ExistingFn)
940 return FunctionSlot = llvm::ConstantExpr::getBitCast(ExistingFn, Ty);
Mike Stump96b7a152009-02-27 22:42:30 +0000941
Chris Lattnerab862cc2007-08-31 04:31:45 +0000942 // FIXME: param attributes for sext/zext etc.
Chris Lattner72cdb962009-03-01 18:47:06 +0000943 return FunctionSlot = ExistingFn =
Nate Begemanad320b62008-04-20 06:29:50 +0000944 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
945 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000946}
947
Chris Lattner4b23f942007-12-18 00:25:38 +0000948llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
949 unsigned NumTys) {
950 return llvm::Intrinsic::getDeclaration(&getModule(),
951 (llvm::Intrinsic::ID)IID, Tys, NumTys);
952}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000953
Chris Lattner4b009652007-07-25 00:24:17 +0000954llvm::Function *CodeGenModule::getMemCpyFn() {
955 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000956 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
957 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000958}
Anders Carlsson36a04872007-08-21 00:21:21 +0000959
Eli Friedman8f08a252008-05-26 12:59:39 +0000960llvm::Function *CodeGenModule::getMemMoveFn() {
961 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000962 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
963 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000964}
965
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000966llvm::Function *CodeGenModule::getMemSetFn() {
967 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000968 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
969 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000970}
Chris Lattner4b23f942007-12-18 00:25:38 +0000971
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000972static void appendFieldAndPadding(CodeGenModule &CGM,
973 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000974 FieldDecl *FieldD, FieldDecl *NextFieldD,
975 llvm::Constant* Field,
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000976 RecordDecl* RD, const llvm::StructType *STy)
977{
978 // Append the field.
979 Fields.push_back(Field);
980
Douglas Gregor8acb7272008-12-11 16:49:14 +0000981 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000982
983 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000984 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000985 NextStructFieldNo = STy->getNumElements();
986 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000987 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000988 }
989
990 // Append padding
991 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
992 llvm::Constant *C =
993 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
994
995 Fields.push_back(C);
996 }
997}
998
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000999// We still need to work out the details of handling UTF-16.
1000// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +00001001llvm::Constant *CodeGenModule::
1002GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +00001003 llvm::StringMapEntry<llvm::Constant *> &Entry =
1004 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1005
1006 if (Entry.getValue())
1007 return Entry.getValue();
1008
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001009 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1010 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001011
1012 if (!CFConstantStringClassRef) {
1013 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1014 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001015
1016 // FIXME: This is fairly broken if
1017 // __CFConstantStringClassReference is already defined, in that it
1018 // will get renamed and the user will most likely see an opaque
1019 // error message. This is a general issue with relying on
1020 // particular names.
1021 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001022 new llvm::GlobalVariable(Ty, false,
1023 llvm::GlobalVariable::ExternalLinkage, 0,
1024 "__CFConstantStringClassReference",
1025 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001026
1027 // Decay array -> ptr
1028 CFConstantStringClassRef =
1029 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001030 }
1031
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001032 QualType CFTy = getContext().getCFConstantStringType();
1033 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001034
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001035 const llvm::StructType *STy =
1036 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1037
1038 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001039 RecordDecl::field_iterator Field = CFRD->field_begin();
1040
Anders Carlsson36a04872007-08-21 00:21:21 +00001041 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001042 FieldDecl *CurField = *Field++;
1043 FieldDecl *NextField = *Field++;
1044 appendFieldAndPadding(*this, Fields, CurField, NextField,
1045 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001046
1047 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001048 CurField = NextField;
1049 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001050 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001051 appendFieldAndPadding(*this, Fields, CurField, NextField,
1052 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001053
1054 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001055 CurField = NextField;
1056 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001057 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +00001058 C = new llvm::GlobalVariable(C->getType(), true,
1059 llvm::GlobalValue::InternalLinkage,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001060 C, ".str", &getModule());
Douglas Gregor8acb7272008-12-11 16:49:14 +00001061 appendFieldAndPadding(*this, Fields, CurField, NextField,
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001062 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1063 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001064
1065 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001066 CurField = NextField;
1067 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001068 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001069 appendFieldAndPadding(*this, Fields, CurField, NextField,
1070 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001071
1072 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001073 C = llvm::ConstantStruct::get(STy, Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001074 llvm::GlobalVariable *GV =
1075 new llvm::GlobalVariable(C->getType(), true,
1076 llvm::GlobalVariable::InternalLinkage,
1077 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001078
Anders Carlsson9be009e2007-11-01 00:41:52 +00001079 GV->setSection("__DATA,__cfstring");
1080 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001081
Anders Carlsson9be009e2007-11-01 00:41:52 +00001082 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001083}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001084
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001085/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001086/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001087std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001088 const char *StrData = E->getStrData();
1089 unsigned Len = E->getByteLength();
1090
1091 const ConstantArrayType *CAT =
1092 getContext().getAsConstantArrayType(E->getType());
1093 assert(CAT && "String isn't pointer or array!");
1094
Chris Lattner14032222009-02-26 23:01:51 +00001095 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001096 std::string Str(StrData, StrData+Len);
1097 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001098
1099 if (E->isWide())
1100 RealLen *= getContext().Target.getWCharWidth()/8;
1101
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001102 Str.resize(RealLen, '\0');
1103
1104 return Str;
1105}
1106
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001107/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1108/// constant array for the given string literal.
1109llvm::Constant *
1110CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1111 // FIXME: This can be more efficient.
1112 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1113}
1114
Chris Lattnerc5d32632009-02-24 22:18:39 +00001115/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1116/// array for the given ObjCEncodeExpr node.
1117llvm::Constant *
1118CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1119 std::string Str;
1120 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1121
1122 llvm::Constant *C = llvm::ConstantArray::get(Str);
1123 C = new llvm::GlobalVariable(C->getType(), true,
1124 llvm::GlobalValue::InternalLinkage,
1125 C, ".str", &getModule());
1126 return C;
1127}
1128
1129
Chris Lattnera6dcce32008-02-11 00:02:17 +00001130/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001131static llvm::Constant *GenerateStringLiteral(const std::string &str,
1132 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001133 CodeGenModule &CGM,
1134 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001135 // Create Constant for this string literal. Don't add a '\0'.
1136 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001137
1138 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001139 return new llvm::GlobalVariable(C->getType(), constant,
1140 llvm::GlobalValue::InternalLinkage,
1141 C, GlobalName ? GlobalName : ".str",
1142 &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001143}
1144
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001145/// GetAddrOfConstantString - Returns a pointer to a character array
1146/// containing the literal. This contents are exactly that of the
1147/// given string, i.e. it will not be null terminated automatically;
1148/// see GetAddrOfConstantCString. Note that whether the result is
1149/// actually a pointer to an LLVM constant depends on
1150/// Feature.WriteableStrings.
1151///
1152/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001153llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1154 const char *GlobalName) {
Chris Lattnerdb6be562007-11-28 05:34:05 +00001155 // Don't share any string literals if writable-strings is turned on.
1156 if (Features.WritableStrings)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001157 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001158
1159 llvm::StringMapEntry<llvm::Constant *> &Entry =
1160 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1161
1162 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001163 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001164
1165 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001166 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001167 Entry.setValue(C);
1168 return C;
1169}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001170
1171/// GetAddrOfConstantCString - Returns a pointer to a character
1172/// array containing the literal and a terminating '\-'
1173/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001174llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1175 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001176 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001177}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001178
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001179/// EmitObjCPropertyImplementations - Emit information for synthesized
1180/// properties for an implementation.
1181void CodeGenModule::EmitObjCPropertyImplementations(const
1182 ObjCImplementationDecl *D) {
1183 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1184 e = D->propimpl_end(); i != e; ++i) {
1185 ObjCPropertyImplDecl *PID = *i;
1186
1187 // Dynamic is just for type-checking.
1188 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1189 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1190
1191 // Determine which methods need to be implemented, some may have
1192 // been overridden. Note that ::isSynthesized is not the method
1193 // we want, that just indicates if the decl came from a
1194 // property. What we want to know is if the method is defined in
1195 // this implementation.
1196 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001197 CodeGenFunction(*this).GenerateObjCGetter(
1198 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001199 if (!PD->isReadOnly() &&
1200 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001201 CodeGenFunction(*this).GenerateObjCSetter(
1202 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001203 }
1204 }
1205}
1206
Daniel Dunbar27250d32008-08-15 23:26:23 +00001207/// EmitTopLevelDecl - Emit code for a single top level declaration.
1208void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1209 // If an error has occurred, stop code generation, but continue
1210 // parsing and semantic analysis (to ensure all warnings and errors
1211 // are emitted).
1212 if (Diags.hasErrorOccurred())
1213 return;
1214
1215 switch (D->getKind()) {
1216 case Decl::Function:
1217 case Decl::Var:
1218 EmitGlobal(cast<ValueDecl>(D));
1219 break;
1220
1221 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +00001222 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001223 break;
1224
1225 // Objective-C Decls
1226
1227 // Forward declarations, no (immediate) code generation.
1228 case Decl::ObjCClass:
1229 case Decl::ObjCCategory:
1230 case Decl::ObjCForwardProtocol:
1231 case Decl::ObjCInterface:
1232 break;
1233
1234 case Decl::ObjCProtocol:
1235 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1236 break;
1237
1238 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001239 // Categories have properties but don't support synthesize so we
1240 // can ignore them here.
1241
Daniel Dunbar27250d32008-08-15 23:26:23 +00001242 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1243 break;
1244
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001245 case Decl::ObjCImplementation: {
1246 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1247 EmitObjCPropertyImplementations(OMD);
1248 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001249 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001250 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001251 case Decl::ObjCMethod: {
1252 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1253 // If this is not a prototype, emit the body.
1254 if (OMD->getBody())
1255 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1256 break;
1257 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001258 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001259 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001260 break;
1261
1262 case Decl::LinkageSpec: {
1263 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1264 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +00001265 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +00001266 // FIXME: implement C++ linkage, C linkage works mostly by C
1267 // language reuse already.
1268 break;
1269 }
1270
1271 case Decl::FileScopeAsm: {
1272 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1273 std::string AsmString(AD->getAsmString()->getStrData(),
1274 AD->getAsmString()->getByteLength());
1275
1276 const std::string &S = getModule().getModuleInlineAsm();
1277 if (S.empty())
1278 getModule().setModuleInlineAsm(AsmString);
1279 else
1280 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1281 break;
1282 }
1283
1284 default:
1285 // Make sure we handled everything we should, every other kind is
1286 // a non-top-level decl. FIXME: Would be nice to have an
1287 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1288 // that easily.
1289 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1290 }
1291}