blob: b4cf5331869de2f8773a457d0915d5a844df942e [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
14#include "CodeGenModule.h"
Chris Lattnerf04a7562009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000016#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 Lattnerf04a7562009-03-26 05:00:52 +000020#include "clang/Frontend/CompileOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Chris Lattner825f6ea2008-11-04 16:51:42 +000023#include "clang/AST/DeclCXX.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000024#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "clang/Basic/TargetInfo.h"
Steve Naroff82e5db22009-04-01 15:50:34 +000027#include "clang/Basic/ConvertUTF.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000028#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000029#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000030#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000031#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33using namespace CodeGen;
34
35
Chris Lattnerf04a7562009-03-26 05:00:52 +000036CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
Chris Lattner22595b82007-12-02 01:40:18 +000037 llvm::Module &M, const llvm::TargetData &TD,
Chris Lattnerf04a7562009-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 Stump1f010b52009-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 Dunbarfc69bde2008-08-11 18:12:00 +000043
Chris Lattner08b05eb2009-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 Gupta40e56a12008-05-08 08:54:20 +000052
53 // If debug info generation is enabled, create the CGDebugInfo object.
Chris Lattnerf04a7562009-03-26 05:00:52 +000054 DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000055}
56
57CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000058 delete Runtime;
59 delete DebugInfo;
60}
61
62void CodeGenModule::Release() {
Chris Lattner13137542009-03-22 21:21:57 +000063 EmitDeferred();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000064 if (Runtime)
65 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
66 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000067 EmitCtorList(GlobalCtors, "llvm.global_ctors");
68 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000069 EmitAnnotations();
Daniel Dunbar21f3cf72009-02-13 20:29:50 +000070 EmitLLVMUsed();
Daniel Dunbar18c2ec62008-10-01 00:49:24 +000071}
72
Daniel Dunbar9503b782008-08-16 00:56:44 +000073/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000074/// specified stmt yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +000079 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000080 "cannot compile this %0 yet");
Chris Lattnercf9c9d02007-12-02 07:19:18 +000081 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000082 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
83 << Msg << S->getSourceRange();
Chris Lattnercf9c9d02007-12-02 07:19:18 +000084}
Chris Lattner0e4755d2007-12-02 06:27:33 +000085
Daniel Dunbar9503b782008-08-16 00:56:44 +000086/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000087/// specified decl yet.
Daniel Dunbar49bddf72008-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 Dunbar9503b782008-08-16 00:56:44 +000092 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarc5ba4912009-02-06 19:18:03 +000093 "cannot compile this %0 yet");
Chris Lattner806a5f52008-01-12 07:05:38 +000094 std::string Msg = Type;
Chris Lattner6948ae62008-11-18 07:04:44 +000095 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner806a5f52008-01-12 07:05:38 +000096}
97
Daniel Dunbar27250d32008-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) {
Dan Gohman4751a3a2008-05-22 00:50:06 +0000102 switch (Vis) {
103 default: assert(0 && "Unknown visibility!");
104 case VisibilityAttr::DefaultVisibility:
105 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
106 break;
107 case VisibilityAttr::HiddenVisibility:
108 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
109 break;
110 case VisibilityAttr::ProtectedVisibility:
111 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
112 break;
113 }
114}
115
Fariborz Jahanian49343332009-04-03 03:28:57 +0000116static void setGlobalOptionVisibility(llvm::GlobalValue *GV,
117 LangOptions::VisibilityMode Vis) {
118 switch (Vis) {
119 default: assert(0 && "Unknown visibility!");
120 case LangOptions::NonVisibility:
121 break;
122 case LangOptions::DefaultVisibility:
123 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
124 break;
125 case LangOptions::HiddenVisibility:
126 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
127 break;
128 case LangOptions::ProtectedVisibility:
129 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
130 break;
131 }
132}
133
134
Douglas Gregor3556bc72009-02-13 00:10:09 +0000135/// \brief Retrieves the mangled name for the given declaration.
136///
137/// If the given declaration requires a mangled name, returns an
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000138/// const char* containing the mangled name. Otherwise, returns
139/// the unmangled name.
Douglas Gregor3556bc72009-02-13 00:10:09 +0000140///
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000141const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000142 // In C, functions with no attributes never need to be mangled. Fastpath them.
143 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
144 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000145 return ND->getNameAsCString();
Chris Lattnerdaa199c2009-03-21 06:31:09 +0000146 }
147
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000148 llvm::SmallString<256> Name;
149 llvm::raw_svector_ostream Out(Name);
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000150 if (!mangleName(ND, Context, Out)) {
151 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
Chris Lattner08b05eb2009-03-21 07:12:05 +0000152 return ND->getNameAsCString();
Daniel Dunbar947cb1d2009-03-05 22:59:19 +0000153 }
Douglas Gregor3556bc72009-02-13 00:10:09 +0000154
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000155 Name += '\0';
Chris Lattner08b05eb2009-03-21 07:12:05 +0000156 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
Douglas Gregor3556bc72009-02-13 00:10:09 +0000157}
158
Chris Lattner753d2592008-03-14 17:18:18 +0000159/// AddGlobalCtor - Add a function to the list that will be called before
160/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000161void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000162 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000163 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000164}
165
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000166/// AddGlobalDtor - Add a function to the list that will be called
167/// when the module is unloaded.
168void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000169 // FIXME: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000170 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
171}
172
173void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
174 // Ctor function type is void()*.
175 llvm::FunctionType* CtorFTy =
176 llvm::FunctionType::get(llvm::Type::VoidTy,
177 std::vector<const llvm::Type*>(),
178 false);
179 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
180
181 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000182 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000183 llvm::StructType::get(llvm::Type::Int32Ty,
184 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000185
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000186 // Construct the constructor and destructor arrays.
187 std::vector<llvm::Constant*> Ctors;
188 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
189 std::vector<llvm::Constant*> S;
190 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
191 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
192 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000193 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000194
195 if (!Ctors.empty()) {
196 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
197 new llvm::GlobalVariable(AT, false,
198 llvm::GlobalValue::AppendingLinkage,
199 llvm::ConstantArray::get(AT, Ctors),
200 GlobalName,
201 &TheModule);
202 }
Chris Lattner753d2592008-03-14 17:18:18 +0000203}
204
Nate Begeman52da5c72008-04-18 23:43:57 +0000205void CodeGenModule::EmitAnnotations() {
206 if (Annotations.empty())
207 return;
208
209 // Create a new global variable for the ConstantStruct in the Module.
210 llvm::Constant *Array =
211 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
212 Annotations.size()),
213 Annotations);
214 llvm::GlobalValue *gv =
215 new llvm::GlobalVariable(Array->getType(), false,
216 llvm::GlobalValue::AppendingLinkage, Array,
217 "llvm.global.annotations", &TheModule);
218 gv->setSection("llvm.metadata");
219}
220
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000221void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
222 bool IsInternal,
223 bool IsInline,
224 llvm::GlobalValue *GV,
225 bool ForDefinition) {
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000226 // FIXME: Set up linkage and many other things. Note, this is a simple
Nuno Lopes78534382008-06-08 15:45:52 +0000227 // approximation of what we really want.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000228 if (!ForDefinition) {
229 // Only a few attributes are set on declarations.
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000230 if (D->getAttr<DLLImportAttr>()) {
231 // The dllimport attribute is overridden by a subsequent declaration as
232 // dllexport.
Sebastian Redle299eb42009-01-05 20:53:53 +0000233 if (!D->getAttr<DLLExportAttr>()) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000234 // dllimport attribute can be applied only to function decls, not to
235 // definitions.
236 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
237 if (!FD->getBody())
238 GV->setLinkage(llvm::Function::DLLImportLinkage);
239 } else
240 GV->setLinkage(llvm::Function::DLLImportLinkage);
Sebastian Redle299eb42009-01-05 20:53:53 +0000241 }
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000242 } else if (D->getAttr<WeakAttr>() ||
243 D->getAttr<WeakImportAttr>()) {
244 // "extern_weak" is overloaded in LLVM; we probably should have
245 // separate linkage types for this.
Duncan Sands9aa5c262009-03-11 08:40:02 +0000246 GV->setLinkage(llvm::Function::ExternalWeakLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000247 }
Daniel Dunbar566a6502008-09-08 23:44:31 +0000248 } else {
249 if (IsInternal) {
250 GV->setLinkage(llvm::Function::InternalLinkage);
251 } else {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000252 if (D->getAttr<DLLExportAttr>()) {
253 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254 // The dllexport attribute is ignored for undefined symbols.
255 if (FD->getBody())
256 GV->setLinkage(llvm::Function::DLLExportLinkage);
257 } else
258 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000259 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
260 IsInline)
Mike Stump36dbf222009-03-07 16:33:28 +0000261 GV->setLinkage(llvm::Function::WeakAnyLinkage);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000262 }
Daniel Dunbara8f02052008-09-08 21:33:45 +0000263 }
Nuno Lopes78534382008-06-08 15:45:52 +0000264
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000265 // FIXME: Figure out the relative priority of the attribute,
266 // -fvisibility, and private_extern.
Daniel Dunbara8f02052008-09-08 21:33:45 +0000267 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000268 setGlobalVisibility(GV, attr->getVisibility());
Fariborz Jahanian49343332009-04-03 03:28:57 +0000269 else
270 setGlobalOptionVisibility(GV, getLangOptions().getVisibilityMode());
Daniel Dunbarced89142008-08-06 00:03:29 +0000271
Daniel Dunbar97509722009-02-12 17:28:23 +0000272 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
273 GV->setSection(SA->getName());
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000274
275 // Only add to llvm.used when we see a definition, otherwise we
276 // might add multiple times or risk the value being replaced by a
277 // subsequent RAUW.
278 if (ForDefinition) {
279 if (D->getAttr<UsedAttr>())
280 AddUsedGlobal(GV);
281 }
Nuno Lopes78534382008-06-08 15:45:52 +0000282}
283
Devang Patela85a9ef2008-09-25 21:02:23 +0000284void CodeGenModule::SetFunctionAttributes(const Decl *D,
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000285 const CGFunctionInfo &Info,
Daniel Dunbar3ef2e852008-09-10 00:41:16 +0000286 llvm::Function *F) {
Devang Patela85a9ef2008-09-25 21:02:23 +0000287 AttributeListType AttributeList;
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000288 ConstructAttributeList(Info, D, AttributeList);
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000289
Devang Patela85a9ef2008-09-25 21:02:23 +0000290 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
291 AttributeList.size()));
Eli Friedman9be42212008-06-01 15:54:49 +0000292
293 // Set the appropriate calling convention for the Function.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000294 if (D->getAttr<FastCallAttr>())
Anton Korobeynikov0ef7c382008-11-11 20:21:14 +0000295 F->setCallingConv(llvm::CallingConv::X86_FastCall);
296
297 if (D->getAttr<StdCallAttr>())
298 F->setCallingConv(llvm::CallingConv::X86_StdCall);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000299}
300
301/// SetFunctionAttributesForDefinition - Set function attributes
302/// specific to a function definition.
Daniel Dunbar566a6502008-09-08 23:44:31 +0000303void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
304 llvm::Function *F) {
305 if (isa<ObjCMethodDecl>(D)) {
306 SetGlobalValueAttributes(D, true, false, F, true);
307 } else {
308 const FunctionDecl *FD = cast<FunctionDecl>(D);
309 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
310 FD->isInline(), F, true);
311 }
312
Daniel Dunbara47bb8e2009-03-02 04:58:03 +0000313 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Daniel Dunbar9575eb32008-09-27 07:16:42 +0000314 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar0a2da712008-10-28 00:17:57 +0000315
316 if (D->getAttr<AlwaysInlineAttr>())
317 F->addFnAttr(llvm::Attribute::AlwaysInline);
Anders Carlsson2157eec2009-02-19 19:22:11 +0000318
319 if (D->getAttr<NoinlineAttr>())
320 F->addFnAttr(llvm::Attribute::NoInline);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000321}
322
323void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
324 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000325 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000326
Daniel Dunbar566a6502008-09-08 23:44:31 +0000327 SetFunctionAttributesForDefinition(MD, F);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000328}
329
330void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
331 llvm::Function *F) {
Daniel Dunbar34bda882009-02-02 23:23:47 +0000332 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +0000333
Daniel Dunbar566a6502008-09-08 23:44:31 +0000334 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
335 FD->isInline(), F, false);
336}
337
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000338void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
339 assert(!GV->isDeclaration() &&
340 "Only globals with definition can force usage.");
Chris Lattner4494c0a2009-03-31 22:37:52 +0000341 LLVMUsed.push_back(GV);
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000342}
343
344void CodeGenModule::EmitLLVMUsed() {
345 // Don't create llvm.used if there is no need.
346 if (LLVMUsed.empty())
347 return;
348
Chris Lattner4494c0a2009-03-31 22:37:52 +0000349 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
350 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, LLVMUsed.size());
351
352 // Convert LLVMUsed to what ConstantArray needs.
353 std::vector<llvm::Constant*> UsedArray;
354 UsedArray.resize(LLVMUsed.size());
355 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
356 UsedArray[i] =
357 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
358 }
359
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000360 llvm::GlobalVariable *GV =
361 new llvm::GlobalVariable(ATy, false,
362 llvm::GlobalValue::AppendingLinkage,
Chris Lattner4494c0a2009-03-31 22:37:52 +0000363 llvm::ConstantArray::get(ATy, UsedArray),
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000364 "llvm.used", &getModule());
365
366 GV->setSection("llvm.metadata");
367}
368
369void CodeGenModule::EmitDeferred() {
Chris Lattner38837f92009-03-21 09:44:56 +0000370 // Emit code for any potentially referenced deferred decls. Since a
371 // previously unused static decl may become used during the generation of code
372 // for a static function, iterate until no changes are made.
373 while (!DeferredDeclsToEmit.empty()) {
374 const ValueDecl *D = DeferredDeclsToEmit.back();
375 DeferredDeclsToEmit.pop_back();
376
377 // The mangled name for the decl must have been emitted in GlobalDeclMap.
378 // Look it up to see if it was defined with a stronger definition (e.g. an
379 // extern inline function with a strong function redefinition). If so,
380 // just ignore the deferred decl.
381 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
382 assert(CGRef && "Deferred decl wasn't referenced?");
Anders Carlsson2e427d52009-01-04 02:08:04 +0000383
Chris Lattner38837f92009-03-21 09:44:56 +0000384 if (!CGRef->isDeclaration())
385 continue;
386
387 // Otherwise, emit the definition and move on to the next one.
388 EmitGlobalDefinition(D);
389 }
Chris Lattner4b009652007-07-25 00:24:17 +0000390}
391
Nate Begeman8a704172008-04-19 04:17:09 +0000392/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
393/// annotation information for a given GlobalValue. The annotation struct is
394/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000395/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000396/// created from the AnnotateAttr's annotation. The third field is a constant
397/// string containing the name of the translation unit. The fourth field is
398/// the line number in the file of the annotated value declaration.
399///
400/// FIXME: this does not unique the annotation string constants, as llvm-gcc
401/// appears to.
402///
403llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
404 const AnnotateAttr *AA,
405 unsigned LineNo) {
406 llvm::Module *M = &getModule();
407
408 // get [N x i8] constants for the annotation string, and the filename string
409 // which are the 2nd and 3rd elements of the global annotation structure.
410 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
411 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
412 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
413 true);
414
415 // Get the two global values corresponding to the ConstantArrays we just
416 // created to hold the bytes of the strings.
Daniel Dunbarc3a48932009-03-31 23:42:16 +0000417 const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
Nate Begeman8a704172008-04-19 04:17:09 +0000418 llvm::GlobalValue *annoGV =
419 new llvm::GlobalVariable(anno->getType(), false,
420 llvm::GlobalValue::InternalLinkage, anno,
Daniel Dunbarc3a48932009-03-31 23:42:16 +0000421 GV->getName() + StringPrefix, M);
Nate Begeman8a704172008-04-19 04:17:09 +0000422 // translation unit name string, emitted into the llvm.metadata section.
423 llvm::GlobalValue *unitGV =
424 new llvm::GlobalVariable(unit->getType(), false,
Daniel Dunbarc3a48932009-03-31 23:42:16 +0000425 llvm::GlobalValue::InternalLinkage, unit,
426 StringPrefix, M);
Nate Begeman8a704172008-04-19 04:17:09 +0000427
428 // Create the ConstantStruct that is the global annotion.
429 llvm::Constant *Fields[4] = {
430 llvm::ConstantExpr::getBitCast(GV, SBP),
431 llvm::ConstantExpr::getBitCast(annoGV, SBP),
432 llvm::ConstantExpr::getBitCast(unitGV, SBP),
433 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
434 };
435 return llvm::ConstantStruct::get(Fields, 4, false);
436}
437
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000438bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000439 // Never defer when EmitAllDecls is specified or the decl has
440 // attribute used.
441 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000442 return false;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000443
444 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000445 // Constructors and destructors should never be deferred.
446 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
447 return false;
448
Chris Lattner7e5888f2009-03-21 08:03:33 +0000449 // FIXME: What about inline, and/or extern inline?
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000450 if (FD->getStorageClass() != FunctionDecl::Static)
451 return false;
452 } else {
453 const VarDecl *VD = cast<VarDecl>(Global);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000454 assert(VD->isFileVarDecl() && "Invalid decl");
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000455
456 if (VD->getStorageClass() != VarDecl::Static)
457 return false;
458 }
459
460 return true;
461}
462
463void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000464 // If this is an alias definition (which otherwise looks like a declaration)
465 // emit it now.
466 if (Global->getAttr<AliasAttr>())
467 return EmitAliasDefinition(Global);
Daniel Dunbar566a6502008-09-08 23:44:31 +0000468
Chris Lattner38837f92009-03-21 09:44:56 +0000469 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar36acae42009-03-19 08:27:24 +0000470 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000471 // Forward declarations are emitted lazily on first use.
472 if (!FD->isThisDeclarationADefinition())
473 return;
Daniel Dunbar21f3cf72009-02-13 20:29:50 +0000474 } else {
475 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000476 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
477
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000478 // Forward declarations are emitted lazily on first use.
Daniel Dunbar0c79d782009-02-13 22:49:13 +0000479 if (!VD->getInit() && VD->hasExternalStorage())
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000480 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000481 }
482
Chris Lattner38837f92009-03-21 09:44:56 +0000483 // Defer code generation when possible if this is a static definition, inline
484 // function etc. These we only want to emit if they are used.
Daniel Dunbarf3482b32009-02-13 21:18:01 +0000485 if (MayDeferGeneration(Global)) {
Chris Lattner38837f92009-03-21 09:44:56 +0000486 // If the value has already been used, add it directly to the
487 // DeferredDeclsToEmit list.
488 const char *MangledName = getMangledName(Global);
489 if (GlobalDeclMap.count(MangledName))
490 DeferredDeclsToEmit.push_back(Global);
491 else {
492 // Otherwise, remember that we saw a deferred decl with this name. The
493 // first use of the mangled name will cause it to move into
494 // DeferredDeclsToEmit.
495 DeferredDecls[MangledName] = Global;
496 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000497 return;
498 }
499
500 // Otherwise emit the definition.
501 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000502}
503
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000504void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
505 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
506 EmitGlobalFunctionDefinition(FD);
507 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
508 EmitGlobalVarDefinition(VD);
509 } else {
510 assert(0 && "Invalid argument to EmitGlobalDefinition()");
511 }
512}
513
Chris Lattneraea1aee2009-03-22 21:03:39 +0000514/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
515/// module, create and return an llvm Function with the specified type. If there
516/// is something in the module with the specified name, return it potentially
517/// bitcasted to the right type.
518///
519/// If D is non-null, it specifies a decl that correspond to this. This is used
520/// to set the attributes on the function when it is first created.
521llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
522 const llvm::Type *Ty,
523 const FunctionDecl *D) {
Chris Lattner5dd030f2009-03-21 09:25:43 +0000524 // Lookup the entry, lazily creating it if necessary.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000525 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
526 if (Entry) {
527 if (Entry->getType()->getElementType() == Ty)
528 return Entry;
529
530 // Make sure the result is of the correct type.
531 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
532 return llvm::ConstantExpr::getBitCast(Entry, PTy);
533 }
534
Chris Lattner38837f92009-03-21 09:44:56 +0000535 // This is the first use or definition of a mangled name. If there is a
536 // deferred decl with this name, remember that we need to emit it at the end
537 // of the file.
538 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000539 DeferredDecls.find(MangledName);
Chris Lattner38837f92009-03-21 09:44:56 +0000540 if (DDI != DeferredDecls.end()) {
541 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
542 // list, and remove it from DeferredDecls (since we don't need it anymore).
543 DeferredDeclsToEmit.push_back(DDI->second);
544 DeferredDecls.erase(DDI);
545 }
546
Chris Lattner5dd030f2009-03-21 09:25:43 +0000547 // This function doesn't have a complete type (for example, the return
548 // type is an incomplete struct). Use a fake type instead, and make
549 // sure not to try to set attributes.
550 bool ShouldSetAttributes = true;
551 if (!isa<llvm::FunctionType>(Ty)) {
552 Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
553 std::vector<const llvm::Type*>(), false);
554 ShouldSetAttributes = false;
555 }
556 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
557 llvm::Function::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000558 "", &getModule());
559 F->setName(MangledName);
Chris Lattneraea1aee2009-03-22 21:03:39 +0000560 if (D && ShouldSetAttributes)
Chris Lattner5dd030f2009-03-21 09:25:43 +0000561 SetFunctionAttributes(D, F);
562 Entry = F;
563 return F;
564}
565
Chris Lattneraea1aee2009-03-22 21:03:39 +0000566/// GetAddrOfFunction - Return the address of the given function. If Ty is
567/// non-null, then this function will use the specified type if it has to
568/// create it (this occurs when we see a definition of the function).
569llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D,
570 const llvm::Type *Ty) {
571 // If there was no specific requested type, just convert it now.
572 if (!Ty)
573 Ty = getTypes().ConvertType(D->getType());
574 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D);
575}
Eli Friedman43a0ce82008-05-30 19:50:47 +0000576
Chris Lattneraea1aee2009-03-22 21:03:39 +0000577/// CreateRuntimeFunction - Create a new runtime function with the specified
578/// type and name.
579llvm::Constant *
580CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
581 const char *Name) {
582 // Convert Name to be a uniqued string from the IdentifierInfo table.
583 Name = getContext().Idents.get(Name).getName();
584 return GetOrCreateLLVMFunction(Name, FTy, 0);
585}
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000586
Chris Lattneraea1aee2009-03-22 21:03:39 +0000587/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
588/// create and return an llvm GlobalVariable with the specified type. If there
589/// is something in the module with the specified name, return it potentially
590/// bitcasted to the right type.
591///
592/// If D is non-null, it specifies a decl that correspond to this. This is used
593/// to set the attributes on the global when it is first created.
594llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
595 const llvm::PointerType*Ty,
596 const VarDecl *D) {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000597 // Lookup the entry, lazily creating it if necessary.
Chris Lattner0b506252009-03-21 08:06:59 +0000598 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
Chris Lattner7e5888f2009-03-21 08:03:33 +0000599 if (Entry) {
Chris Lattneraea1aee2009-03-22 21:03:39 +0000600 if (Entry->getType() == Ty)
Chris Lattnera6984932009-03-21 09:16:30 +0000601 return Entry;
602
Chris Lattner7e5888f2009-03-21 08:03:33 +0000603 // Make sure the result is of the correct type.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000604 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000605 }
Chris Lattner38837f92009-03-21 09:44:56 +0000606
607 // This is the first use or definition of a mangled name. If there is a
608 // deferred decl with this name, remember that we need to emit it at the end
609 // of the file.
610 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI =
611 DeferredDecls.find(MangledName);
612 if (DDI != DeferredDecls.end()) {
613 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
614 // list, and remove it from DeferredDecls (since we don't need it anymore).
615 DeferredDeclsToEmit.push_back(DDI->second);
616 DeferredDecls.erase(DDI);
617 }
618
Chris Lattner7e5888f2009-03-21 08:03:33 +0000619 llvm::GlobalVariable *GV =
Chris Lattneraea1aee2009-03-22 21:03:39 +0000620 new llvm::GlobalVariable(Ty->getElementType(), false,
Chris Lattner7e5888f2009-03-21 08:03:33 +0000621 llvm::GlobalValue::ExternalLinkage,
Chris Lattner68306b32009-03-22 00:12:30 +0000622 0, "", &getModule(),
Chris Lattneraea1aee2009-03-22 21:03:39 +0000623 0, Ty->getAddressSpace());
Chris Lattner68306b32009-03-22 00:12:30 +0000624 GV->setName(MangledName);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000625
626 // Handle things which are present even on external declarations.
Chris Lattneraea1aee2009-03-22 21:03:39 +0000627 if (D) {
628 // FIXME: This code is overly simple and should be merged with
629 // other global handling.
630 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner7e5888f2009-03-21 08:03:33 +0000631
Chris Lattneraea1aee2009-03-22 21:03:39 +0000632 // FIXME: Merge with other attribute handling code.
633 if (D->getStorageClass() == VarDecl::PrivateExtern)
634 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
Chris Lattner7e5888f2009-03-21 08:03:33 +0000635
Chris Lattneraea1aee2009-03-22 21:03:39 +0000636 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
637 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
638 }
639
Chris Lattner7e5888f2009-03-21 08:03:33 +0000640 return Entry = GV;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000641}
642
Chris Lattneraea1aee2009-03-22 21:03:39 +0000643
644/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
645/// given global variable. If Ty is non-null and if the global doesn't exist,
646/// then it will be greated with the specified type instead of whatever the
647/// normal requested type would be.
648llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
649 const llvm::Type *Ty) {
650 assert(D->hasGlobalStorage() && "Not a global variable");
651 QualType ASTTy = D->getType();
652 if (Ty == 0)
653 Ty = getTypes().ConvertTypeForMem(ASTTy);
654
655 const llvm::PointerType *PTy =
656 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
657 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
658}
659
660/// CreateRuntimeVariable - Create a new runtime global variable with the
661/// specified type and name.
662llvm::Constant *
663CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
664 const char *Name) {
665 // Convert Name to be a uniqued string from the IdentifierInfo table.
666 Name = getContext().Idents.get(Name).getName();
667 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
668}
669
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000670void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000671 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000672 QualType ASTTy = D->getType();
Eli Friedman43a0ce82008-05-30 19:50:47 +0000673
Chris Lattner4b009652007-07-25 00:24:17 +0000674 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000675 // This is a tentative definition; tentative definitions are
676 // implicitly initialized with { 0 }
Chris Lattnera6984932009-03-21 09:16:30 +0000677 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000678 if (ASTTy->isIncompleteArrayType()) {
679 // An incomplete array is normally [ TYPE x 0 ], but we need
680 // to fix it to [ TYPE x 1 ].
Chris Lattnera6984932009-03-21 09:16:30 +0000681 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000682 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
Eli Friedman7008e9a2008-05-30 20:39:54 +0000683 }
684 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000685 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000686 Init = EmitConstantExpr(D->getInit());
Eli Friedman442959a2009-02-20 01:18:21 +0000687 if (!Init) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000688 ErrorUnsupported(D, "static initializer");
Eli Friedman442959a2009-02-20 01:18:21 +0000689 QualType T = D->getInit()->getType();
690 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
691 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000692 }
Eli Friedman43a0ce82008-05-30 19:50:47 +0000693
Chris Lattner23afd5b2009-03-21 08:13:05 +0000694 const llvm::Type* InitType = Init->getType();
Chris Lattnera6984932009-03-21 09:16:30 +0000695 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000696
Chris Lattnera6984932009-03-21 09:16:30 +0000697 // Strip off a bitcast if we got one back.
698 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
699 assert(CE->getOpcode() == llvm::Instruction::BitCast);
700 Entry = CE->getOperand(0);
701 }
702
703 // Entry is now either a Function or GlobalVariable.
704 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
705
706 // If we already have this global and it has an initializer, then
707 // we are in the rare situation where we emitted the defining
708 // declaration of the global and are now being asked to emit a
709 // definition which would be common. This occurs, for example, in
710 // the following situation because statics can be emitted out of
711 // order:
712 //
713 // static int x;
714 // static int *y = &x;
715 // static int x = 10;
716 // int **z = &y;
717 //
718 // Bail here so we don't blow away the definition. Note that if we
719 // can't distinguish here if we emitted a definition with a null
720 // initializer, but this case is safe.
721 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000722 assert(!D->getInit() && "Emitting multiple definitions of a decl!");
723 return;
Chris Lattnera6984932009-03-21 09:16:30 +0000724 }
725
726 // We have a definition after a declaration with the wrong type.
727 // We must make a new GlobalVariable* and update everything that used OldGV
728 // (a declaration or tentative definition) with the new GlobalVariable*
729 // (which will be a definition).
730 //
731 // This happens if there is a prototype for a global (e.g.
732 // "extern int x[];") and then a definition of a different type (e.g.
733 // "int x[10];"). This also happens when an initializer has a different type
734 // from the type of the global (this happens with unions).
735 //
736 // FIXME: This also ends up happening if there's a definition followed by
737 // a tentative definition! (Although Sema rejects that construct
738 // at the moment.)
739 if (GV == 0 ||
740 GV->getType()->getElementType() != InitType ||
741 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
742
743 // Remove the old entry from GlobalDeclMap so that we'll create a new one.
744 GlobalDeclMap.erase(getMangledName(D));
Daniel Dunbar3d78d3d2009-02-19 05:36:41 +0000745
Chris Lattnera6984932009-03-21 09:16:30 +0000746 // Make a new global with the correct type, this is now guaranteed to work.
747 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000748 GV->takeName(cast<llvm::GlobalValue>(Entry));
749
Eli Friedman43a0ce82008-05-30 19:50:47 +0000750 // Replace all uses of the old global with the new global
751 llvm::Constant *NewPtrForOldDecl =
Chris Lattnera6984932009-03-21 09:16:30 +0000752 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
753 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000754
755 // Erase the old global, since it is no longer used.
Chris Lattnera6984932009-03-21 09:16:30 +0000756 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000757 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000758
Nate Begeman8a704172008-04-19 04:17:09 +0000759 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
760 SourceManager &SM = Context.getSourceManager();
761 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner18c8dc02009-01-16 07:36:28 +0000762 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begeman8a704172008-04-19 04:17:09 +0000763 }
764
Chris Lattner4b009652007-07-25 00:24:17 +0000765 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000766 GV->setConstant(D->getType().isConstant(Context));
Eli Friedman175b73f2009-02-27 04:11:37 +0000767 GV->setAlignment(getContext().getDeclAlignInBytes(D));
Eli Friedmanb232e992008-05-29 11:10:27 +0000768
Chris Lattner402b3372008-03-03 03:28:21 +0000769 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000770 setGlobalVisibility(GV, attr->getVisibility());
Fariborz Jahanian49343332009-04-03 03:28:57 +0000771 else
772 setGlobalOptionVisibility(GV, getLangOptions().getVisibilityMode());
Daniel Dunbarced89142008-08-06 00:03:29 +0000773
Chris Lattner4b009652007-07-25 00:24:17 +0000774 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000775 if (D->getStorageClass() == VarDecl::Static)
776 GV->setLinkage(llvm::Function::InternalLinkage);
777 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000778 GV->setLinkage(llvm::Function::DLLImportLinkage);
779 else if (D->getAttr<DLLExportAttr>())
780 GV->setLinkage(llvm::Function::DLLExportLinkage);
Daniel Dunbar80f5f992009-03-06 16:20:49 +0000781 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
Mike Stump36dbf222009-03-07 16:33:28 +0000782 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000783 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000784 // FIXME: This isn't right. This should handle common linkage and other
785 // stuff.
786 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000787 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000788 case VarDecl::Auto:
789 case VarDecl::Register:
790 assert(0 && "Can't have auto or register globals");
791 case VarDecl::None:
Chris Lattnerf04a7562009-03-26 05:00:52 +0000792 if (!D->getInit() && !CompileOpts.NoCommon)
Duncan Sands78c33cc2009-03-11 20:15:27 +0000793 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Anders Carlsson689bba82008-12-03 05:51:23 +0000794 else
795 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000796 break;
797 case VarDecl::Extern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000798 // FIXME: common
799 break;
800
Chris Lattner402b3372008-03-03 03:28:21 +0000801 case VarDecl::PrivateExtern:
Daniel Dunbar3a80fc02009-01-13 02:25:00 +0000802 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
803 // FIXME: common
Chris Lattner402b3372008-03-03 03:28:21 +0000804 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000805 }
Chris Lattner4b009652007-07-25 00:24:17 +0000806 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000807
Daniel Dunbar97509722009-02-12 17:28:23 +0000808 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
809 GV->setSection(SA->getName());
810
Daniel Dunbar375da3f2009-02-13 22:08:43 +0000811 if (D->getAttr<UsedAttr>())
812 AddUsedGlobal(GV);
813
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000814 // Emit global variable debug information.
Chris Lattner23afd5b2009-03-21 08:13:05 +0000815 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000816 DI->setLocation(D->getLocation());
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000817 DI->EmitGlobalVariable(GV, D);
818 }
Chris Lattner4b009652007-07-25 00:24:17 +0000819}
820
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000821
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000822void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar3f197842009-02-19 07:15:39 +0000823 const llvm::FunctionType *Ty =
824 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
825
826 // As a special case, make sure that definitions of K&R function
827 // "type foo()" aren't declared as varargs (which forces the backend
828 // to do unnecessary work).
Chris Lattnerb7cee972009-03-22 19:35:37 +0000829 if (D->getType()->isFunctionNoProtoType()) {
830 assert(Ty->isVarArg() && "Didn't lower type as expected");
831 // Due to stret, the lowered function could have arguments. Just create the
832 // same type as was lowered by ConvertType but strip off the varargs bit.
833 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
834 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
835 }
Daniel Dunbar3f197842009-02-19 07:15:39 +0000836
Chris Lattnerd26784e2009-03-21 08:53:37 +0000837 // Get or create the prototype for teh function.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000838 llvm::Constant *Entry = GetAddrOfFunction(D, Ty);
Chris Lattnerd26784e2009-03-21 08:53:37 +0000839
Chris Lattner5dd030f2009-03-21 09:25:43 +0000840 // Strip off a bitcast if we got one back.
841 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
842 assert(CE->getOpcode() == llvm::Instruction::BitCast);
843 Entry = CE->getOperand(0);
844 }
845
846
847 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Daniel Dunbaredf953c2009-03-09 23:53:08 +0000848 // If the types mismatch then we have to rewrite the definition.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000849 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() &&
850 "Shouldn't replace non-declaration");
Chris Lattnerd26784e2009-03-21 08:53:37 +0000851
Chris Lattnere28718c2009-03-21 08:38:50 +0000852 // F is the Function* for the one with the wrong type, we must make a new
853 // Function* and update everything that used F (a declaration) with the new
854 // Function* (which will be a definition).
855 //
856 // This happens if there is a prototype for a function
857 // (e.g. "int f()") and then a definition of a different type
858 // (e.g. "int f(int x)"). Start by making a new function of the
859 // correct type, RAUW, then steal the name.
Chris Lattnerd26784e2009-03-21 08:53:37 +0000860 GlobalDeclMap.erase(getMangledName(D));
Chris Lattner5dd030f2009-03-21 09:25:43 +0000861 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty));
862 NewFn->takeName(cast<llvm::GlobalValue>(Entry));
Chris Lattnere28718c2009-03-21 08:38:50 +0000863
864 // Replace uses of F with the Function we will endow with a body.
865 llvm::Constant *NewPtrForOldDecl =
Chris Lattner5dd030f2009-03-21 09:25:43 +0000866 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
867 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnere28718c2009-03-21 08:38:50 +0000868
869 // Ok, delete the old function now, which is dead.
Chris Lattner5dd030f2009-03-21 09:25:43 +0000870 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattnere28718c2009-03-21 08:38:50 +0000871
Chris Lattner5dd030f2009-03-21 09:25:43 +0000872 Entry = NewFn;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000873 }
Chris Lattner5dd030f2009-03-21 09:25:43 +0000874
875 llvm::Function *Fn = cast<llvm::Function>(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000876
Daniel Dunbar566a6502008-09-08 23:44:31 +0000877 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000878
Daniel Dunbar566a6502008-09-08 23:44:31 +0000879 SetFunctionAttributesForDefinition(D, Fn);
880
Chris Lattnerd26784e2009-03-21 08:53:37 +0000881 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000882 AddGlobalCtor(Fn, CA->getPriority());
Chris Lattnerd26784e2009-03-21 08:53:37 +0000883 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar566a6502008-09-08 23:44:31 +0000884 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000885}
886
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000887void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
888 const AliasAttr *AA = D->getAttr<AliasAttr>();
889 assert(AA && "Not an alias?");
890
891 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
892
893 // Unique the name through the identifier table.
894 const char *AliaseeName = AA->getAliasee().c_str();
895 AliaseeName = getContext().Idents.get(AliaseeName).getName();
896
897 // Create a reference to the named value. This ensures that it is emitted
898 // if a deferred decl.
899 llvm::Constant *Aliasee;
900 if (isa<llvm::FunctionType>(DeclTy))
901 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0);
902 else
903 Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
904 llvm::PointerType::getUnqual(DeclTy), 0);
905
906 // Create the new alias itself, but don't set a name yet.
907 llvm::GlobalValue *GA =
908 new llvm::GlobalAlias(Aliasee->getType(),
909 llvm::Function::ExternalLinkage,
910 "", Aliasee, &getModule());
911
912 // See if there is already something with the alias' name in the module.
913 const char *MangledName = getMangledName(D);
914 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
915
916 if (Entry && !Entry->isDeclaration()) {
917 // If there is a definition in the module, then it wins over the alias.
918 // This is dubious, but allow it to be safe. Just ignore the alias.
919 GA->eraseFromParent();
920 return;
921 }
922
923 if (Entry) {
924 // If there is a declaration in the module, then we had an extern followed
925 // by the alias, as in:
926 // extern int test6();
927 // ...
928 // int test6() __attribute__((alias("test7")));
929 //
930 // Remove it and replace uses of it with the alias.
931
932 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
933 Entry->getType()));
Chris Lattner89a5b4e2009-03-22 21:47:11 +0000934 Entry->eraseFromParent();
935 }
936
937 // Now we know that there is no conflict, set the name.
938 Entry = GA;
939 GA->setName(MangledName);
940
941 // Alias should never be internal or inline.
942 SetGlobalValueAttributes(D, false, false, GA, true);
943}
944
Chris Lattnere6247a22009-03-22 21:56:56 +0000945/// getBuiltinLibFunction - Given a builtin id for a function like
946/// "__builtin_fabsf", return a Function* for "fabsf".
Mike Stump96b7a152009-02-27 22:42:30 +0000947llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Douglas Gregor411889e2009-02-13 23:20:09 +0000948 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
949 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
950 "isn't a lib fn");
Chris Lattnerab862cc2007-08-31 04:31:45 +0000951
Douglas Gregor411889e2009-02-13 23:20:09 +0000952 // Get the name, skip over the __builtin_ prefix (if necessary).
953 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
954 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
955 Name += 10;
Chris Lattnerab862cc2007-08-31 04:31:45 +0000956
957 // Get the type for the builtin.
Douglas Gregor1fa246d2009-02-14 01:52:53 +0000958 Builtin::Context::GetBuiltinTypeError Error;
959 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
960 assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
961
Chris Lattnerab862cc2007-08-31 04:31:45 +0000962 const llvm::FunctionType *Ty =
963 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
964
Chris Lattnere6247a22009-03-22 21:56:56 +0000965 // Unique the name through the identifier table.
966 Name = getContext().Idents.get(Name).getName();
Chris Lattnerab862cc2007-08-31 04:31:45 +0000967 // FIXME: param attributes for sext/zext etc.
Chris Lattnere6247a22009-03-22 21:56:56 +0000968 return GetOrCreateLLVMFunction(Name, Ty, 0);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000969}
970
Chris Lattner4b23f942007-12-18 00:25:38 +0000971llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
972 unsigned NumTys) {
973 return llvm::Intrinsic::getDeclaration(&getModule(),
974 (llvm::Intrinsic::ID)IID, Tys, NumTys);
975}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000976
Chris Lattner4b009652007-07-25 00:24:17 +0000977llvm::Function *CodeGenModule::getMemCpyFn() {
978 if (MemCpyFn) return MemCpyFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000979 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
980 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000981}
Anders Carlsson36a04872007-08-21 00:21:21 +0000982
Eli Friedman8f08a252008-05-26 12:59:39 +0000983llvm::Function *CodeGenModule::getMemMoveFn() {
984 if (MemMoveFn) return MemMoveFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000985 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
986 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
Eli Friedman8f08a252008-05-26 12:59:39 +0000987}
988
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000989llvm::Function *CodeGenModule::getMemSetFn() {
990 if (MemSetFn) return MemSetFn;
Chris Lattnere73302f2008-11-21 16:43:15 +0000991 const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
992 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000993}
Chris Lattner4b23f942007-12-18 00:25:38 +0000994
Anders Carlsson0c0d8952008-11-15 18:54:24 +0000995static void appendFieldAndPadding(CodeGenModule &CGM,
996 std::vector<llvm::Constant*>& Fields,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000997 FieldDecl *FieldD, FieldDecl *NextFieldD,
998 llvm::Constant* Field,
Chris Lattner08b05eb2009-03-21 07:12:05 +0000999 RecordDecl* RD, const llvm::StructType *STy) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001000 // Append the field.
1001 Fields.push_back(Field);
1002
Douglas Gregor8acb7272008-12-11 16:49:14 +00001003 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001004
1005 int NextStructFieldNo;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001006 if (!NextFieldD) {
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001007 NextStructFieldNo = STy->getNumElements();
1008 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +00001009 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001010 }
1011
1012 // Append padding
1013 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1014 llvm::Constant *C =
1015 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1016
1017 Fields.push_back(C);
1018 }
1019}
1020
Chris Lattnerab862cc2007-08-31 04:31:45 +00001021llvm::Constant *CodeGenModule::
Steve Naroff9a744e52009-04-01 13:55:36 +00001022GetAddrOfConstantCFString(const StringLiteral *Literal) {
Steve Naroff5e6084c2009-04-01 21:16:31 +00001023 std::string str;
1024 unsigned StringLength;
1025
Steve Naroff82e5db22009-04-01 15:50:34 +00001026 bool isUTF16 = false;
1027 if (Literal->containsNonAsciiOrNull()) {
1028 // Convert from UTF-8 to UTF-16.
1029 llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1030 const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1031 UTF16 *ToPtr = &ToBuf[0];
1032
1033 ConversionResult Result;
1034 Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1035 &ToPtr, ToPtr+Literal->getByteLength(),
1036 strictConversion);
1037 assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
Steve Naroff5e6084c2009-04-01 21:16:31 +00001038
Steve Naroffdfe09d82009-04-03 09:44:50 +00001039 // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1040 // without doing more surgery to this routine. Since we aren't explicitly
1041 // checking for endianness here, it's also a bug (when generating code for
1042 // a target that doesn't match the host endianness). Modeling this as an i16
1043 // array is likely the cleanest solution.
Steve Naroff5e6084c2009-04-01 21:16:31 +00001044 StringLength = ToPtr-&ToBuf[0];
1045 str.assign((char *)&ToBuf[0], StringLength*2); // Twice as many UTF8 chars.
Steve Naroff82e5db22009-04-01 15:50:34 +00001046 isUTF16 = true;
Steve Naroff5e6084c2009-04-01 21:16:31 +00001047 } else {
1048 str.assign(Literal->getStrData(), Literal->getByteLength());
1049 StringLength = str.length();
Steve Naroff82e5db22009-04-01 15:50:34 +00001050 }
Anders Carlsson36a04872007-08-21 00:21:21 +00001051 llvm::StringMapEntry<llvm::Constant *> &Entry =
1052 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1053
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001054 if (llvm::Constant *C = Entry.getValue())
1055 return C;
Anders Carlsson36a04872007-08-21 00:21:21 +00001056
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001057 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1058 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +00001059
1060 if (!CFConstantStringClassRef) {
1061 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1062 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001063
1064 // FIXME: This is fairly broken if
1065 // __CFConstantStringClassReference is already defined, in that it
1066 // will get renamed and the user will most likely see an opaque
1067 // error message. This is a general issue with relying on
1068 // particular names.
1069 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +00001070 new llvm::GlobalVariable(Ty, false,
1071 llvm::GlobalVariable::ExternalLinkage, 0,
1072 "__CFConstantStringClassReference",
1073 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001074
1075 // Decay array -> ptr
1076 CFConstantStringClassRef =
1077 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +00001078 }
1079
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001080 QualType CFTy = getContext().getCFConstantStringType();
1081 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001082
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001083 const llvm::StructType *STy =
1084 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1085
1086 std::vector<llvm::Constant*> Fields;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001087 RecordDecl::field_iterator Field = CFRD->field_begin();
1088
Anders Carlsson36a04872007-08-21 00:21:21 +00001089 // Class pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001090 FieldDecl *CurField = *Field++;
1091 FieldDecl *NextField = *Field++;
1092 appendFieldAndPadding(*this, Fields, CurField, NextField,
1093 CFConstantStringClassRef, CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001094
1095 // Flags.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001096 CurField = NextField;
1097 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001098 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001099 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroff82e5db22009-04-01 15:50:34 +00001100 isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1101 : llvm::ConstantInt::get(Ty, 0x07C8),
1102 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001103
1104 // String pointer.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001105 CurField = NextField;
1106 NextField = *Field++;
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001107 llvm::Constant *C = llvm::ConstantArray::get(str);
Daniel Dunbar6a916482009-04-03 00:57:44 +00001108
1109 const char *Sect, *Prefix;
1110 bool isConstant;
1111 if (isUTF16) {
1112 Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1113 Sect = getContext().Target.getUnicodeStringSection();
1114 // FIXME: Why does GCC not set constant here?
1115 isConstant = false;
1116 } else {
1117 Prefix = getContext().Target.getStringSymbolPrefix(true);
1118 Sect = getContext().Target.getCFStringDataSection();
1119 // FIXME: -fwritable-strings should probably affect this, but we
1120 // are following gcc here.
1121 isConstant = true;
1122 }
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001123 llvm::GlobalVariable *GV =
Daniel Dunbar6a916482009-04-03 00:57:44 +00001124 new llvm::GlobalVariable(C->getType(), isConstant,
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001125 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar6a916482009-04-03 00:57:44 +00001126 C, Prefix, &getModule());
1127 if (Sect)
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001128 GV->setSection(Sect);
Daniel Dunbar6a916482009-04-03 00:57:44 +00001129 if (isUTF16) {
1130 unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1131 GV->setAlignment(Align);
1132 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001133 appendFieldAndPadding(*this, Fields, CurField, NextField,
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001134 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001135 CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001136
1137 // String length.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001138 CurField = NextField;
1139 NextField = 0;
Anders Carlsson36a04872007-08-21 00:21:21 +00001140 Ty = getTypes().ConvertType(getContext().LongTy);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001141 appendFieldAndPadding(*this, Fields, CurField, NextField,
Steve Naroff5e6084c2009-04-01 21:16:31 +00001142 llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
Anders Carlsson36a04872007-08-21 00:21:21 +00001143
1144 // The struct.
Anders Carlsson0c0d8952008-11-15 18:54:24 +00001145 C = llvm::ConstantStruct::get(STy, Fields);
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001146 GV = new llvm::GlobalVariable(C->getType(), true,
1147 llvm::GlobalVariable::InternalLinkage, C,
1148 getContext().Target.getCFStringSymbolPrefix(),
1149 &getModule());
1150 if (const char *Sect = getContext().Target.getCFStringSection())
1151 GV->setSection(Sect);
Anders Carlsson9be009e2007-11-01 00:41:52 +00001152 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +00001153
Anders Carlsson9be009e2007-11-01 00:41:52 +00001154 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +00001155}
Chris Lattnerdb6be562007-11-28 05:34:05 +00001156
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001157/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001158/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001159std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001160 const char *StrData = E->getStrData();
1161 unsigned Len = E->getByteLength();
1162
1163 const ConstantArrayType *CAT =
1164 getContext().getAsConstantArrayType(E->getType());
1165 assert(CAT && "String isn't pointer or array!");
1166
Chris Lattner14032222009-02-26 23:01:51 +00001167 // Resize the string to the right size.
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001168 std::string Str(StrData, StrData+Len);
1169 uint64_t RealLen = CAT->getSize().getZExtValue();
Chris Lattner14032222009-02-26 23:01:51 +00001170
1171 if (E->isWide())
1172 RealLen *= getContext().Target.getWCharWidth()/8;
1173
Daniel Dunbar3c670e12008-08-10 20:25:57 +00001174 Str.resize(RealLen, '\0');
1175
1176 return Str;
1177}
1178
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001179/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1180/// constant array for the given string literal.
1181llvm::Constant *
1182CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1183 // FIXME: This can be more efficient.
1184 return GetAddrOfConstantString(GetStringForStringLiteral(S));
1185}
1186
Chris Lattnerc5d32632009-02-24 22:18:39 +00001187/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1188/// array for the given ObjCEncodeExpr node.
1189llvm::Constant *
1190CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1191 std::string Str;
1192 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmandc8d1c62009-03-07 20:17:55 +00001193
1194 return GetAddrOfConstantCString(Str);
Chris Lattnerc5d32632009-02-24 22:18:39 +00001195}
1196
1197
Chris Lattnera6dcce32008-02-11 00:02:17 +00001198/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +00001199static llvm::Constant *GenerateStringLiteral(const std::string &str,
1200 bool constant,
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001201 CodeGenModule &CGM,
1202 const char *GlobalName) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001203 // Create Constant for this string literal. Don't add a '\0'.
1204 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001205
1206 // Create a global variable for this string
Chris Lattnerc5d32632009-02-24 22:18:39 +00001207 return new llvm::GlobalVariable(C->getType(), constant,
1208 llvm::GlobalValue::InternalLinkage,
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001209 C, GlobalName, &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +00001210}
1211
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001212/// GetAddrOfConstantString - Returns a pointer to a character array
1213/// containing the literal. This contents are exactly that of the
1214/// given string, i.e. it will not be null terminated automatically;
1215/// see GetAddrOfConstantCString. Note that whether the result is
1216/// actually a pointer to an LLVM constant depends on
1217/// Feature.WriteableStrings.
1218///
1219/// The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001220llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1221 const char *GlobalName) {
Daniel Dunbarc3a48932009-03-31 23:42:16 +00001222 bool IsConstant = !Features.WritableStrings;
1223
1224 // Get the default prefix if a name wasn't specified.
1225 if (!GlobalName)
1226 GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1227
1228 // Don't share any string literals if strings aren't constant.
1229 if (!IsConstant)
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001230 return GenerateStringLiteral(str, false, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001231
1232 llvm::StringMapEntry<llvm::Constant *> &Entry =
1233 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1234
1235 if (Entry.getValue())
Chris Lattnerc5d32632009-02-24 22:18:39 +00001236 return Entry.getValue();
Chris Lattnerdb6be562007-11-28 05:34:05 +00001237
1238 // Create a global variable for this.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001239 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerdb6be562007-11-28 05:34:05 +00001240 Entry.setValue(C);
1241 return C;
1242}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001243
1244/// GetAddrOfConstantCString - Returns a pointer to a character
1245/// array containing the literal and a terminating '\-'
1246/// character. The result has pointer to array type.
Daniel Dunbara70e1d72008-10-17 21:56:50 +00001247llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1248 const char *GlobalName){
Chris Lattnerb2176012008-12-09 19:10:54 +00001249 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbar31fe9c32008-08-13 23:20:05 +00001250}
Daniel Dunbar27250d32008-08-15 23:26:23 +00001251
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001252/// EmitObjCPropertyImplementations - Emit information for synthesized
1253/// properties for an implementation.
1254void CodeGenModule::EmitObjCPropertyImplementations(const
1255 ObjCImplementationDecl *D) {
1256 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1257 e = D->propimpl_end(); i != e; ++i) {
1258 ObjCPropertyImplDecl *PID = *i;
1259
1260 // Dynamic is just for type-checking.
1261 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1262 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1263
1264 // Determine which methods need to be implemented, some may have
1265 // been overridden. Note that ::isSynthesized is not the method
1266 // we want, that just indicates if the decl came from a
1267 // property. What we want to know is if the method is defined in
1268 // this implementation.
1269 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001270 CodeGenFunction(*this).GenerateObjCGetter(
1271 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001272 if (!PD->isReadOnly() &&
1273 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian91dd9d32008-12-09 20:23:04 +00001274 CodeGenFunction(*this).GenerateObjCSetter(
1275 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001276 }
1277 }
1278}
1279
Anders Carlssonb573e462009-04-02 05:55:18 +00001280/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson8ff34a62009-04-01 00:58:25 +00001281void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1282 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1283 I != E; ++I)
1284 EmitTopLevelDecl(*I);
1285}
1286
Anders Carlssonb573e462009-04-02 05:55:18 +00001287// EmitLinkageSpec - Emit all declarations in a linkage spec.
1288void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1289 if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1290 ErrorUnsupported(LSD, "linkage spec");
1291 return;
1292 }
1293
1294 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1295 I != E; ++I)
1296 EmitTopLevelDecl(*I);
1297}
1298
Daniel Dunbar27250d32008-08-15 23:26:23 +00001299/// EmitTopLevelDecl - Emit code for a single top level declaration.
1300void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1301 // If an error has occurred, stop code generation, but continue
1302 // parsing and semantic analysis (to ensure all warnings and errors
1303 // are emitted).
1304 if (Diags.hasErrorOccurred())
1305 return;
1306
1307 switch (D->getKind()) {
1308 case Decl::Function:
1309 case Decl::Var:
1310 EmitGlobal(cast<ValueDecl>(D));
1311 break;
1312
1313 case Decl::Namespace:
Anders Carlsson8ff34a62009-04-01 00:58:25 +00001314 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001315 break;
1316
1317 // Objective-C Decls
1318
Fariborz Jahanian2c7de6d2009-03-18 22:33:24 +00001319 // Forward declarations, no (immediate) code generation.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001320 case Decl::ObjCClass:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001321 case Decl::ObjCForwardProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001322 case Decl::ObjCCategory:
Daniel Dunbar27250d32008-08-15 23:26:23 +00001323 break;
Chris Lattner4f718b42009-04-01 02:36:43 +00001324 case Decl::ObjCInterface:
1325 // If we already laid out this interface due to an @class, and if we
1326 // codegen'd a reference it, update the 'opaque' type to be a real type now.
1327 Types.UpdateCompletedType(cast<ObjCInterfaceDecl>(D));
1328 break;
1329
Daniel Dunbar27250d32008-08-15 23:26:23 +00001330 case Decl::ObjCProtocol:
Fariborz Jahanianca277322009-03-21 18:06:45 +00001331 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001332 break;
1333
1334 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001335 // Categories have properties but don't support synthesize so we
1336 // can ignore them here.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001337 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1338 break;
1339
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001340 case Decl::ObjCImplementation: {
1341 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1342 EmitObjCPropertyImplementations(OMD);
1343 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +00001344 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +00001345 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001346 case Decl::ObjCMethod: {
1347 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1348 // If this is not a prototype, emit the body.
1349 if (OMD->getBody())
1350 CodeGenFunction(*this).GenerateObjCMethod(OMD);
1351 break;
1352 }
Daniel Dunbar27250d32008-08-15 23:26:23 +00001353 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian2ac4cd32009-01-08 01:10:55 +00001354 // compatibility-alias is a directive and has no code gen.
Daniel Dunbar27250d32008-08-15 23:26:23 +00001355 break;
1356
Anders Carlssonb573e462009-04-02 05:55:18 +00001357 case Decl::LinkageSpec:
1358 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar27250d32008-08-15 23:26:23 +00001359 break;
Daniel Dunbar27250d32008-08-15 23:26:23 +00001360
1361 case Decl::FileScopeAsm: {
1362 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1363 std::string AsmString(AD->getAsmString()->getStrData(),
1364 AD->getAsmString()->getByteLength());
1365
1366 const std::string &S = getModule().getModuleInlineAsm();
1367 if (S.empty())
1368 getModule().setModuleInlineAsm(AsmString);
1369 else
1370 getModule().setModuleInlineAsm(S + '\n' + AsmString);
1371 break;
1372 }
1373
1374 default:
1375 // Make sure we handled everything we should, every other kind is
1376 // a non-top-level decl. FIXME: Would be nice to have an
1377 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1378 // that easily.
1379 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1380 }
1381}