blob: f471565bc3314893e86380e69e9e70c408fe332f [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
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#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"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000021#include "clang/Basic/Diagnostic.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000024#include "llvm/CallingConv.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000025#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/Intrinsics.h"
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000027#include "llvm/Target/TargetData.h"
Chris Lattnera1945fa2008-04-30 16:05:42 +000028#include "llvm/Analysis/Verifier.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattner45e8cbd2007-11-28 05:34:05 +000033CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000034 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbarf77ac862008-08-11 21:35:06 +000035 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000036 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000037 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman0c995092008-05-26 12:59:39 +000038 CFConstantStringClassRef(0) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000039
40 if (Features.ObjC1) {
Daniel Dunbarf77ac862008-08-11 21:35:06 +000041 if (Features.NeXTRuntime) {
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000042 Runtime = CreateMacObjCRuntime(*this);
43 } else {
44 Runtime = CreateGNUObjCRuntime(*this);
45 }
Daniel Dunbarc17a4d32008-08-11 02:45:11 +000046 }
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000047
48 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek815c78f2008-08-05 18:50:11 +000049 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattner2b94fe32008-03-01 08:45:05 +000050}
51
52CodeGenModule::~CodeGenModule() {
Ted Kremenek815c78f2008-08-05 18:50:11 +000053 delete Runtime;
54 delete DebugInfo;
55}
56
57void CodeGenModule::Release() {
Anton Korobeynikov20ff3102008-06-01 14:13:53 +000058 EmitStatics();
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000059 if (Runtime)
60 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
61 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +000062 EmitCtorList(GlobalCtors, "llvm.global_ctors");
63 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman532485c2008-04-18 23:43:57 +000064 EmitAnnotations();
Chris Lattnera1945fa2008-04-30 16:05:42 +000065 // Run the verifier to check that the generated code is consistent.
66 assert(!verifyModule(TheModule));
Chris Lattner2b94fe32008-03-01 08:45:05 +000067}
Reid Spencer5f016e22007-07-11 17:01:13 +000068
Daniel Dunbar488e9932008-08-16 00:56:44 +000069/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +000070/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000071void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
72 bool OmitOnError) {
73 if (OmitOnError && getDiags().hasErrorOccurred())
74 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000075 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner2c8569d2007-12-02 07:19:18 +000076 "cannot codegen this %0 yet");
77 SourceRange Range = S->getSourceRange();
78 std::string Msg = Type;
Ted Kremenek9c728dc2007-12-12 22:39:36 +000079 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000080 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000081}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000082
Daniel Dunbar488e9932008-08-16 00:56:44 +000083/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +000084/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +000085void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
86 bool OmitOnError) {
87 if (OmitOnError && getDiags().hasErrorOccurred())
88 return;
Daniel Dunbar488e9932008-08-16 00:56:44 +000089 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnerc6fdc342008-01-12 07:05:38 +000090 "cannot codegen this %0 yet");
91 std::string Msg = Type;
92 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
93 &Msg, 1);
94}
95
Daniel Dunbar41071de2008-08-15 23:26:23 +000096/// setGlobalVisibility - Set the visibility for the given LLVM
97/// GlobalValue according to the given clang AST visibility value.
98static void setGlobalVisibility(llvm::GlobalValue *GV,
99 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4f8d1232008-05-22 00:50:06 +0000100 switch (Vis) {
101 default: assert(0 && "Unknown visibility!");
102 case VisibilityAttr::DefaultVisibility:
103 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
104 break;
105 case VisibilityAttr::HiddenVisibility:
106 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
107 break;
108 case VisibilityAttr::ProtectedVisibility:
109 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
110 break;
111 }
112}
113
Chris Lattner6d397602008-03-14 17:18:18 +0000114/// AddGlobalCtor - Add a function to the list that will be called before
115/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000116void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner6d397602008-03-14 17:18:18 +0000117 // TODO: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000118 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000119}
120
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000121/// AddGlobalDtor - Add a function to the list that will be called
122/// when the module is unloaded.
123void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
124 // TODO: Type coercion of void()* types.
125 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
126}
127
128void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
129 // Ctor function type is void()*.
130 llvm::FunctionType* CtorFTy =
131 llvm::FunctionType::get(llvm::Type::VoidTy,
132 std::vector<const llvm::Type*>(),
133 false);
134 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
135
136 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattner572cf092008-03-19 05:24:56 +0000137 llvm::StructType* CtorStructTy =
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000138 llvm::StructType::get(llvm::Type::Int32Ty,
139 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000140
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000141 // Construct the constructor and destructor arrays.
142 std::vector<llvm::Constant*> Ctors;
143 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
144 std::vector<llvm::Constant*> S;
145 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
146 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
147 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000148 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000149
150 if (!Ctors.empty()) {
151 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
152 new llvm::GlobalVariable(AT, false,
153 llvm::GlobalValue::AppendingLinkage,
154 llvm::ConstantArray::get(AT, Ctors),
155 GlobalName,
156 &TheModule);
157 }
Chris Lattner6d397602008-03-14 17:18:18 +0000158}
159
Nate Begeman532485c2008-04-18 23:43:57 +0000160void CodeGenModule::EmitAnnotations() {
161 if (Annotations.empty())
162 return;
163
164 // Create a new global variable for the ConstantStruct in the Module.
165 llvm::Constant *Array =
166 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
167 Annotations.size()),
168 Annotations);
169 llvm::GlobalValue *gv =
170 new llvm::GlobalVariable(Array->getType(), false,
171 llvm::GlobalValue::AppendingLinkage, Array,
172 "llvm.global.annotations", &TheModule);
173 gv->setSection("llvm.metadata");
174}
175
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000176static void SetGlobalValueAttributes(const Decl *D,
177 bool IsInternal,
178 bool IsInline,
179 llvm::GlobalValue *GV) {
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000180 // TODO: Set up linkage and many other things. Note, this is a simple
181 // approximation of what we really want.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000182 if (IsInternal) {
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000183 GV->setLinkage(llvm::Function::InternalLinkage);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000184 } else {
185 if (D->getAttr<DLLImportAttr>())
186 GV->setLinkage(llvm::Function::DLLImportLinkage);
187 else if (D->getAttr<DLLExportAttr>())
188 GV->setLinkage(llvm::Function::DLLExportLinkage);
189 else if (D->getAttr<WeakAttr>() || IsInline)
190 GV->setLinkage(llvm::Function::WeakLinkage);
191 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000192
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000193 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000194 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000195 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000196
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000197 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
Daniel Dunbara735ad82008-08-06 00:03:29 +0000198 // Prefaced with special LLVM marker to indicate that the name
199 // should not be munged.
200 GV->setName("\01" + ALA->getLabel());
201 }
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000202}
203
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000204static void SetFunctionAttrs(const CGFunctionInfo &Info, llvm::Function *F) {
205 ParamAttrListType ParamAttrList;
206 Info.constructParamAttrList(ParamAttrList);
Eli Friedmanc134fcb2008-06-04 19:41:28 +0000207
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000208 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
209 ParamAttrList.size()));
210
211 // Set the appropriate calling convention for the Function.
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000212 if (Info.getDecl()->getAttr<FastCallAttr>())
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000213 F->setCallingConv(llvm::CallingConv::Fast);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000214}
215
216/// SetFunctionAttributesForDefinition - Set function attributes
217/// specific to a function definition.
218void CodeGenModule::SetFunctionAttributesForDefinition(llvm::Function *F) {
219 if (!Features.Exceptions)
220 F->addParamAttr(0, llvm::ParamAttr::NoUnwind);
221}
222
223void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
224 llvm::Function *F) {
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000225 SetFunctionAttrs(CGFunctionInfo(MD, Context), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000226
227 SetFunctionAttributesForDefinition(F);
228
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000229 SetGlobalValueAttributes(MD, true, false, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000230}
231
232void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
233 llvm::Function *F) {
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000234 SetFunctionAttrs(CGFunctionInfo(FD), F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000235
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000236 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
237 FD->isInline(), F);
Eli Friedmanff4a2d92008-06-01 15:54:49 +0000238}
239
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000240void CodeGenModule::EmitStatics() {
241 // Emit code for each used static decl encountered. Since a previously unused
242 // static decl may become used during the generation of code for a static
243 // function, iterate until no changes are made.
244 bool Changed;
245 do {
246 Changed = false;
247 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000248 const ValueDecl *D = StaticDecls[i];
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000249
250 // Check if we have used a decl with the same name
251 // FIXME: The AST should have some sort of aggregate decls or
252 // global symbol map.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000253 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbara735ad82008-08-06 00:03:29 +0000254 continue;
Eli Friedman6f7e2ee2008-05-27 04:58:01 +0000255
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000256 // Emit the definition.
257 EmitGlobalDefinition(D);
258
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000259 // Erase the used decl from the list.
260 StaticDecls[i] = StaticDecls.back();
261 StaticDecls.pop_back();
262 --i;
263 --e;
264
265 // Remember that we made a change.
266 Changed = true;
267 }
268 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000269}
270
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000271/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
272/// annotation information for a given GlobalValue. The annotation struct is
273/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000274/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000275/// created from the AnnotateAttr's annotation. The third field is a constant
276/// string containing the name of the translation unit. The fourth field is
277/// the line number in the file of the annotated value declaration.
278///
279/// FIXME: this does not unique the annotation string constants, as llvm-gcc
280/// appears to.
281///
282llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
283 const AnnotateAttr *AA,
284 unsigned LineNo) {
285 llvm::Module *M = &getModule();
286
287 // get [N x i8] constants for the annotation string, and the filename string
288 // which are the 2nd and 3rd elements of the global annotation structure.
289 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
290 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
291 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
292 true);
293
294 // Get the two global values corresponding to the ConstantArrays we just
295 // created to hold the bytes of the strings.
296 llvm::GlobalValue *annoGV =
297 new llvm::GlobalVariable(anno->getType(), false,
298 llvm::GlobalValue::InternalLinkage, anno,
299 GV->getName() + ".str", M);
300 // translation unit name string, emitted into the llvm.metadata section.
301 llvm::GlobalValue *unitGV =
302 new llvm::GlobalVariable(unit->getType(), false,
303 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
304
305 // Create the ConstantStruct that is the global annotion.
306 llvm::Constant *Fields[4] = {
307 llvm::ConstantExpr::getBitCast(GV, SBP),
308 llvm::ConstantExpr::getBitCast(annoGV, SBP),
309 llvm::ConstantExpr::getBitCast(unitGV, SBP),
310 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
311 };
312 return llvm::ConstantStruct::get(Fields, 4, false);
313}
314
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000315void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
316 bool isDef, isStatic;
317
318 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
319 isDef = (FD->isThisDeclarationADefinition() ||
320 FD->getAttr<AliasAttr>());
321 isStatic = FD->getStorageClass() == FunctionDecl::Static;
322 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
323 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
324
325 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
326 isStatic = VD->getStorageClass() == VarDecl::Static;
327 } else {
328 assert(0 && "Invalid argument to EmitGlobal");
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000329 return;
330 }
331
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000332 // Forward declarations are emitted lazily on first use.
333 if (!isDef)
Chris Lattner88a69ad2007-07-13 05:13:43 +0000334 return;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000335
336 // If the global is a static, defer code generation until later so
337 // we can easily omit unused statics.
338 if (isStatic) {
339 StaticDecls.push_back(Global);
340 return;
341 }
342
343 // Otherwise emit the definition.
344 EmitGlobalDefinition(Global);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000345}
346
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000347void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
348 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
349 EmitGlobalFunctionDefinition(FD);
350 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
351 EmitGlobalVarDefinition(VD);
352 } else {
353 assert(0 && "Invalid argument to EmitGlobalDefinition()");
354 }
355}
356
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000357 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000358 assert(D->hasGlobalStorage() && "Not a global variable");
359
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000360 QualType ASTTy = D->getType();
361 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000362 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000363
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000364 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000365 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000366 if (!Entry)
367 Entry = new llvm::GlobalVariable(Ty, false,
368 llvm::GlobalValue::ExternalLinkage,
369 0, D->getName(), &getModule(), 0,
370 ASTTy.getAddressSpace());
371
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000372 // Make sure the result is of the correct type.
373 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000374}
375
376void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +0000377 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +0000378 QualType ASTTy = D->getType();
379 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000380
Chris Lattner8f32f712007-07-14 00:23:28 +0000381 if (D->getInit() == 0) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000382 // This is a tentative definition; tentative definitions are
383 // implicitly initialized with { 0 }
384 const llvm::Type* InitTy;
385 if (ASTTy->isIncompleteArrayType()) {
386 // An incomplete array is normally [ TYPE x 0 ], but we need
387 // to fix it to [ TYPE x 1 ].
388 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
389 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
390 } else {
391 InitTy = VarTy;
392 }
393 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman77ba7082008-05-30 19:50:47 +0000394 } else {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000395 Init = EmitConstantExpr(D->getInit());
Eli Friedman77ba7082008-05-30 19:50:47 +0000396 }
397 const llvm::Type* InitType = Init->getType();
398
Daniel Dunbar90db8822008-08-25 06:18:57 +0000399 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000400 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
401
Eli Friedman77ba7082008-05-30 19:50:47 +0000402 if (!GV) {
403 GV = new llvm::GlobalVariable(InitType, false,
404 llvm::GlobalValue::ExternalLinkage,
405 0, D->getName(), &getModule(), 0,
406 ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000407 } else if (GV->getType() !=
408 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman77ba7082008-05-30 19:50:47 +0000409 // We have a definition after a prototype with the wrong type.
410 // We must make a new GlobalVariable* and update everything that used OldGV
411 // (a declaration or tentative definition) with the new GlobalVariable*
412 // (which will be a definition).
413 //
414 // This happens if there is a prototype for a global (e.g. "extern int x[];")
415 // and then a definition of a different type (e.g. "int x[10];"). This also
416 // happens when an initializer has a different type from the type of the
417 // global (this happens with unions).
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000418 //
419 // FIXME: This also ends up happening if there's a definition followed by
420 // a tentative definition! (Although Sema rejects that construct
421 // at the moment.)
Eli Friedman77ba7082008-05-30 19:50:47 +0000422
423 // Save the old global
424 llvm::GlobalVariable *OldGV = GV;
425
426 // Make a new global with the correct type
427 GV = new llvm::GlobalVariable(InitType, false,
428 llvm::GlobalValue::ExternalLinkage,
429 0, D->getName(), &getModule(), 0,
430 ASTTy.getAddressSpace());
431 // Steal the name of the old global
432 GV->takeName(OldGV);
433
434 // Replace all uses of the old global with the new global
435 llvm::Constant *NewPtrForOldDecl =
436 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
437 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +0000438
439 // Erase the old global, since it is no longer used.
440 OldGV->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +0000441 }
Devang Patel8e53e722007-10-26 16:31:40 +0000442
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000443 Entry = GV;
Devang Patel8e53e722007-10-26 16:31:40 +0000444
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000445 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
446 SourceManager &SM = Context.getSourceManager();
447 AddAnnotation(EmitAnnotateAttr(GV, AA,
448 SM.getLogicalLineNumber(D->getLocation())));
449 }
450
Chris Lattner88a69ad2007-07-13 05:13:43 +0000451 GV->setInitializer(Init);
Nuno Lopesb381aac2008-09-01 11:33:04 +0000452 GV->setConstant(D->getType().isConstant(Context));
Chris Lattnerddee4232008-03-03 03:28:21 +0000453
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000454 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
455 unsigned Align;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000456 if (const IncompleteArrayType* IAT =
457 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedmancd5f4aa2008-05-30 20:39:54 +0000458 Align = Context.getTypeAlign(IAT->getElementType());
459 else
460 Align = Context.getTypeAlign(D->getType());
Eli Friedman08d78022008-05-29 11:10:27 +0000461 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
462 Align = std::max(Align, AA->getAlignment());
463 }
464 GV->setAlignment(Align / 8);
465
Chris Lattnerddee4232008-03-03 03:28:21 +0000466 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar41071de2008-08-15 23:26:23 +0000467 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattnerddee4232008-03-03 03:28:21 +0000468 // FIXME: else handle -fvisibility
Daniel Dunbara735ad82008-08-06 00:03:29 +0000469
470 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
471 // Prefaced with special LLVM marker to indicate that the name
472 // should not be munged.
473 GV->setName("\01" + ALA->getLabel());
474 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000475
476 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000477 if (D->getStorageClass() == VarDecl::Static)
478 GV->setLinkage(llvm::Function::InternalLinkage);
479 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000480 GV->setLinkage(llvm::Function::DLLImportLinkage);
481 else if (D->getAttr<DLLExportAttr>())
482 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000483 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000484 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000485 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000486 // FIXME: This isn't right. This should handle common linkage and other
487 // stuff.
488 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000489 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000490 case VarDecl::Auto:
491 case VarDecl::Register:
492 assert(0 && "Can't have auto or register globals");
493 case VarDecl::None:
494 if (!D->getInit())
Eli Friedmana07b7642008-05-29 11:03:17 +0000495 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattnerddee4232008-03-03 03:28:21 +0000496 break;
497 case VarDecl::Extern:
498 case VarDecl::PrivateExtern:
499 // todo: common
500 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000501 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000502 }
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000503
504 // Emit global variable debug information.
505 CGDebugInfo *DI = getDebugInfo();
506 if(DI) {
507 if(D->getLocation().isValid())
508 DI->setLocation(D->getLocation());
509 DI->EmitGlobalVariable(GV, D);
510 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000511}
Reid Spencer5f016e22007-07-11 17:01:13 +0000512
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000513llvm::GlobalValue *
514CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
515 // FIXME: param attributes for sext/zext etc.
516 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
517 assert(!D->getBody() && "Unexpected alias attr on function with body.");
518
519 const std::string& aliaseeName = AA->getAliasee();
520 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
521 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
522 llvm::Function::ExternalLinkage,
523 D->getName(),
524 aliasee,
525 &getModule());
Daniel Dunbar0dbe2272008-09-08 21:33:45 +0000526 // Alias should never be internal
527 SetGlobalValueAttributes(D, false, false, alias);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000528 return alias;
529 } else {
530 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000531 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000532 llvm::Function::ExternalLinkage,
533 D->getName(), &getModule());
534
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000535 SetFunctionAttributes(D, F);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000536 return F;
537 }
538}
539
540llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000541 QualType ASTTy = D->getType();
542 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
543 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000544
545 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbar90db8822008-08-25 06:18:57 +0000546 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000547 if (!Entry)
548 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000549
Daniel Dunbar9986eab2008-07-30 16:32:24 +0000550 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000551}
552
553void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbar90db8822008-08-25 06:18:57 +0000554 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000555 if (!Entry) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000556 Entry = EmitForwardFunctionDefinition(D);
557 } else {
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000558 // If the types mismatch then we have to rewrite the definition.
559 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
560 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000561 // Otherwise, we have a definition after a prototype with the wrong type.
562 // F is the Function* for the one with the wrong type, we must make a new
563 // Function* and update everything that used F (a declaration) with the new
564 // Function* (which will be a definition).
565 //
566 // This happens if there is a prototype for a function (e.g. "int f()") and
567 // then a definition of a different type (e.g. "int f(int x)"). Start by
568 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000569 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
570 NewFn->takeName(Entry);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000571
572 // Replace uses of F with the Function we will endow with a body.
573 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000574 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
575 Entry->replaceAllUsesWith(NewPtrForOldDecl);
576
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000577 // Ok, delete the old function now, which is dead.
Daniel Dunbar3c827a72008-08-05 23:31:02 +0000578 // FIXME: Add GlobalValue->eraseFromParent().
579 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
580 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
581 F->eraseFromParent();
582 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
583 GA->eraseFromParent();
584 } else {
585 assert(0 && "Invalid global variable type.");
586 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000587
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000588 Entry = NewFn;
589 }
590 }
591
592 if (D->getAttr<AliasAttr>()) {
593 ;
594 } else {
595 llvm::Function *Fn = cast<llvm::Function>(Entry);
596 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000597
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000598 SetFunctionAttributesForDefinition(Fn);
Daniel Dunbar6379a7a2008-08-11 17:36:14 +0000599
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000600 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
601 AddGlobalCtor(Fn, CA->getPriority());
602 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
603 AddGlobalDtor(Fn, DA->getPriority());
604 }
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000605 }
606}
607
Chris Lattnerc5b88062008-02-06 05:08:19 +0000608void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
609 // Make sure that this type is translated.
610 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000611}
612
613
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000614/// getBuiltinLibFunction
615llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000616 if (BuiltinID > BuiltinFunctions.size())
617 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000618
Chris Lattner1426fec2007-12-13 00:38:03 +0000619 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
620 // a slot for it.
621 assert(BuiltinID && "Invalid Builtin ID");
622 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000623 if (FunctionSlot)
624 return FunctionSlot;
625
626 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
627
628 // Get the name, skip over the __builtin_ prefix.
629 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
630
631 // Get the type for the builtin.
632 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
633 const llvm::FunctionType *Ty =
634 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
635
636 // FIXME: This has a serious problem with code like this:
637 // void abs() {}
638 // ... __builtin_abs(x);
639 // The two versions of abs will collide. The fix is for the builtin to win,
640 // and for the existing one to be turned into a constantexpr cast of the
641 // builtin. In the case where the existing one is a static function, it
642 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000643 if (llvm::Function *Existing = getModule().getFunction(Name)) {
644 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
645 return FunctionSlot = Existing;
646 assert(Existing == 0 && "FIXME: Name collision");
647 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000648
649 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000650 return FunctionSlot =
651 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
652 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000653}
654
Chris Lattner7acda7c2007-12-18 00:25:38 +0000655llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
656 unsigned NumTys) {
657 return llvm::Intrinsic::getDeclaration(&getModule(),
658 (llvm::Intrinsic::ID)IID, Tys, NumTys);
659}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000660
Reid Spencer5f016e22007-07-11 17:01:13 +0000661llvm::Function *CodeGenModule::getMemCpyFn() {
662 if (MemCpyFn) return MemCpyFn;
663 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000664 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 default: assert(0 && "Unknown ptr width");
666 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
667 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
668 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000669 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000670}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000671
Eli Friedman0c995092008-05-26 12:59:39 +0000672llvm::Function *CodeGenModule::getMemMoveFn() {
673 if (MemMoveFn) return MemMoveFn;
674 llvm::Intrinsic::ID IID;
675 switch (Context.Target.getPointerWidth(0)) {
676 default: assert(0 && "Unknown ptr width");
677 case 32: IID = llvm::Intrinsic::memmove_i32; break;
678 case 64: IID = llvm::Intrinsic::memmove_i64; break;
679 }
680 return MemMoveFn = getIntrinsic(IID);
681}
682
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000683llvm::Function *CodeGenModule::getMemSetFn() {
684 if (MemSetFn) return MemSetFn;
685 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000686 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000687 default: assert(0 && "Unknown ptr width");
688 case 32: IID = llvm::Intrinsic::memset_i32; break;
689 case 64: IID = llvm::Intrinsic::memset_i64; break;
690 }
691 return MemSetFn = getIntrinsic(IID);
692}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000693
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000694// We still need to work out the details of handling UTF-16.
695// See: <rdr://2996215>
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000696llvm::Constant *CodeGenModule::
697GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000698 llvm::StringMapEntry<llvm::Constant *> &Entry =
699 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
700
701 if (Entry.getValue())
702 return Entry.getValue();
703
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000704 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
705 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlssonc9e20912007-08-21 00:21:21 +0000706
707 if (!CFConstantStringClassRef) {
708 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
709 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000710
711 // FIXME: This is fairly broken if
712 // __CFConstantStringClassReference is already defined, in that it
713 // will get renamed and the user will most likely see an opaque
714 // error message. This is a general issue with relying on
715 // particular names.
716 llvm::GlobalVariable *GV =
Anders Carlssonc9e20912007-08-21 00:21:21 +0000717 new llvm::GlobalVariable(Ty, false,
718 llvm::GlobalVariable::ExternalLinkage, 0,
719 "__CFConstantStringClassReference",
720 &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000721
722 // Decay array -> ptr
723 CFConstantStringClassRef =
724 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000725 }
726
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000727 std::vector<llvm::Constant*> Fields(4);
728
Anders Carlssonc9e20912007-08-21 00:21:21 +0000729 // Class pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000730 Fields[0] = CFConstantStringClassRef;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000731
732 // Flags.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000733 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
734 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000735
736 // String pointer.
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000737 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000738 C = new llvm::GlobalVariable(C->getType(), true,
739 llvm::GlobalValue::InternalLinkage,
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000740 C, ".str", &getModule());
741 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Anders Carlssonc9e20912007-08-21 00:21:21 +0000742
743 // String length.
744 Ty = getTypes().ConvertType(getContext().LongTy);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000745 Fields[3] = llvm::ConstantInt::get(Ty, str.length());
Anders Carlssonc9e20912007-08-21 00:21:21 +0000746
747 // The struct.
748 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
749 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000750 llvm::GlobalVariable *GV =
751 new llvm::GlobalVariable(C->getType(), true,
752 llvm::GlobalVariable::InternalLinkage,
753 C, "", &getModule());
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000754
Anders Carlsson0c678292007-11-01 00:41:52 +0000755 GV->setSection("__DATA,__cfstring");
756 Entry.setValue(GV);
Daniel Dunbar3e9df992008-08-23 18:37:06 +0000757
Anders Carlsson0c678292007-11-01 00:41:52 +0000758 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000759}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000760
Daniel Dunbar61432932008-08-13 23:20:05 +0000761/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar1e049762008-08-10 20:25:57 +0000762/// string literal, properly padded to match the literal type.
Daniel Dunbar61432932008-08-13 23:20:05 +0000763std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar662174c82008-08-29 17:28:43 +0000764 if (E->isWide()) {
765 ErrorUnsupported(E, "wide string");
766 return "FIXME";
767 }
768
Daniel Dunbar1e049762008-08-10 20:25:57 +0000769 const char *StrData = E->getStrData();
770 unsigned Len = E->getByteLength();
771
772 const ConstantArrayType *CAT =
773 getContext().getAsConstantArrayType(E->getType());
774 assert(CAT && "String isn't pointer or array!");
775
776 // Resize the string to the right size
777 // FIXME: What about wchar_t strings?
778 std::string Str(StrData, StrData+Len);
779 uint64_t RealLen = CAT->getSize().getZExtValue();
780 Str.resize(RealLen, '\0');
781
782 return Str;
783}
784
Daniel Dunbar61432932008-08-13 23:20:05 +0000785/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
786/// constant array for the given string literal.
787llvm::Constant *
788CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
789 // FIXME: This can be more efficient.
790 return GetAddrOfConstantString(GetStringForStringLiteral(S));
791}
792
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000793/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000794static llvm::Constant *GenerateStringLiteral(const std::string &str,
795 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000796 CodeGenModule &CGM) {
Daniel Dunbar61432932008-08-13 23:20:05 +0000797 // Create Constant for this string literal. Don't add a '\0'.
798 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000799
800 // Create a global variable for this string
801 C = new llvm::GlobalVariable(C->getType(), constant,
802 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000803 C, ".str", &CGM.getModule());
Daniel Dunbar61432932008-08-13 23:20:05 +0000804
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000805 return C;
806}
807
Daniel Dunbar61432932008-08-13 23:20:05 +0000808/// GetAddrOfConstantString - Returns a pointer to a character array
809/// containing the literal. This contents are exactly that of the
810/// given string, i.e. it will not be null terminated automatically;
811/// see GetAddrOfConstantCString. Note that whether the result is
812/// actually a pointer to an LLVM constant depends on
813/// Feature.WriteableStrings.
814///
815/// The result has pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000816llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
817 // Don't share any string literals if writable-strings is turned on.
818 if (Features.WritableStrings)
819 return GenerateStringLiteral(str, false, *this);
820
821 llvm::StringMapEntry<llvm::Constant *> &Entry =
822 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
823
824 if (Entry.getValue())
825 return Entry.getValue();
826
827 // Create a global variable for this.
828 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
829 Entry.setValue(C);
830 return C;
831}
Daniel Dunbar61432932008-08-13 23:20:05 +0000832
833/// GetAddrOfConstantCString - Returns a pointer to a character
834/// array containing the literal and a terminating '\-'
835/// character. The result has pointer to array type.
836llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
Daniel Dunbar9d9b09c2008-08-15 18:29:12 +0000837 return GetAddrOfConstantString(str + "\0");
Daniel Dunbar61432932008-08-13 23:20:05 +0000838}
Daniel Dunbar41071de2008-08-15 23:26:23 +0000839
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000840/// EmitObjCPropertyImplementations - Emit information for synthesized
841/// properties for an implementation.
842void CodeGenModule::EmitObjCPropertyImplementations(const
843 ObjCImplementationDecl *D) {
844 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
845 e = D->propimpl_end(); i != e; ++i) {
846 ObjCPropertyImplDecl *PID = *i;
847
848 // Dynamic is just for type-checking.
849 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
850 ObjCPropertyDecl *PD = PID->getPropertyDecl();
851
852 // Determine which methods need to be implemented, some may have
853 // been overridden. Note that ::isSynthesized is not the method
854 // we want, that just indicates if the decl came from a
855 // property. What we want to know is if the method is defined in
856 // this implementation.
857 if (!D->getInstanceMethod(PD->getGetterName()))
858 CodeGenFunction(*this).GenerateObjCGetter(PID);
859 if (!PD->isReadOnly() &&
860 !D->getInstanceMethod(PD->getSetterName()))
861 CodeGenFunction(*this).GenerateObjCSetter(PID);
862 }
863 }
864}
865
Daniel Dunbar41071de2008-08-15 23:26:23 +0000866/// EmitTopLevelDecl - Emit code for a single top level declaration.
867void CodeGenModule::EmitTopLevelDecl(Decl *D) {
868 // If an error has occurred, stop code generation, but continue
869 // parsing and semantic analysis (to ensure all warnings and errors
870 // are emitted).
871 if (Diags.hasErrorOccurred())
872 return;
873
874 switch (D->getKind()) {
875 case Decl::Function:
876 case Decl::Var:
877 EmitGlobal(cast<ValueDecl>(D));
878 break;
879
880 case Decl::Namespace:
Daniel Dunbar662174c82008-08-29 17:28:43 +0000881 ErrorUnsupported(D, "namespace");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000882 break;
883
884 // Objective-C Decls
885
886 // Forward declarations, no (immediate) code generation.
887 case Decl::ObjCClass:
888 case Decl::ObjCCategory:
889 case Decl::ObjCForwardProtocol:
890 case Decl::ObjCInterface:
891 break;
892
893 case Decl::ObjCProtocol:
894 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
895 break;
896
897 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000898 // Categories have properties but don't support synthesize so we
899 // can ignore them here.
900
Daniel Dunbar41071de2008-08-15 23:26:23 +0000901 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
902 break;
903
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000904 case Decl::ObjCImplementation: {
905 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
906 EmitObjCPropertyImplementations(OMD);
907 Runtime->GenerateClass(OMD);
Daniel Dunbar41071de2008-08-15 23:26:23 +0000908 break;
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000909 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000910 case Decl::ObjCMethod: {
911 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
912 // If this is not a prototype, emit the body.
913 if (OMD->getBody())
914 CodeGenFunction(*this).GenerateObjCMethod(OMD);
915 break;
916 }
Daniel Dunbar41071de2008-08-15 23:26:23 +0000917 case Decl::ObjCCompatibleAlias:
Daniel Dunbar662174c82008-08-29 17:28:43 +0000918 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000919 break;
920
921 case Decl::LinkageSpec: {
922 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
923 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar488e9932008-08-16 00:56:44 +0000924 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar41071de2008-08-15 23:26:23 +0000925 // FIXME: implement C++ linkage, C linkage works mostly by C
926 // language reuse already.
927 break;
928 }
929
930 case Decl::FileScopeAsm: {
931 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
932 std::string AsmString(AD->getAsmString()->getStrData(),
933 AD->getAsmString()->getByteLength());
934
935 const std::string &S = getModule().getModuleInlineAsm();
936 if (S.empty())
937 getModule().setModuleInlineAsm(AsmString);
938 else
939 getModule().setModuleInlineAsm(S + '\n' + AsmString);
940 break;
941 }
942
943 default:
944 // Make sure we handled everything we should, every other kind is
945 // a non-top-level decl. FIXME: Would be nice to have an
946 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
947 // that easily.
948 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
949 }
950}
951