blob: 79bf4de4f7a2ec5e9330f04df9e44dcdea35184a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000016#include "CodeGenFunction.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000017#include "CGCall.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Douglas Gregor5f2bfd42009-02-13 00:10:09 +000019#include "Mangle.h"
Chris Lattnerbd360642009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000024#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "clang/Basic/TargetInfo.h"
Steve Naroffe9b7d8a2009-04-01 15:50:34 +000027#include "clang/Basic/ConvertUTF.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000028#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000029#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000030#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000031#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33using namespace CodeGen;
34
35
Chris Lattnerbd360642009-03-26 05:00:52 +000036CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattnerfb97b032007-12-02 01:40:18 +000037 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerbd360642009-03-26 05:00:52 +000038 Diagnostic &diags)
39 : BlockModule(C, M, TD, Types, *this), Context(C),
40 Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
Mike Stump2a998142009-03-04 18:17:45 +000041 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
42 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000043
Chris Lattner3c8f1532009-03-21 07:12:05 +000044 if (!Features.ObjC1)
45 Runtime = 0;
46 else if (!Features.NeXTRuntime)
47 Runtime = CreateGNUObjCRuntime(*this);
48 else if (Features.ObjCNonFragileABI)
49 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
50 else
51 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000052
53 // If debug info generation is enabled, create the CGDebugInfo object.
Chris Lattnerbd360642009-03-26 05:00:52 +000054 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000055}
56
57CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000058 delete Runtime;
59 delete DebugInfo;
60}
61
62void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +000063 EmitDeferred();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000064 if (Runtime)
65 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
66 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000067 EmitCtorList(GlobalCtors, "llvm.global_ctors");
68 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000069 EmitAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +000070 EmitLLVMUsed();
Daniel Dunbarf1968f22008-10-01 00:49:24 +000071}
72
Daniel Dunbar488e9932008-08-16 00:56:44 +000073/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000074/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000075void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
76 bool OmitOnError) {
77 if (OmitOnError && getDiags().hasErrorOccurred())
78 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000079 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000080 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +000081 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000082 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
83 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +000084}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000085
Daniel Dunbar488e9932008-08-16 00:56:44 +000086/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000087/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000088void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
89 bool OmitOnError) {
90 if (OmitOnError && getDiags().hasErrorOccurred())
91 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000092 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +000093 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +000094 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +000095 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +000096}
97
Daniel Dunbar41071de2008-08-15 23:26:23 +000098/// setGlobalVisibility - Set the visibility for the given LLVM
99/// GlobalValue according to the given clang AST visibility value.
100static void setGlobalVisibility(llvm::GlobalValue *GV,
101 VisibilityAttr::VisibilityTypes Vis) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000102 // Internal definitions should always have default visibility.
103 if (GV->hasInternalLinkage()) {
104 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000105 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000106 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000107
Dan Gohman4f8d1232008-05-22 00:50:06 +0000108 switch (Vis) {
109 default: assert(0 && "Unknown visibility!");
110 case VisibilityAttr::DefaultVisibility:
111 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
112 break;
113 case VisibilityAttr::HiddenVisibility:
114 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
115 break;
116 case VisibilityAttr::ProtectedVisibility:
117 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
118 break;
119 }
120}
121
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000122static void setGlobalOptionVisibility(llvm::GlobalValue *GV,
123 LangOptions::VisibilityMode Vis) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000124 // Internal definitions should always have default visibility.
125 if (GV->hasInternalLinkage()) {
126 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000127 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000128 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000129
Fariborz Jahanian7cd2e932009-04-03 03:28:57 +0000130 switch (Vis) {
131 default: assert(0 && "Unknown visibility!");
132 case LangOptions::NonVisibility:
133 break;
134 case LangOptions::DefaultVisibility:
135 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
136 break;
137 case LangOptions::HiddenVisibility:
138 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
139 break;
140 case LangOptions::ProtectedVisibility:
141 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
142 break;
143 }
144}
145
146
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000147/// \brief Retrieves the mangled name for the given declaration.
148///
149/// If the given declaration requires a mangled name, returns an
Chris Lattnerc50689b2009-03-21 06:31:09 +0000150/// const char* containing the mangled name. Otherwise, returns
151/// the unmangled name.
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000152///
Douglas Gregor6ec36682009-02-18 23:53:56 +0000153const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerc50689b2009-03-21 06:31:09 +0000154 // In C, functions with no attributes never need to be mangled. Fastpath them.
155 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
156 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000157 return ND->getNameAsCString();
Chris Lattnerc50689b2009-03-21 06:31:09 +0000158 }
159
Douglas Gregor6ec36682009-02-18 23:53:56 +0000160 llvm::SmallString<256> Name;
161 llvm::raw_svector_ostream Out(Name);
Daniel Dunbarfe345572009-03-05 22:59:19 +0000162 if (!mangleName(ND, Context, Out)) {
163 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner3c8f1532009-03-21 07:12:05 +0000164 return ND->getNameAsCString();
Daniel Dunbarfe345572009-03-05 22:59:19 +0000165 }
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000166
Douglas Gregor6ec36682009-02-18 23:53:56 +0000167 Name += '\0';
Chris Lattner3c8f1532009-03-21 07:12:05 +0000168 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000169}
170
Chris Lattner6d397602008-03-14 17:18:18 +0000171/// AddGlobalCtor - Add a function to the list that will be called before
172/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000173void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000174 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000175 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000176}
177
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000178/// AddGlobalDtor - Add a function to the list that will be called
179/// when the module is unloaded.
180void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000181 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000182 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
183}
184
185void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
186 // Ctor function type is void()*.
187 llvm::FunctionType* CtorFTy =
188 llvm::FunctionType::get(llvm::Type::VoidTy,
189 std::vector<const llvm::Type*>(),
190 false);
191 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
192
193 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000194 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000195 llvm::StructType::get(llvm::Type::Int32Ty,
196 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000197
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000198 // Construct the constructor and destructor arrays.
199 std::vector<llvm::Constant*> Ctors;
200 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
201 std::vector<llvm::Constant*> S;
202 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
203 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
204 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000205 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000206
207 if (!Ctors.empty()) {
208 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
209 new llvm::GlobalVariable(AT, false,
210 llvm::GlobalValue::AppendingLinkage,
211 llvm::ConstantArray::get(AT, Ctors),
212 GlobalName,
213 &TheModule);
214 }
Chris Lattner6d397602008-03-14 17:18:18 +0000215}
216
Nate Begeman532485c2008-04-18 23:43:57 +0000217void CodeGenModule::EmitAnnotations() {
218 if (Annotations.empty())
219 return;
220
221 // Create a new global variable for the ConstantStruct in the Module.
222 llvm::Constant *Array =
223 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
224 Annotations.size()),
225 Annotations);
226 llvm::GlobalValue *gv =
227 new llvm::GlobalVariable(Array->getType(), false,
228 llvm::GlobalValue::AppendingLinkage, Array,
229 "llvm.global.annotations", &TheModule);
230 gv->setSection("llvm.metadata");
231}
232
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000233void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
234 bool IsInternal,
235 bool IsInline,
236 llvm::GlobalValue *GV,
237 bool ForDefinition) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000238 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000239 // approximation of what we really want.
Daniel Dunbar219df662008-09-08 23:44:31 +0000240 if (!ForDefinition) {
241 // Only a few attributes are set on declarations.
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000242 if (D->getAttr<DLLImportAttr>()) {
243 // The dllimport attribute is overridden by a subsequent declaration as
244 // dllexport.
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000245 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000246 // dllimport attribute can be applied only to function decls, not to
247 // definitions.
248 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
249 if (!FD->getBody())
250 GV->setLinkage(llvm::Function::DLLImportLinkage);
251 } else
252 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redl3ef5db62009-01-05 20:53:53 +0000253 }
Daniel Dunbar5e273142009-03-06 16:20:49 +0000254 } else if (D->getAttr<WeakAttr>() ||
255 D->getAttr<WeakImportAttr>()) {
256 // "extern_weak" is overloaded in LLVM; we probably should have
257 // separate linkage types for this.
Duncan Sandse3fedbe2009-03-11 08:40:02 +0000258 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000259 }
Daniel Dunbar219df662008-09-08 23:44:31 +0000260 } else {
261 if (IsInternal) {
262 GV->setLinkage(llvm::Function::InternalLinkage);
263 } else {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000264 if (D->getAttr<DLLExportAttr>()) {
265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // The dllexport attribute is ignored for undefined symbols.
267 if (FD->getBody())
268 GV->setLinkage(llvm::Function::DLLExportLinkage);
269 } else
270 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000271 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
272 IsInline)
Mike Stump286acbd2009-03-07 16:33:28 +0000273 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar219df662008-09-08 23:44:31 +0000274 }
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000275 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000276
Daniel Dunbar49988882009-01-13 02:25:00 +0000277 // FIXME: Figure out the relative priority of the attribute,
278 // -fvisibility, and private_extern.
Daniel Dunbar03abc9e2009-04-07 22:36:33 +0000279 if (ForDefinition) {
280 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
281 setGlobalVisibility(GV, attr->getVisibility());
282 else
283 setGlobalOptionVisibility(GV, getLangOptions().getVisibilityMode());
284 }
Daniel Dunbara735ad82008-08-06 00:03:29 +0000285
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000286 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
287 GV->setSection(SA->getName());
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000288
289 // Only add to llvm.used when we see a definition, otherwise we
290 // might add multiple times or risk the value being replaced by a
291 // subsequent RAUW.
292 if (ForDefinition) {
293 if (D->getAttr<UsedAttr>())
294 AddUsedGlobal(GV);
295 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000296}
297
Devang Patel761d7f72008-09-25 21:02:23 +0000298void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000299 const CGFunctionInfo &Info,
Daniel Dunbarb7688072008-09-10 00:41:16 +0000300 llvm::Function *F) {
Devang Patel761d7f72008-09-25 21:02:23 +0000301 AttributeListType AttributeList;
Daniel Dunbar88b53962009-02-02 22:03:45 +0000302 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000303
Devang Patel761d7f72008-09-25 21:02:23 +0000304 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
305 AttributeList.size()));
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000306
307 // Set the appropriate calling convention for the Function.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000308 if (D->getAttr<FastCallAttr>())
Anton Korobeynikovf1c9c092008-11-11 20:21:14 +0000309 F->setCallingConv(llvm::CallingConv::X86_FastCall);
310
311 if (D->getAttr<StdCallAttr>())
312 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000313}
314
315/// SetFunctionAttributesForDefinition - Set function attributes
316/// specific to a function definition.
Daniel Dunbar219df662008-09-08 23:44:31 +0000317void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
318 llvm::Function *F) {
319 if (isa<ObjCMethodDecl>(D)) {
320 SetGlobalValueAttributes(D, true, false, F, true);
321 } else {
322 const FunctionDecl *FD = cast<FunctionDecl>(D);
323 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
324 FD->isInline(), F, true);
325 }
326
Daniel Dunbar74ac74a2009-03-02 04:58:03 +0000327 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbarf93349f2008-09-27 07:16:42 +0000328 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000329
330 if (D->getAttr<AlwaysInlineAttr>())
331 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson81ebbde2009-02-19 19:22:11 +0000332
333 if (D->getAttr<NoinlineAttr>())
334 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000335}
336
337void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
338 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000339 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000340
Daniel Dunbar219df662008-09-08 23:44:31 +0000341 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000342}
343
344void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
345 llvm::Function *F) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000346 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +0000347
Daniel Dunbar219df662008-09-08 23:44:31 +0000348 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
349 FD->isInline(), F, false);
350}
351
Daniel Dunbar02698712009-02-13 20:29:50 +0000352void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
353 assert(!GV->isDeclaration() &&
354 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000355 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000356}
357
358void CodeGenModule::EmitLLVMUsed() {
359 // Don't create llvm.used if there is no need.
360 if (LLVMUsed.empty())
361 return;
362
Chris Lattner35f38a22009-03-31 22:37:52 +0000363 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
364 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, LLVMUsed.size());
365
366 // Convert LLVMUsed to what ConstantArray needs.
367 std::vector<llvm::Constant*> UsedArray;
368 UsedArray.resize(LLVMUsed.size());
369 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
370 UsedArray[i] =
371 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
372 }
373
Daniel Dunbar02698712009-02-13 20:29:50 +0000374 llvm::GlobalVariable *GV =
375 new llvm::GlobalVariable(ATy, false,
376 llvm::GlobalValue::AppendingLinkage,
Chris Lattner35f38a22009-03-31 22:37:52 +0000377 llvm::ConstantArray::get(ATy, UsedArray),
Daniel Dunbar02698712009-02-13 20:29:50 +0000378 "llvm.used", &getModule());
379
380 GV->setSection("llvm.metadata");
381}
382
383void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000384 // Emit code for any potentially referenced deferred decls. Since a
385 // previously unused static decl may become used during the generation of code
386 // for a static function, iterate until no changes are made.
387 while (!DeferredDeclsToEmit.empty()) {
388 const ValueDecl *D = DeferredDeclsToEmit.back();
389 DeferredDeclsToEmit.pop_back();
390
391 // The mangled name for the decl must have been emitted in GlobalDeclMap.
392 // Look it up to see if it was defined with a stronger definition (e.g. an
393 // extern inline function with a strong function redefinition). If so,
394 // just ignore the deferred decl.
395 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
396 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlssonb723f752009-01-04 02:08:04 +0000397
Chris Lattner67b00522009-03-21 09:44:56 +0000398 if (!CGRef->isDeclaration())
399 continue;
400
401 // Otherwise, emit the definition and move on to the next one.
402 EmitGlobalDefinition(D);
403 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000404}
405
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000406/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
407/// annotation information for a given GlobalValue. The annotation struct is
408/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000409/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000410/// created from the AnnotateAttr's annotation. The third field is a constant
411/// string containing the name of the translation unit. The fourth field is
412/// the line number in the file of the annotated value declaration.
413///
414/// FIXME: this does not unique the annotation string constants, as llvm-gcc
415/// appears to.
416///
417llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
418 const AnnotateAttr *AA,
419 unsigned LineNo) {
420 llvm::Module *M = &getModule();
421
422 // get [N x i8] constants for the annotation string, and the filename string
423 // which are the 2nd and 3rd elements of the global annotation structure.
424 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
425 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
426 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
427 true);
428
429 // Get the two global values corresponding to the ConstantArrays we just
430 // created to hold the bytes of the strings.
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000431 const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000432 llvm::GlobalValue *annoGV =
433 new llvm::GlobalVariable(anno->getType(), false,
434 llvm::GlobalValue::InternalLinkage, anno,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000435 GV->getName() + StringPrefix, M);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000436 // translation unit name string, emitted into the llvm.metadata section.
437 llvm::GlobalValue *unitGV =
438 new llvm::GlobalVariable(unit->getType(), false,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +0000439 llvm::GlobalValue::InternalLinkage, unit,
440 StringPrefix, M);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000441
442 // Create the ConstantStruct that is the global annotion.
443 llvm::Constant *Fields[4] = {
444 llvm::ConstantExpr::getBitCast(GV, SBP),
445 llvm::ConstantExpr::getBitCast(annoGV, SBP),
446 llvm::ConstantExpr::getBitCast(unitGV, SBP),
447 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
448 };
449 return llvm::ConstantStruct::get(Fields, 4, false);
450}
451
Daniel Dunbar73241df2009-02-13 21:18:01 +0000452bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000453 // Never defer when EmitAllDecls is specified or the decl has
454 // attribute used.
455 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000456 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000457
458 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000459 // Constructors and destructors should never be deferred.
460 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
461 return false;
462
Chris Lattner99b53612009-03-21 08:03:33 +0000463 // FIXME: What about inline, and/or extern inline?
Daniel Dunbar73241df2009-02-13 21:18:01 +0000464 if (FD->getStorageClass() != FunctionDecl::Static)
465 return false;
466 } else {
467 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner99b53612009-03-21 08:03:33 +0000468 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbar73241df2009-02-13 21:18:01 +0000469
470 if (VD->getStorageClass() != VarDecl::Static)
471 return false;
472 }
473
474 return true;
475}
476
477void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattnerbd532712009-03-22 21:47:11 +0000478 // If this is an alias definition (which otherwise looks like a declaration)
479 // emit it now.
480 if (Global->getAttr<AliasAttr>())
481 return EmitAliasDefinition(Global);
Daniel Dunbar219df662008-09-08 23:44:31 +0000482
Chris Lattner67b00522009-03-21 09:44:56 +0000483 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000484 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000485 // Forward declarations are emitted lazily on first use.
486 if (!FD->isThisDeclarationADefinition())
487 return;
Daniel Dunbar02698712009-02-13 20:29:50 +0000488 } else {
489 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000490 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
491
Daniel Dunbar73241df2009-02-13 21:18:01 +0000492 // Forward declarations are emitted lazily on first use.
Daniel Dunbar7542bca2009-02-13 22:49:13 +0000493 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbar73241df2009-02-13 21:18:01 +0000494 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000495 }
496
Chris Lattner67b00522009-03-21 09:44:56 +0000497 // Defer code generation when possible if this is a static definition, inline
498 // function etc. These we only want to emit if they are used.
Daniel Dunbar73241df2009-02-13 21:18:01 +0000499 if (MayDeferGeneration(Global)) {
Chris Lattner67b00522009-03-21 09:44:56 +0000500 // If the value has already been used, add it directly to the
501 // DeferredDeclsToEmit list.
502 const char *MangledName = getMangledName(Global);
503 if (GlobalDeclMap.count(MangledName))
504 DeferredDeclsToEmit.push_back(Global);
505 else {
506 // Otherwise, remember that we saw a deferred decl with this name. The
507 // first use of the mangled name will cause it to move into
508 // DeferredDeclsToEmit.
509 DeferredDecls[MangledName] = Global;
510 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000511 return;
512 }
513
514 // Otherwise emit the definition.
515 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000516}
517
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000518void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
520 EmitGlobalFunctionDefinition(FD);
521 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
522 EmitGlobalVarDefinition(VD);
523 } else {
524 assert(0 && "Invalid argument to EmitGlobalDefinition()");
525 }
526}
527
Chris Lattner74391b42009-03-22 21:03:39 +0000528/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
529/// module, create and return an llvm Function with the specified type. If there
530/// is something in the module with the specified name, return it potentially
531/// bitcasted to the right type.
532///
533/// If D is non-null, it specifies a decl that correspond to this. This is used
534/// to set the attributes on the function when it is first created.
535llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
536 const llvm::Type *Ty,
537 const FunctionDecl *D) {
Chris Lattner0558e792009-03-21 09:25:43 +0000538 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0558e792009-03-21 09:25:43 +0000539 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
540 if (Entry) {
541 if (Entry->getType()->getElementType() == Ty)
542 return Entry;
543
544 // Make sure the result is of the correct type.
545 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
546 return llvm::ConstantExpr::getBitCast(Entry, PTy);
547 }
548
Chris Lattner67b00522009-03-21 09:44:56 +0000549 // This is the first use or definition of a mangled name. If there is a
550 // deferred decl with this name, remember that we need to emit it at the end
551 // of the file.
552 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattner74391b42009-03-22 21:03:39 +0000553 DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +0000554 if (DDI != DeferredDecls.end()) {
555 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
556 // list, and remove it from DeferredDecls (since we don't need it anymore).
557 DeferredDeclsToEmit.push_back(DDI->second);
558 DeferredDecls.erase(DDI);
559 }
560
Chris Lattner0558e792009-03-21 09:25:43 +0000561 // This function doesn't have a complete type (for example, the return
562 // type is an incomplete struct). Use a fake type instead, and make
563 // sure not to try to set attributes.
564 bool ShouldSetAttributes = true;
565 if (!isa<llvm::FunctionType>(Ty)) {
566 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
567 std::vector<const llvm::Type*>(), false);
568 ShouldSetAttributes = false;
569 }
570 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
571 llvm::Function::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000572 "", &getModule());
573 F->setName(MangledName);
Chris Lattner74391b42009-03-22 21:03:39 +0000574 if (D && ShouldSetAttributes)
Chris Lattner0558e792009-03-21 09:25:43 +0000575 SetFunctionAttributes(D, F);
576 Entry = F;
577 return F;
578}
579
Chris Lattner74391b42009-03-22 21:03:39 +0000580/// GetAddrOfFunction - Return the address of the given function. If Ty is
581/// non-null, then this function will use the specified type if it has to
582/// create it (this occurs when we see a definition of the function).
583llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
584 const llvm::Type *Ty) {
585 // If there was no specific requested type, just convert it now.
586 if (!Ty)
587 Ty = getTypes().ConvertType(D->getType());
588 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
589}
Eli Friedman77ba7082008-05-30 19:50:47 +0000590
Chris Lattner74391b42009-03-22 21:03:39 +0000591/// CreateRuntimeFunction - Create a new runtime function with the specified
592/// type and name.
593llvm::Constant *
594CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
595 const char *Name) {
596 // Convert Name to be a uniqued string from the IdentifierInfo table.
597 Name = getContext().Idents.get(Name).getName();
598 return GetOrCreateLLVMFunction(Name, FTy, 0);
599}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000600
Chris Lattner74391b42009-03-22 21:03:39 +0000601/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
602/// create and return an llvm GlobalVariable with the specified type. If there
603/// is something in the module with the specified name, return it potentially
604/// bitcasted to the right type.
605///
606/// If D is non-null, it specifies a decl that correspond to this. This is used
607/// to set the attributes on the global when it is first created.
608llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
609 const llvm::PointerType*Ty,
610 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000611 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5d4f5c72009-03-21 08:06:59 +0000612 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner99b53612009-03-21 08:03:33 +0000613 if (Entry) {
Chris Lattner74391b42009-03-22 21:03:39 +0000614 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +0000615 return Entry;
616
Chris Lattner99b53612009-03-21 08:03:33 +0000617 // Make sure the result is of the correct type.
Chris Lattner74391b42009-03-22 21:03:39 +0000618 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +0000619 }
Chris Lattner67b00522009-03-21 09:44:56 +0000620
Chris Lattnerb75863d2009-04-10 00:35:59 +0000621 // We don't support __thread yet.
622 if (D && D->isThreadSpecified())
623 ErrorUnsupported(D, "thread local ('__thread') variable", true);
624
Chris Lattner67b00522009-03-21 09:44:56 +0000625 // This is the first use or definition of a mangled name. If there is a
626 // deferred decl with this name, remember that we need to emit it at the end
627 // of the file.
628 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
629 DeferredDecls.find(MangledName);
630 if (DDI != DeferredDecls.end()) {
631 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
632 // list, and remove it from DeferredDecls (since we don't need it anymore).
633 DeferredDeclsToEmit.push_back(DDI->second);
634 DeferredDecls.erase(DDI);
635 }
636
Chris Lattner99b53612009-03-21 08:03:33 +0000637 llvm::GlobalVariable *GV =
Chris Lattner74391b42009-03-22 21:03:39 +0000638 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +0000639 llvm::GlobalValue::ExternalLinkage,
Chris Lattnerd9726782009-03-22 00:12:30 +0000640 0, "", &getModule(),
Chris Lattner74391b42009-03-22 21:03:39 +0000641 0, Ty->getAddressSpace());
Chris Lattnerd9726782009-03-22 00:12:30 +0000642 GV->setName(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +0000643
644 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +0000645 if (D) {
646 // FIXME: This code is overly simple and should be merged with
647 // other global handling.
648 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner99b53612009-03-21 08:03:33 +0000649
Chris Lattner74391b42009-03-22 21:03:39 +0000650 // FIXME: Merge with other attribute handling code.
651 if (D->getStorageClass() == VarDecl::PrivateExtern)
652 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner99b53612009-03-21 08:03:33 +0000653
Chris Lattner74391b42009-03-22 21:03:39 +0000654 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
655 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
656 }
657
Chris Lattner99b53612009-03-21 08:03:33 +0000658 return Entry = GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000659}
660
Chris Lattner74391b42009-03-22 21:03:39 +0000661
662/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
663/// given global variable. If Ty is non-null and if the global doesn't exist,
664/// then it will be greated with the specified type instead of whatever the
665/// normal requested type would be.
666llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
667 const llvm::Type *Ty) {
668 assert(D->hasGlobalStorage() && "Not a global variable");
669 QualType ASTTy = D->getType();
670 if (Ty == 0)
671 Ty = getTypes().ConvertTypeForMem(ASTTy);
672
673 const llvm::PointerType *PTy =
674 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
675 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
676}
677
678/// CreateRuntimeVariable - Create a new runtime global variable with the
679/// specified type and name.
680llvm::Constant *
681CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
682 const char *Name) {
683 // Convert Name to be a uniqued string from the IdentifierInfo table.
684 Name = getContext().Idents.get(Name).getName();
685 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
686}
687
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000688void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000689 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000690 QualType ASTTy = D->getType();
Chris Lattnerb75863d2009-04-10 00:35:59 +0000691
Chris Lattner8f32f712007-07-14 00:23:28 +0000692 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000693 // This is a tentative definition; tentative definitions are
694 // implicitly initialized with { 0 }
Chris Lattner570585c2009-03-21 09:16:30 +0000695 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000696 if (ASTTy->isIncompleteArrayType()) {
697 // An incomplete array is normally [ TYPE x 0 ], but we need
698 // to fix it to [ TYPE x 1 ].
Chris Lattner570585c2009-03-21 09:16:30 +0000699 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000700 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000701 }
702 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000703 } else {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000704 Init = EmitConstantExpr(D->getInit(), D->getType());
Eli Friedman6e656f42009-02-20 01:18:21 +0000705 if (!Init) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000706 ErrorUnsupported(D, "static initializer");
Eli Friedman6e656f42009-02-20 01:18:21 +0000707 QualType T = D->getInit()->getType();
708 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
709 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000710 }
Eli Friedman77ba7082008-05-30 19:50:47 +0000711
Chris Lattner2d584062009-03-21 08:13:05 +0000712 const llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +0000713 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000714
Chris Lattner570585c2009-03-21 09:16:30 +0000715 // Strip off a bitcast if we got one back.
716 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
717 assert(CE->getOpcode() == llvm::Instruction::BitCast);
718 Entry = CE->getOperand(0);
719 }
720
721 // Entry is now either a Function or GlobalVariable.
722 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
723
724 // If we already have this global and it has an initializer, then
725 // we are in the rare situation where we emitted the defining
726 // declaration of the global and are now being asked to emit a
727 // definition which would be common. This occurs, for example, in
728 // the following situation because statics can be emitted out of
729 // order:
730 //
731 // static int x;
732 // static int *y = &x;
733 // static int x = 10;
734 // int **z = &y;
735 //
736 // Bail here so we don't blow away the definition. Note that if we
737 // can't distinguish here if we emitted a definition with a null
738 // initializer, but this case is safe.
739 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar232350d2009-02-19 05:36:41 +0000740 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
741 return;
Chris Lattner570585c2009-03-21 09:16:30 +0000742 }
743
744 // We have a definition after a declaration with the wrong type.
745 // We must make a new GlobalVariable* and update everything that used OldGV
746 // (a declaration or tentative definition) with the new GlobalVariable*
747 // (which will be a definition).
748 //
749 // This happens if there is a prototype for a global (e.g.
750 // "extern int x[];") and then a definition of a different type (e.g.
751 // "int x[10];"). This also happens when an initializer has a different type
752 // from the type of the global (this happens with unions).
753 //
754 // FIXME: This also ends up happening if there's a definition followed by
755 // a tentative definition! (Although Sema rejects that construct
756 // at the moment.)
757 if (GV == 0 ||
758 GV->getType()->getElementType() != InitType ||
759 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
760
761 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
762 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar232350d2009-02-19 05:36:41 +0000763
Chris Lattner570585c2009-03-21 09:16:30 +0000764 // Make a new global with the correct type, this is now guaranteed to work.
765 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +0000766 GV->takeName(cast<llvm::GlobalValue>(Entry));
767
Eli Friedman77ba7082008-05-30 19:50:47 +0000768 // Replace all uses of the old global with the new global
769 llvm::Constant *NewPtrForOldDecl =
Chris Lattner570585c2009-03-21 09:16:30 +0000770 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
771 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000772
773 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +0000774 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000775 }
Devang Patel8e53e722007-10-26 16:31:40 +0000776
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000777 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
778 SourceManager &SM = Context.getSourceManager();
779 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000780 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000781 }
782
Chris Lattner88a69ad2007-07-13 05:13:43 +0000783 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000784 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman0de40af2009-02-27 04:11:37 +0000785 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedman08d78022008-05-29 11:10:27 +0000786
Chris Lattner88a69ad2007-07-13 05:13:43 +0000787 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000788 if (D->getStorageClass() == VarDecl::Static)
789 GV->setLinkage(llvm::Function::InternalLinkage);
790 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000791 GV->setLinkage(llvm::Function::DLLImportLinkage);
792 else if (D->getAttr<DLLExportAttr>())
793 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar5e273142009-03-06 16:20:49 +0000794 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump286acbd2009-03-07 16:33:28 +0000795 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000796 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000797 // FIXME: This isn't right. This should handle common linkage and other
798 // stuff.
799 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000800 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000801 case VarDecl::Auto:
802 case VarDecl::Register:
803 assert(0 && "Can't have auto or register globals");
804 case VarDecl::None:
Chris Lattnerbd360642009-03-26 05:00:52 +0000805 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sandsceb77d92009-03-11 20:15:27 +0000806 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson98883e12008-12-03 05:51:23 +0000807 else
808 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000809 break;
810 case VarDecl::Extern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000811 // FIXME: common
812 break;
813
Chris Lattnerddee4232008-03-03 03:28:21 +0000814 case VarDecl::PrivateExtern:
Daniel Dunbar49988882009-01-13 02:25:00 +0000815 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
816 // FIXME: common
Chris Lattnerddee4232008-03-03 03:28:21 +0000817 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000818 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000819 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000820
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000821 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
822 setGlobalVisibility(GV, attr->getVisibility());
823 else
824 setGlobalOptionVisibility(GV, getLangOptions().getVisibilityMode());
825
Daniel Dunbar17f194f2009-02-12 17:28:23 +0000826 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
827 GV->setSection(SA->getName());
828
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000829 if (D->getAttr<UsedAttr>())
830 AddUsedGlobal(GV);
831
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000832 // Emit global variable debug information.
Chris Lattner2d584062009-03-21 08:13:05 +0000833 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000834 DI->setLocation(D->getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000835 DI->EmitGlobalVariable(GV, D);
836 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000837}
Reid Spencer5f016e22007-07-11 17:01:13 +0000838
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000839
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000840void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000841 const llvm::FunctionType *Ty;
Daniel Dunbard5d31802009-02-19 07:15:39 +0000842
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000843 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
844 bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
845
846 Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
847 } else {
848 Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
849
850 // As a special case, make sure that definitions of K&R function
851 // "type foo()" aren't declared as varargs (which forces the backend
852 // to do unnecessary work).
853 if (D->getType()->isFunctionNoProtoType()) {
854 assert(Ty->isVarArg() && "Didn't lower type as expected");
855 // Due to stret, the lowered function could have arguments.
856 // Just create the same type as was lowered by ConvertType
857 // but strip off the varargs bit.
858 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
859 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
860 }
Chris Lattnerff75e1d2009-03-22 19:35:37 +0000861 }
Daniel Dunbard5d31802009-02-19 07:15:39 +0000862
Chris Lattner34809502009-03-21 08:53:37 +0000863 // Get or create the prototype for teh function.
Chris Lattner0558e792009-03-21 09:25:43 +0000864 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattner34809502009-03-21 08:53:37 +0000865
Chris Lattner0558e792009-03-21 09:25:43 +0000866 // Strip off a bitcast if we got one back.
867 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
868 assert(CE->getOpcode() == llvm::Instruction::BitCast);
869 Entry = CE->getOperand(0);
870 }
871
872
873 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbar42745812009-03-09 23:53:08 +0000874 // If the types mismatch then we have to rewrite the definition.
Chris Lattner0558e792009-03-21 09:25:43 +0000875 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
876 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +0000877
Chris Lattner62b33ea2009-03-21 08:38:50 +0000878 // F is the Function* for the one with the wrong type, we must make a new
879 // Function* and update everything that used F (a declaration) with the new
880 // Function* (which will be a definition).
881 //
882 // This happens if there is a prototype for a function
883 // (e.g. "int f()") and then a definition of a different type
884 // (e.g. "int f(int x)"). Start by making a new function of the
885 // correct type, RAUW, then steal the name.
Chris Lattner34809502009-03-21 08:53:37 +0000886 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner0558e792009-03-21 09:25:43 +0000887 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
888 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattner62b33ea2009-03-21 08:38:50 +0000889
890 // Replace uses of F with the Function we will endow with a body.
891 llvm::Constant *NewPtrForOldDecl =
Chris Lattner0558e792009-03-21 09:25:43 +0000892 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
893 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattner62b33ea2009-03-21 08:38:50 +0000894
895 // Ok, delete the old function now, which is dead.
Chris Lattner0558e792009-03-21 09:25:43 +0000896 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner62b33ea2009-03-21 08:38:50 +0000897
Chris Lattner0558e792009-03-21 09:25:43 +0000898 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000899 }
Chris Lattner0558e792009-03-21 09:25:43 +0000900
901 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000902
Daniel Dunbar219df662008-09-08 23:44:31 +0000903 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000904
Daniel Dunbar219df662008-09-08 23:44:31 +0000905 SetFunctionAttributesForDefinition(D, Fn);
906
Chris Lattner34809502009-03-21 08:53:37 +0000907 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000908 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattner34809502009-03-21 08:53:37 +0000909 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +0000910 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000911}
912
Chris Lattnerbd532712009-03-22 21:47:11 +0000913void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
914 const AliasAttr *AA = D->getAttr<AliasAttr>();
915 assert(AA && "Not an alias?");
916
917 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
918
919 // Unique the name through the identifier table.
920 const char *AliaseeName = AA->getAliasee().c_str();
921 AliaseeName = getContext().Idents.get(AliaseeName).getName();
922
923 // Create a reference to the named value. This ensures that it is emitted
924 // if a deferred decl.
925 llvm::Constant *Aliasee;
926 if (isa<llvm::FunctionType>(DeclTy))
927 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
928 else
929 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
930 llvm::PointerType::getUnqual(DeclTy), 0);
931
932 // Create the new alias itself, but don't set a name yet.
933 llvm::GlobalValue *GA =
934 new llvm::GlobalAlias(Aliasee->getType(),
935 llvm::Function::ExternalLinkage,
936 "", Aliasee, &getModule());
937
938 // See if there is already something with the alias' name in the module.
939 const char *MangledName = getMangledName(D);
940 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
941
942 if (Entry && !Entry->isDeclaration()) {
943 // If there is a definition in the module, then it wins over the alias.
944 // This is dubious, but allow it to be safe. Just ignore the alias.
945 GA->eraseFromParent();
946 return;
947 }
948
949 if (Entry) {
950 // If there is a declaration in the module, then we had an extern followed
951 // by the alias, as in:
952 // extern int test6();
953 // ...
954 // int test6() __attribute__((alias("test7")));
955 //
956 // Remove it and replace uses of it with the alias.
957
958 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
959 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +0000960 Entry->eraseFromParent();
961 }
962
963 // Now we know that there is no conflict, set the name.
964 Entry = GA;
965 GA->setName(MangledName);
966
967 // Alias should never be internal or inline.
968 SetGlobalValueAttributes(D, false, false, GA, true);
969}
970
Chris Lattnerb808c952009-03-22 21:56:56 +0000971/// getBuiltinLibFunction - Given a builtin id for a function like
972/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stumpc136e6c2009-02-27 22:42:30 +0000973llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor3e41d602009-02-13 23:20:09 +0000974 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
975 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
976 "isn't a lib fn");
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000977
Douglas Gregor3e41d602009-02-13 23:20:09 +0000978 // Get the name, skip over the __builtin_ prefix (if necessary).
979 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
980 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
981 Name += 10;
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000982
983 // Get the type for the builtin.
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000984 Builtin::Context::GetBuiltinTypeError Error;
985 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
986 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
987
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000988 const llvm::FunctionType *Ty =
989 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
990
Chris Lattnerb808c952009-03-22 21:56:56 +0000991 // Unique the name through the identifier table.
992 Name = getContext().Idents.get(Name).getName();
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000993 // FIXME: param attributes for sext/zext etc.
Chris Lattnerb808c952009-03-22 21:56:56 +0000994 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000995}
996
Chris Lattner7acda7c2007-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 Lattnerbef20ac2007-08-31 04:31:45 +00001002
Reid Spencer5f016e22007-07-11 17:01:13 +00001003llvm::Function *CodeGenModule::getMemCpyFn() {
1004 if (MemCpyFn) return MemCpyFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001005 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1006 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001007}
Anders Carlssonc9e20912007-08-21 00:21:21 +00001008
Eli Friedman0c995092008-05-26 12:59:39 +00001009llvm::Function *CodeGenModule::getMemMoveFn() {
1010 if (MemMoveFn) return MemMoveFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001011 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1012 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman0c995092008-05-26 12:59:39 +00001013}
1014
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001015llvm::Function *CodeGenModule::getMemSetFn() {
1016 if (MemSetFn) return MemSetFn;
Chris Lattner4e8a9e82008-11-21 16:43:15 +00001017 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1018 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +00001019}
Chris Lattner7acda7c2007-12-18 00:25:38 +00001020
Anders Carlssone3daa762008-11-15 18:54:24 +00001021static void appendFieldAndPadding(CodeGenModule &CGM,
1022 std::vector<llvm::Constant*>& Fields,
Douglas Gregor44b43212008-12-11 16:49:14 +00001023 FieldDecl *FieldD, FieldDecl *NextFieldD,
1024 llvm::Constant* Field,
Chris Lattner3c8f1532009-03-21 07:12:05 +00001025 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001026 // Append the field.
1027 Fields.push_back(Field);
1028
Douglas Gregor44b43212008-12-11 16:49:14 +00001029 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlssone3daa762008-11-15 18:54:24 +00001030
1031 int NextStructFieldNo;
Douglas Gregor44b43212008-12-11 16:49:14 +00001032 if (!NextFieldD) {
Anders Carlssone3daa762008-11-15 18:54:24 +00001033 NextStructFieldNo = STy->getNumElements();
1034 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +00001035 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlssone3daa762008-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
Chris Lattnerbef20ac2007-08-31 04:31:45 +00001047llvm::Constant *CodeGenModule::
Steve Naroff8d4141f2009-04-01 13:55:36 +00001048GetAddrOfConstantCFString(const StringLiteral *Literal) {
Steve Naroffb59212a2009-04-01 21:16:31 +00001049 std::string str;
1050 unsigned StringLength;
1051
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001052 bool isUTF16 = false;
1053 if (Literal->containsNonAsciiOrNull()) {
1054 // Convert from UTF-8 to UTF-16.
1055 llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1056 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1057 UTF16 *ToPtr = &ToBuf[0];
1058
1059 ConversionResult Result;
1060 Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1061 &ToPtr, ToPtr+Literal->getByteLength(),
1062 strictConversion);
Steve Naroffaa4a7562009-04-13 19:08:08 +00001063 if (Result == conversionOK) {
1064 // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1065 // without doing more surgery to this routine. Since we aren't explicitly
1066 // checking for endianness here, it's also a bug (when generating code for
1067 // a target that doesn't match the host endianness). Modeling this as an
1068 // i16 array is likely the cleanest solution.
1069 StringLength = ToPtr-&ToBuf[0];
1070 str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1071 isUTF16 = true;
1072 } else if (Result == sourceIllegal) {
Steve Narofffd942622009-04-13 20:26:29 +00001073 // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
Steve Naroffaa4a7562009-04-13 19:08:08 +00001074 str.assign(Literal->getStrData(), Literal->getByteLength());
1075 StringLength = str.length();
1076 } else
1077 assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
Steve Naroffb59212a2009-04-01 21:16:31 +00001078
Steve Naroffb59212a2009-04-01 21:16:31 +00001079 } else {
1080 str.assign(Literal->getStrData(), Literal->getByteLength());
1081 StringLength = str.length();
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001082 }
Anders Carlssonc9e20912007-08-21 00:21:21 +00001083 llvm::StringMapEntry<llvm::Constant *> &Entry =
1084 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1085
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001086 if (llvm::Constant *C = Entry.getValue())
1087 return C;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001088
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001089 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1090 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +00001091
1092 if (!CFConstantStringClassRef) {
1093 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1094 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001095
1096 // FIXME: This is fairly broken if
1097 // __CFConstantStringClassReference is already defined, in that it
1098 // will get renamed and the user will most likely see an opaque
1099 // error message. This is a general issue with relying on
1100 // particular names.
1101 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +00001102 new llvm::GlobalVariable(Ty, false,
1103 llvm::GlobalVariable::ExternalLinkage, 0,
1104 "__CFConstantStringClassReference",
1105 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001106
1107 // Decay array -> ptr
1108 CFConstantStringClassRef =
1109 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001110 }
1111
Anders Carlssone3daa762008-11-15 18:54:24 +00001112 QualType CFTy = getContext().getCFConstantStringType();
1113 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001114
Anders Carlssone3daa762008-11-15 18:54:24 +00001115 const llvm::StructType *STy =
1116 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1117
1118 std::vector<llvm::Constant*> Fields;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001119 RecordDecl::field_iterator Field = CFRD->field_begin(getContext());
Douglas Gregor44b43212008-12-11 16:49:14 +00001120
Anders Carlssonc9e20912007-08-21 00:21:21 +00001121 // Class pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001122 FieldDecl *CurField = *Field++;
1123 FieldDecl *NextField = *Field++;
1124 appendFieldAndPadding(*this, Fields, CurField, NextField,
1125 CFConstantStringClassRef, CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001126
1127 // Flags.
Douglas Gregor44b43212008-12-11 16:49:14 +00001128 CurField = NextField;
1129 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001130 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001131 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroffe9b7d8a2009-04-01 15:50:34 +00001132 isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1133 : llvm::ConstantInt::get(Ty, 0x07C8),
1134 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001135
1136 // String pointer.
Douglas Gregor44b43212008-12-11 16:49:14 +00001137 CurField = NextField;
1138 NextField = *Field++;
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001139 llvm::Constant *C = llvm::ConstantArray::get(str);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001140
1141 const char *Sect, *Prefix;
1142 bool isConstant;
1143 if (isUTF16) {
1144 Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1145 Sect = getContext().Target.getUnicodeStringSection();
1146 // FIXME: Why does GCC not set constant here?
1147 isConstant = false;
1148 } else {
1149 Prefix = getContext().Target.getStringSymbolPrefix(true);
1150 Sect = getContext().Target.getCFStringDataSection();
1151 // FIXME: -fwritable-strings should probably affect this, but we
1152 // are following gcc here.
1153 isConstant = true;
1154 }
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001155 llvm::GlobalVariable *GV =
Daniel Dunbara9668e02009-04-03 00:57:44 +00001156 new llvm::GlobalVariable(C->getType(), isConstant,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001157 llvm::GlobalValue::InternalLinkage,
Daniel Dunbara9668e02009-04-03 00:57:44 +00001158 C, Prefix, &getModule());
1159 if (Sect)
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001160 GV->setSection(Sect);
Daniel Dunbara9668e02009-04-03 00:57:44 +00001161 if (isUTF16) {
1162 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1163 GV->setAlignment(Align);
1164 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001165 appendFieldAndPadding(*this, Fields, CurField, NextField,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001166 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
Anders Carlssone3daa762008-11-15 18:54:24 +00001167 CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001168
1169 // String length.
Douglas Gregor44b43212008-12-11 16:49:14 +00001170 CurField = NextField;
1171 NextField = 0;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001172 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor44b43212008-12-11 16:49:14 +00001173 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroffb59212a2009-04-01 21:16:31 +00001174 llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
Anders Carlssonc9e20912007-08-21 00:21:21 +00001175
1176 // The struct.
Anders Carlssone3daa762008-11-15 18:54:24 +00001177 C = llvm::ConstantStruct::get(STy, Fields);
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001178 GV = new llvm::GlobalVariable(C->getType(), true,
1179 llvm::GlobalVariable::InternalLinkage, C,
1180 getContext().Target.getCFStringSymbolPrefix(),
1181 &getModule());
1182 if (const char *Sect = getContext().Target.getCFStringSection())
1183 GV->setSection(Sect);
Anders Carlsson0c678292007-11-01 00:41:52 +00001184 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00001185
Anders Carlsson0c678292007-11-01 00:41:52 +00001186 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00001187}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001188
Daniel Dunbar61432932008-08-13 23:20:05 +00001189/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +00001190/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +00001191std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar1e049762008-08-10 20:25:57 +00001192 const char *StrData = E->getStrData();
1193 unsigned Len = E->getByteLength();
1194
1195 const ConstantArrayType *CAT =
1196 getContext().getAsConstantArrayType(E->getType());
1197 assert(CAT && "String isn't pointer or array!");
1198
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001199 // Resize the string to the right size.
Daniel Dunbar1e049762008-08-10 20:25:57 +00001200 std::string Str(StrData, StrData+Len);
1201 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +00001202
1203 if (E->isWide())
1204 RealLen *= getContext().Target.getWCharWidth()/8;
1205
Daniel Dunbar1e049762008-08-10 20:25:57 +00001206 Str.resize(RealLen, '\0');
1207
1208 return Str;
1209}
1210
Daniel Dunbar61432932008-08-13 23:20:05 +00001211/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1212/// constant array for the given string literal.
1213llvm::Constant *
1214CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1215 // FIXME: This can be more efficient.
1216 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1217}
1218
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001219/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1220/// array for the given ObjCEncodeExpr node.
1221llvm::Constant *
1222CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1223 std::string Str;
1224 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00001225
1226 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001227}
1228
1229
Chris Lattnera7ad98f2008-02-11 00:02:17 +00001230/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001231static llvm::Constant *GenerateStringLiteral(const std::string &str,
1232 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001233 CodeGenModule &CGM,
1234 const char *GlobalName) {
Daniel Dunbar61432932008-08-13 23:20:05 +00001235 // Create Constant for this string literal. Don't add a '\0'.
1236 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001237
1238 // Create a global variable for this string
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001239 return new llvm::GlobalVariable(C->getType(), constant,
1240 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001241 C, GlobalName, &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001242}
1243
Daniel Dunbar61432932008-08-13 23:20:05 +00001244/// GetAddrOfConstantString - Returns a pointer to a character array
1245/// containing the literal. This contents are exactly that of the
1246/// given string, i.e. it will not be null terminated automatically;
1247/// see GetAddrOfConstantCString. Note that whether the result is
1248/// actually a pointer to an LLVM constant depends on
1249/// Feature.WriteableStrings.
1250///
1251/// The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001252llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1253 const char *GlobalName) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00001254 bool IsConstant = !Features.WritableStrings;
1255
1256 // Get the default prefix if a name wasn't specified.
1257 if (!GlobalName)
1258 GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1259
1260 // Don't share any string literals if strings aren't constant.
1261 if (!IsConstant)
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001262 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001263
1264 llvm::StringMapEntry<llvm::Constant *> &Entry =
1265 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1266
1267 if (Entry.getValue())
Chris Lattnereaf2bb82009-02-24 22:18:39 +00001268 return Entry.getValue();
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001269
1270 // Create a global variable for this.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001271 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00001272 Entry.setValue(C);
1273 return C;
1274}
Daniel Dunbar61432932008-08-13 23:20:05 +00001275
1276/// GetAddrOfConstantCString - Returns a pointer to a character
1277/// array containing the literal and a terminating '\-'
1278/// character. The result has pointer to array type.
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00001279llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1280 const char *GlobalName){
Chris Lattnerc9f29c62008-12-09 19:10:54 +00001281 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar61432932008-08-13 23:20:05 +00001282}
Daniel Dunbar41071de2008-08-15 23:26:23 +00001283
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001284/// EmitObjCPropertyImplementations - Emit information for synthesized
1285/// properties for an implementation.
1286void CodeGenModule::EmitObjCPropertyImplementations(const
1287 ObjCImplementationDecl *D) {
1288 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1289 e = D->propimpl_end(); i != e; ++i) {
1290 ObjCPropertyImplDecl *PID = *i;
1291
1292 // Dynamic is just for type-checking.
1293 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1294 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1295
1296 // Determine which methods need to be implemented, some may have
1297 // been overridden. Note that ::isSynthesized is not the method
1298 // we want, that just indicates if the decl came from a
1299 // property. What we want to know is if the method is defined in
1300 // this implementation.
1301 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001302 CodeGenFunction(*this).GenerateObjCGetter(
1303 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001304 if (!PD->isReadOnly() &&
1305 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001306 CodeGenFunction(*this).GenerateObjCSetter(
1307 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001308 }
1309 }
1310}
1311
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001312/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00001313void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001314 for (RecordDecl::decl_iterator I = ND->decls_begin(getContext()),
1315 E = ND->decls_end(getContext());
Anders Carlsson984e0682009-04-01 00:58:25 +00001316 I != E; ++I)
1317 EmitTopLevelDecl(*I);
1318}
1319
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001320// EmitLinkageSpec - Emit all declarations in a linkage spec.
1321void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1322 if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1323 ErrorUnsupported(LSD, "linkage spec");
1324 return;
1325 }
1326
Douglas Gregor6ab35242009-04-09 21:40:53 +00001327 for (RecordDecl::decl_iterator I = LSD->decls_begin(getContext()),
1328 E = LSD->decls_end(getContext());
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001329 I != E; ++I)
1330 EmitTopLevelDecl(*I);
1331}
1332
Daniel Dunbar41071de2008-08-15 23:26:23 +00001333/// EmitTopLevelDecl - Emit code for a single top level declaration.
1334void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1335 // If an error has occurred, stop code generation, but continue
1336 // parsing and semantic analysis (to ensure all warnings and errors
1337 // are emitted).
1338 if (Diags.hasErrorOccurred())
1339 return;
1340
1341 switch (D->getKind()) {
Anders Carlsson2b77ba82009-04-04 20:47:02 +00001342 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001343 case Decl::Function:
1344 case Decl::Var:
1345 EmitGlobal(cast<ValueDecl>(D));
1346 break;
1347
1348 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00001349 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001350 break;
1351
1352 // Objective-C Decls
1353
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00001354 // Forward declarations, no (immediate) code generation.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001355 case Decl::ObjCClass:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001356 case Decl::ObjCForwardProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001357 case Decl::ObjCCategory:
Daniel Dunbar41071de2008-08-15 23:26:23 +00001358 break;
Chris Lattner285d0db2009-04-01 02:36:43 +00001359 case Decl::ObjCInterface:
1360 // If we already laid out this interface due to an @class, and if we
1361 // codegen'd a reference it, update the 'opaque' type to be a real type now.
1362 Types.UpdateCompletedType(cast<ObjCInterfaceDecl>(D));
1363 break;
1364
Daniel Dunbar41071de2008-08-15 23:26:23 +00001365 case Decl::ObjCProtocol:
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00001366 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001367 break;
1368
1369 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001370 // Categories have properties but don't support synthesize so we
1371 // can ignore them here.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001372 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1373 break;
1374
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001375 case Decl::ObjCImplementation: {
1376 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1377 EmitObjCPropertyImplementations(OMD);
1378 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +00001379 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001380 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001381 case Decl::ObjCMethod: {
1382 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1383 // If this is not a prototype, emit the body.
1384 if (OMD->getBody())
1385 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1386 break;
1387 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00001388 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian305c6582009-01-08 01:10:55 +00001389 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar41071de2008-08-15 23:26:23 +00001390 break;
1391
Anders Carlsson91e20dd2009-04-02 05:55:18 +00001392 case Decl::LinkageSpec:
1393 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00001394 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00001395
1396 case Decl::FileScopeAsm: {
1397 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1398 std::string AsmString(AD->getAsmString()->getStrData(),
1399 AD->getAsmString()->getByteLength());
1400
1401 const std::string &S = getModule().getModuleInlineAsm();
1402 if (S.empty())
1403 getModule().setModuleInlineAsm(AsmString);
1404 else
1405 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1406 break;
1407 }
1408
1409 default:
1410 // Make sure we handled everything we should, every other kind is
1411 // a non-top-level decl. FIXME: Would be nice to have an
1412 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1413 // that easily.
1414 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1415 }
1416}