blob: 373027bbff4247ab30ed11eea807159f46f6f5a9 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
Daniel Dunbar84bb85f2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000020#include "clang/Basic/Diagnostic.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000026#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000027#include "llvm/Analysis/Verifier.h"
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattnerdb6be562007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
Daniel Dunbar1be1df32008-08-11 21:35:06 +000034 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000035 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000036 Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
Eli Friedman8f08a252008-05-26 12:59:39 +000037 CFConstantStringClassRef(0) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000038
39 if (Features.ObjC1) {
Daniel Dunbar1be1df32008-08-11 21:35:06 +000040 if (Features.NeXTRuntime) {
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000041 Runtime = CreateMacObjCRuntime(*this);
42 } else {
43 Runtime = CreateGNUObjCRuntime(*this);
44 }
Daniel Dunbar8c85fac2008-08-11 02:45:11 +000045 }
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000046
47 // If debug info generation is enabled, create the CGDebugInfo object.
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000048 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Ted Kremenek7c65b6c2008-08-05 18:50:11 +000052 delete Runtime;
53 delete DebugInfo;
54}
55
56void CodeGenModule::Release() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000057 EmitStatics();
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000058 if (Runtime)
59 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
60 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +000061 EmitCtorList(GlobalCtors, "llvm.global_ctors");
62 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman52da5c72008-04-18 23:43:57 +000063 EmitAnnotations();
Chris Lattnerb033c4a2008-04-30 16:05:42 +000064 // Run the verifier to check that the generated code is consistent.
65 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000066}
Chris Lattner4b009652007-07-25 00:24:17 +000067
Daniel Dunbar9503b782008-08-16 00:56:44 +000068/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnercf9c9d02007-12-02 07:19:18 +000069/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000070void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
71 bool OmitOnError) {
72 if (OmitOnError && getDiags().hasErrorOccurred())
73 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000074 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattnercf9c9d02007-12-02 07:19:18 +000075 "cannot codegen this %0 yet");
76 SourceRange Range = S->getSourceRange();
77 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000078 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000079 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000080}
Chris Lattner0e4755d2007-12-02 06:27:33 +000081
Daniel Dunbar9503b782008-08-16 00:56:44 +000082/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner806a5f52008-01-12 07:05:38 +000083/// specified decl yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +000084void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
85 bool OmitOnError) {
86 if (OmitOnError && getDiags().hasErrorOccurred())
87 return;
Daniel Dunbar9503b782008-08-16 00:56:44 +000088 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Chris Lattner806a5f52008-01-12 07:05:38 +000089 "cannot codegen this %0 yet");
90 std::string Msg = Type;
91 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
92 &Msg, 1);
93}
94
Daniel Dunbar27250d32008-08-15 23:26:23 +000095/// setGlobalVisibility - Set the visibility for the given LLVM
96/// GlobalValue according to the given clang AST visibility value.
97static void setGlobalVisibility(llvm::GlobalValue *GV,
98 VisibilityAttr::VisibilityTypes Vis) {
Dan Gohman4751a3a2008-05-22 00:50:06 +000099 switch (Vis) {
100 default: assert(0 && "Unknown visibility!");
101 case VisibilityAttr::DefaultVisibility:
102 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
103 break;
104 case VisibilityAttr::HiddenVisibility:
105 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
106 break;
107 case VisibilityAttr::ProtectedVisibility:
108 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
109 break;
110 }
111}
112
Chris Lattner753d2592008-03-14 17:18:18 +0000113/// AddGlobalCtor - Add a function to the list that will be called before
114/// main() runs.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000115void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Chris Lattner753d2592008-03-14 17:18:18 +0000116 // TODO: Type coercion of void()* types.
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000117 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner753d2592008-03-14 17:18:18 +0000118}
119
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000120/// AddGlobalDtor - Add a function to the list that will be called
121/// when the module is unloaded.
122void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
123 // TODO: Type coercion of void()* types.
124 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
125}
126
127void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
128 // Ctor function type is void()*.
129 llvm::FunctionType* CtorFTy =
130 llvm::FunctionType::get(llvm::Type::VoidTy,
131 std::vector<const llvm::Type*>(),
132 false);
133 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
134
135 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnera18c12e2008-03-19 05:24:56 +0000136 llvm::StructType* CtorStructTy =
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000137 llvm::StructType::get(llvm::Type::Int32Ty,
138 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000139
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000140 // Construct the constructor and destructor arrays.
141 std::vector<llvm::Constant*> Ctors;
142 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
143 std::vector<llvm::Constant*> S;
144 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
145 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
146 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner753d2592008-03-14 17:18:18 +0000147 }
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000148
149 if (!Ctors.empty()) {
150 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
151 new llvm::GlobalVariable(AT, false,
152 llvm::GlobalValue::AppendingLinkage,
153 llvm::ConstantArray::get(AT, Ctors),
154 GlobalName,
155 &TheModule);
156 }
Chris Lattner753d2592008-03-14 17:18:18 +0000157}
158
Nate Begeman52da5c72008-04-18 23:43:57 +0000159void CodeGenModule::EmitAnnotations() {
160 if (Annotations.empty())
161 return;
162
163 // Create a new global variable for the ConstantStruct in the Module.
164 llvm::Constant *Array =
165 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
166 Annotations.size()),
167 Annotations);
168 llvm::GlobalValue *gv =
169 new llvm::GlobalVariable(Array->getType(), false,
170 llvm::GlobalValue::AppendingLinkage, Array,
171 "llvm.global.annotations", &TheModule);
172 gv->setSection("llvm.metadata");
173}
174
Nuno Lopes78534382008-06-08 15:45:52 +0000175void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
176 llvm::GlobalValue *GV) {
177 // TODO: Set up linkage and many other things. Note, this is a simple
178 // approximation of what we really want.
179 if (FD->getStorageClass() == FunctionDecl::Static)
180 GV->setLinkage(llvm::Function::InternalLinkage);
181 else if (FD->getAttr<DLLImportAttr>())
182 GV->setLinkage(llvm::Function::DLLImportLinkage);
183 else if (FD->getAttr<DLLExportAttr>())
184 GV->setLinkage(llvm::Function::DLLExportLinkage);
185 else if (FD->getAttr<WeakAttr>() || FD->isInline())
186 GV->setLinkage(llvm::Function::WeakLinkage);
187
188 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000189 setGlobalVisibility(GV, attr->getVisibility());
Nuno Lopes78534382008-06-08 15:45:52 +0000190 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000191
192 if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
193 // Prefaced with special LLVM marker to indicate that the name
194 // should not be munged.
195 GV->setName("\01" + ALA->getLabel());
196 }
Nuno Lopes78534382008-06-08 15:45:52 +0000197}
198
Daniel Dunbarf2787002008-09-04 23:41:35 +0000199static void
200SetFunctionAttributesFromTypes(const Decl *FD,
201 llvm::Function *F,
202 const llvm::SmallVector<QualType, 16> &ArgTypes) {
Eli Friedman9be42212008-06-01 15:54:49 +0000203 unsigned FuncAttrs = 0;
204 if (FD->getAttr<NoThrowAttr>())
205 FuncAttrs |= llvm::ParamAttr::NoUnwind;
206 if (FD->getAttr<NoReturnAttr>())
207 FuncAttrs |= llvm::ParamAttr::NoReturn;
208
209 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
Eli Friedman9be42212008-06-01 15:54:49 +0000210 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
Daniel Dunbar896d1e22008-09-05 00:57:45 +0000211 unsigned increment = 1;
212 if (CodeGenFunction::hasAggregateLLVMType(ArgTypes[0])) {
Eli Friedman9be42212008-06-01 15:54:49 +0000213 ParamAttrList.push_back(
214 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
Daniel Dunbar896d1e22008-09-05 00:57:45 +0000215 ++increment;
216 } else if (ArgTypes[0]->isPromotableIntegerType()) {
217 if (ArgTypes[0]->isSignedIntegerType()) {
218 FuncAttrs |= llvm::ParamAttr::SExt;
219 } else if (ArgTypes[0]->isUnsignedIntegerType()) {
220 FuncAttrs |= llvm::ParamAttr::ZExt;
221 }
222 }
223 if (FuncAttrs)
224 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
Daniel Dunbarf2787002008-09-04 23:41:35 +0000225 for (llvm::SmallVector<QualType, 8>::const_iterator i = ArgTypes.begin() + 1,
226 e = ArgTypes.end(); i != e; ++i, ++increment) {
227 QualType ParamType = *i;
228 unsigned ParamAttrs = 0;
229 if (ParamType->isRecordType())
230 ParamAttrs |= llvm::ParamAttr::ByVal;
231 if (ParamType->isSignedIntegerType() &&
232 ParamType->isPromotableIntegerType())
233 ParamAttrs |= llvm::ParamAttr::SExt;
234 if (ParamType->isUnsignedIntegerType() &&
235 ParamType->isPromotableIntegerType())
236 ParamAttrs |= llvm::ParamAttr::ZExt;
237 if (ParamAttrs)
238 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(increment,
239 ParamAttrs));
Eli Friedman9be42212008-06-01 15:54:49 +0000240 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000241
Eli Friedman9be42212008-06-01 15:54:49 +0000242 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
243 ParamAttrList.size()));
244
245 // Set the appropriate calling convention for the Function.
246 if (FD->getAttr<FastCallAttr>())
247 F->setCallingConv(llvm::CallingConv::Fast);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000248}
249
250/// SetFunctionAttributesForDefinition - Set function attributes
251/// specific to a function definition.
252void CodeGenModule::SetFunctionAttributesForDefinition(llvm::Function *F) {
253 if (!Features.Exceptions)
254 F->addParamAttr(0, llvm::ParamAttr::NoUnwind);
255}
256
257void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
258 llvm::Function *F) {
259 llvm::SmallVector<QualType, 16> ArgTypes;
260
261 ArgTypes.push_back(MD->getResultType());
262 ArgTypes.push_back(MD->getSelfDecl()->getType());
263 ArgTypes.push_back(Context.getObjCSelType());
264 for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
265 e = MD->param_end(); i != e; ++i)
266 ArgTypes.push_back((*i)->getType());
267
268 SetFunctionAttributesFromTypes(MD, F, ArgTypes);
269
270 SetFunctionAttributesForDefinition(F);
271
272 // FIXME: set visibility
273}
274
275void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
276 llvm::Function *F) {
277 llvm::SmallVector<QualType, 16> ArgTypes;
278 const FunctionType *FTy = FD->getType()->getAsFunctionType();
279 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FTy);
280
281 ArgTypes.push_back(FTy->getResultType());
282 if (FTP)
283 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
284 ArgTypes.push_back(FTP->getArgType(i));
285
286 SetFunctionAttributesFromTypes(FD, F, ArgTypes);
Eli Friedman9be42212008-06-01 15:54:49 +0000287
Nuno Lopes78534382008-06-08 15:45:52 +0000288 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000289}
290
Nate Begemanad320b62008-04-20 06:29:50 +0000291void CodeGenModule::EmitStatics() {
292 // Emit code for each used static decl encountered. Since a previously unused
293 // static decl may become used during the generation of code for a static
294 // function, iterate until no changes are made.
295 bool Changed;
296 do {
297 Changed = false;
298 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000299 const ValueDecl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000300
301 // Check if we have used a decl with the same name
302 // FIXME: The AST should have some sort of aggregate decls or
303 // global symbol map.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000304 if (!GlobalDeclMap.count(D->getIdentifier()))
Daniel Dunbarced89142008-08-06 00:03:29 +0000305 continue;
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000306
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000307 // Emit the definition.
308 EmitGlobalDefinition(D);
309
Nate Begemanad320b62008-04-20 06:29:50 +0000310 // Erase the used decl from the list.
311 StaticDecls[i] = StaticDecls.back();
312 StaticDecls.pop_back();
313 --i;
314 --e;
315
316 // Remember that we made a change.
317 Changed = true;
318 }
319 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000320}
321
Nate Begeman8a704172008-04-19 04:17:09 +0000322/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
323/// annotation information for a given GlobalValue. The annotation struct is
324/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000325/// GlobalValue being annotated. The second field is the constant string
Nate Begeman8a704172008-04-19 04:17:09 +0000326/// created from the AnnotateAttr's annotation. The third field is a constant
327/// string containing the name of the translation unit. The fourth field is
328/// the line number in the file of the annotated value declaration.
329///
330/// FIXME: this does not unique the annotation string constants, as llvm-gcc
331/// appears to.
332///
333llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
334 const AnnotateAttr *AA,
335 unsigned LineNo) {
336 llvm::Module *M = &getModule();
337
338 // get [N x i8] constants for the annotation string, and the filename string
339 // which are the 2nd and 3rd elements of the global annotation structure.
340 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
341 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
342 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
343 true);
344
345 // Get the two global values corresponding to the ConstantArrays we just
346 // created to hold the bytes of the strings.
347 llvm::GlobalValue *annoGV =
348 new llvm::GlobalVariable(anno->getType(), false,
349 llvm::GlobalValue::InternalLinkage, anno,
350 GV->getName() + ".str", M);
351 // translation unit name string, emitted into the llvm.metadata section.
352 llvm::GlobalValue *unitGV =
353 new llvm::GlobalVariable(unit->getType(), false,
354 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
355
356 // Create the ConstantStruct that is the global annotion.
357 llvm::Constant *Fields[4] = {
358 llvm::ConstantExpr::getBitCast(GV, SBP),
359 llvm::ConstantExpr::getBitCast(annoGV, SBP),
360 llvm::ConstantExpr::getBitCast(unitGV, SBP),
361 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
362 };
363 return llvm::ConstantStruct::get(Fields, 4, false);
364}
365
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000366void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
367 bool isDef, isStatic;
368
369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
370 isDef = (FD->isThisDeclarationADefinition() ||
371 FD->getAttr<AliasAttr>());
372 isStatic = FD->getStorageClass() == FunctionDecl::Static;
373 } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
374 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
375
376 isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
377 isStatic = VD->getStorageClass() == VarDecl::Static;
378 } else {
379 assert(0 && "Invalid argument to EmitGlobal");
Nate Begemanad320b62008-04-20 06:29:50 +0000380 return;
381 }
382
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000383 // Forward declarations are emitted lazily on first use.
384 if (!isDef)
Chris Lattner4b009652007-07-25 00:24:17 +0000385 return;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000386
387 // If the global is a static, defer code generation until later so
388 // we can easily omit unused statics.
389 if (isStatic) {
390 StaticDecls.push_back(Global);
391 return;
392 }
393
394 // Otherwise emit the definition.
395 EmitGlobalDefinition(Global);
Nate Begemanad320b62008-04-20 06:29:50 +0000396}
397
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000398void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
399 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
400 EmitGlobalFunctionDefinition(FD);
401 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
402 EmitGlobalVarDefinition(VD);
403 } else {
404 assert(0 && "Invalid argument to EmitGlobalDefinition()");
405 }
406}
407
Daniel Dunbar2188c532008-07-30 16:32:24 +0000408 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000409 assert(D->hasGlobalStorage() && "Not a global variable");
410
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000411 QualType ASTTy = D->getType();
412 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Daniel Dunbar2188c532008-07-30 16:32:24 +0000413 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000414
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000415 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000416 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000417 if (!Entry)
418 Entry = new llvm::GlobalVariable(Ty, false,
419 llvm::GlobalValue::ExternalLinkage,
420 0, D->getName(), &getModule(), 0,
421 ASTTy.getAddressSpace());
422
Daniel Dunbar2188c532008-07-30 16:32:24 +0000423 // Make sure the result is of the correct type.
424 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000425}
426
427void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +0000428 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000429 QualType ASTTy = D->getType();
430 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000431
Chris Lattner4b009652007-07-25 00:24:17 +0000432 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000433 // This is a tentative definition; tentative definitions are
434 // implicitly initialized with { 0 }
435 const llvm::Type* InitTy;
436 if (ASTTy->isIncompleteArrayType()) {
437 // An incomplete array is normally [ TYPE x 0 ], but we need
438 // to fix it to [ TYPE x 1 ].
439 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
440 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
441 } else {
442 InitTy = VarTy;
443 }
444 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000445 } else {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000446 Init = EmitConstantExpr(D->getInit());
Eli Friedman43a0ce82008-05-30 19:50:47 +0000447 }
448 const llvm::Type* InitType = Init->getType();
449
Daniel Dunbarad30be42008-08-25 06:18:57 +0000450 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000451 llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
452
Eli Friedman43a0ce82008-05-30 19:50:47 +0000453 if (!GV) {
454 GV = new llvm::GlobalVariable(InitType, false,
455 llvm::GlobalValue::ExternalLinkage,
456 0, D->getName(), &getModule(), 0,
457 ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000458 } else if (GV->getType() !=
459 llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000460 // We have a definition after a prototype with the wrong type.
461 // We must make a new GlobalVariable* and update everything that used OldGV
462 // (a declaration or tentative definition) with the new GlobalVariable*
463 // (which will be a definition).
464 //
465 // This happens if there is a prototype for a global (e.g. "extern int x[];")
466 // and then a definition of a different type (e.g. "int x[10];"). This also
467 // happens when an initializer has a different type from the type of the
468 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000469 //
470 // FIXME: This also ends up happening if there's a definition followed by
471 // a tentative definition! (Although Sema rejects that construct
472 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000473
474 // Save the old global
475 llvm::GlobalVariable *OldGV = GV;
476
477 // Make a new global with the correct type
478 GV = new llvm::GlobalVariable(InitType, false,
479 llvm::GlobalValue::ExternalLinkage,
480 0, D->getName(), &getModule(), 0,
481 ASTTy.getAddressSpace());
482 // Steal the name of the old global
483 GV->takeName(OldGV);
484
485 // Replace all uses of the old global with the new global
486 llvm::Constant *NewPtrForOldDecl =
487 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
488 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000489
490 // Erase the old global, since it is no longer used.
491 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000492 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000493
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000494 Entry = GV;
Devang Patel8b5f5302007-10-26 16:31:40 +0000495
Nate Begeman8a704172008-04-19 04:17:09 +0000496 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
497 SourceManager &SM = Context.getSourceManager();
498 AddAnnotation(EmitAnnotateAttr(GV, AA,
499 SM.getLogicalLineNumber(D->getLocation())));
500 }
501
Chris Lattner4b009652007-07-25 00:24:17 +0000502 GV->setInitializer(Init);
Nuno Lopesa7bbf562008-09-01 11:33:04 +0000503 GV->setConstant(D->getType().isConstant(Context));
Chris Lattner402b3372008-03-03 03:28:21 +0000504
Eli Friedman7008e9a2008-05-30 20:39:54 +0000505 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
506 unsigned Align;
Chris Lattnera1923f62008-08-04 07:31:14 +0000507 if (const IncompleteArrayType* IAT =
508 Context.getAsIncompleteArrayType(D->getType()))
Eli Friedman7008e9a2008-05-30 20:39:54 +0000509 Align = Context.getTypeAlign(IAT->getElementType());
510 else
511 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000512 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
513 Align = std::max(Align, AA->getAlignment());
514 }
515 GV->setAlignment(Align / 8);
516
Chris Lattner402b3372008-03-03 03:28:21 +0000517 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Daniel Dunbar27250d32008-08-15 23:26:23 +0000518 setGlobalVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000519 // FIXME: else handle -fvisibility
Daniel Dunbarced89142008-08-06 00:03:29 +0000520
521 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
522 // Prefaced with special LLVM marker to indicate that the name
523 // should not be munged.
524 GV->setName("\01" + ALA->getLabel());
525 }
Chris Lattner4b009652007-07-25 00:24:17 +0000526
527 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000528 if (D->getStorageClass() == VarDecl::Static)
529 GV->setLinkage(llvm::Function::InternalLinkage);
530 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000531 GV->setLinkage(llvm::Function::DLLImportLinkage);
532 else if (D->getAttr<DLLExportAttr>())
533 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000534 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000535 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000536 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000537 // FIXME: This isn't right. This should handle common linkage and other
538 // stuff.
539 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000540 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000541 case VarDecl::Auto:
542 case VarDecl::Register:
543 assert(0 && "Can't have auto or register globals");
544 case VarDecl::None:
545 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000546 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000547 break;
548 case VarDecl::Extern:
549 case VarDecl::PrivateExtern:
550 // todo: common
551 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000552 }
Chris Lattner4b009652007-07-25 00:24:17 +0000553 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000554
555 // Emit global variable debug information.
556 CGDebugInfo *DI = getDebugInfo();
557 if(DI) {
558 if(D->getLocation().isValid())
559 DI->setLocation(D->getLocation());
560 DI->EmitGlobalVariable(GV, D);
561 }
Chris Lattner4b009652007-07-25 00:24:17 +0000562}
563
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000564llvm::GlobalValue *
565CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
566 // FIXME: param attributes for sext/zext etc.
567 if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
568 assert(!D->getBody() && "Unexpected alias attr on function with body.");
569
570 const std::string& aliaseeName = AA->getAliasee();
571 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
572 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
573 llvm::Function::ExternalLinkage,
574 D->getName(),
575 aliasee,
576 &getModule());
577 SetGlobalValueAttributes(D, alias);
578 return alias;
579 } else {
580 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
Daniel Dunbarf2787002008-09-04 23:41:35 +0000581 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000582 llvm::Function::ExternalLinkage,
583 D->getName(), &getModule());
584
Daniel Dunbarf2787002008-09-04 23:41:35 +0000585 SetFunctionAttributes(D, F);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000586 return F;
587 }
588}
589
590llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
Daniel Dunbar2188c532008-07-30 16:32:24 +0000591 QualType ASTTy = D->getType();
592 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
593 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000594
595 // Lookup the entry, lazily creating it if necessary.
Daniel Dunbarad30be42008-08-25 06:18:57 +0000596 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000597 if (!Entry)
598 Entry = EmitForwardFunctionDefinition(D);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000599
Daniel Dunbar2188c532008-07-30 16:32:24 +0000600 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000601}
602
603void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
Daniel Dunbarad30be42008-08-25 06:18:57 +0000604 llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000605 if (!Entry) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000606 Entry = EmitForwardFunctionDefinition(D);
607 } else {
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000608 // If the types mismatch then we have to rewrite the definition.
609 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
610 if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000611 // Otherwise, we have a definition after a prototype with the wrong type.
612 // F is the Function* for the one with the wrong type, we must make a new
613 // Function* and update everything that used F (a declaration) with the new
614 // Function* (which will be a definition).
615 //
616 // This happens if there is a prototype for a function (e.g. "int f()") and
617 // then a definition of a different type (e.g. "int f(int x)"). Start by
618 // making a new function of the correct type, RAUW, then steal the name.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000619 llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
620 NewFn->takeName(Entry);
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000621
622 // Replace uses of F with the Function we will endow with a body.
623 llvm::Constant *NewPtrForOldDecl =
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000624 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
625 Entry->replaceAllUsesWith(NewPtrForOldDecl);
626
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000627 // Ok, delete the old function now, which is dead.
Daniel Dunbara31eaf72008-08-05 23:31:02 +0000628 // FIXME: Add GlobalValue->eraseFromParent().
629 assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
630 if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
631 F->eraseFromParent();
632 } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
633 GA->eraseFromParent();
634 } else {
635 assert(0 && "Invalid global variable type.");
636 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000637
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000638 Entry = NewFn;
639 }
640 }
641
642 if (D->getAttr<AliasAttr>()) {
643 ;
644 } else {
645 llvm::Function *Fn = cast<llvm::Function>(Entry);
646 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000647
Daniel Dunbarf2787002008-09-04 23:41:35 +0000648 SetFunctionAttributesForDefinition(Fn);
Daniel Dunbar91692d92008-08-11 17:36:14 +0000649
Daniel Dunbardd2e9ca2008-08-01 00:01:51 +0000650 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
651 AddGlobalCtor(Fn, CA->getPriority());
652 } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
653 AddGlobalDtor(Fn, DA->getPriority());
654 }
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000655 }
656}
657
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000658void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
659 // Make sure that this type is translated.
660 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000661}
662
663
Chris Lattnerab862cc2007-08-31 04:31:45 +0000664/// getBuiltinLibFunction
665llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000666 if (BuiltinID > BuiltinFunctions.size())
667 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000668
Chris Lattner9f2d6892007-12-13 00:38:03 +0000669 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
670 // a slot for it.
671 assert(BuiltinID && "Invalid Builtin ID");
672 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000673 if (FunctionSlot)
674 return FunctionSlot;
675
676 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
677
678 // Get the name, skip over the __builtin_ prefix.
679 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
680
681 // Get the type for the builtin.
682 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
683 const llvm::FunctionType *Ty =
684 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
685
686 // FIXME: This has a serious problem with code like this:
687 // void abs() {}
688 // ... __builtin_abs(x);
689 // The two versions of abs will collide. The fix is for the builtin to win,
690 // and for the existing one to be turned into a constantexpr cast of the
691 // builtin. In the case where the existing one is a static function, it
692 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000693 if (llvm::Function *Existing = getModule().getFunction(Name)) {
694 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
695 return FunctionSlot = Existing;
696 assert(Existing == 0 && "FIXME: Name collision");
697 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000698
699 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000700 return FunctionSlot =
701 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
702 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000703}
704
Chris Lattner4b23f942007-12-18 00:25:38 +0000705llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
706 unsigned NumTys) {
707 return llvm::Intrinsic::getDeclaration(&getModule(),
708 (llvm::Intrinsic::ID)IID, Tys, NumTys);
709}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000710
Chris Lattner4b009652007-07-25 00:24:17 +0000711llvm::Function *CodeGenModule::getMemCpyFn() {
712 if (MemCpyFn) return MemCpyFn;
713 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000714 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000715 default: assert(0 && "Unknown ptr width");
716 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
717 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
718 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000719 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000720}
Anders Carlsson36a04872007-08-21 00:21:21 +0000721
Eli Friedman8f08a252008-05-26 12:59:39 +0000722llvm::Function *CodeGenModule::getMemMoveFn() {
723 if (MemMoveFn) return MemMoveFn;
724 llvm::Intrinsic::ID IID;
725 switch (Context.Target.getPointerWidth(0)) {
726 default: assert(0 && "Unknown ptr width");
727 case 32: IID = llvm::Intrinsic::memmove_i32; break;
728 case 64: IID = llvm::Intrinsic::memmove_i64; break;
729 }
730 return MemMoveFn = getIntrinsic(IID);
731}
732
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000733llvm::Function *CodeGenModule::getMemSetFn() {
734 if (MemSetFn) return MemSetFn;
735 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000736 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000737 default: assert(0 && "Unknown ptr width");
738 case 32: IID = llvm::Intrinsic::memset_i32; break;
739 case 64: IID = llvm::Intrinsic::memset_i64; break;
740 }
741 return MemSetFn = getIntrinsic(IID);
742}
Chris Lattner4b23f942007-12-18 00:25:38 +0000743
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000744// We still need to work out the details of handling UTF-16.
745// See: <rdr://2996215>
Chris Lattnerab862cc2007-08-31 04:31:45 +0000746llvm::Constant *CodeGenModule::
747GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000748 llvm::StringMapEntry<llvm::Constant *> &Entry =
749 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
750
751 if (Entry.getValue())
752 return Entry.getValue();
753
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000754 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
755 llvm::Constant *Zeros[] = { Zero, Zero };
Anders Carlsson36a04872007-08-21 00:21:21 +0000756
757 if (!CFConstantStringClassRef) {
758 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
759 Ty = llvm::ArrayType::get(Ty, 0);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000760
761 // FIXME: This is fairly broken if
762 // __CFConstantStringClassReference is already defined, in that it
763 // will get renamed and the user will most likely see an opaque
764 // error message. This is a general issue with relying on
765 // particular names.
766 llvm::GlobalVariable *GV =
Anders Carlsson36a04872007-08-21 00:21:21 +0000767 new llvm::GlobalVariable(Ty, false,
768 llvm::GlobalVariable::ExternalLinkage, 0,
769 "__CFConstantStringClassReference",
770 &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000771
772 // Decay array -> ptr
773 CFConstantStringClassRef =
774 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000775 }
776
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000777 std::vector<llvm::Constant*> Fields(4);
778
Anders Carlsson36a04872007-08-21 00:21:21 +0000779 // Class pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000780 Fields[0] = CFConstantStringClassRef;
Anders Carlsson36a04872007-08-21 00:21:21 +0000781
782 // Flags.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000783 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
784 Fields[1] = llvm::ConstantInt::get(Ty, 0x07C8);
Anders Carlsson36a04872007-08-21 00:21:21 +0000785
786 // String pointer.
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000787 llvm::Constant *C = llvm::ConstantArray::get(str);
Anders Carlsson36a04872007-08-21 00:21:21 +0000788 C = new llvm::GlobalVariable(C->getType(), true,
789 llvm::GlobalValue::InternalLinkage,
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000790 C, ".str", &getModule());
791 Fields[2] = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Anders Carlsson36a04872007-08-21 00:21:21 +0000792
793 // String length.
794 Ty = getTypes().ConvertType(getContext().LongTy);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000795 Fields[3] = llvm::ConstantInt::get(Ty, str.length());
Anders Carlsson36a04872007-08-21 00:21:21 +0000796
797 // The struct.
798 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
799 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000800 llvm::GlobalVariable *GV =
801 new llvm::GlobalVariable(C->getType(), true,
802 llvm::GlobalVariable::InternalLinkage,
803 C, "", &getModule());
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000804
Anders Carlsson9be009e2007-11-01 00:41:52 +0000805 GV->setSection("__DATA,__cfstring");
806 Entry.setValue(GV);
Daniel Dunbardbdb9512008-08-23 18:37:06 +0000807
Anders Carlsson9be009e2007-11-01 00:41:52 +0000808 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000809}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000810
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000811/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000812/// string literal, properly padded to match the literal type.
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000813std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Daniel Dunbar952f4732008-08-29 17:28:43 +0000814 if (E->isWide()) {
815 ErrorUnsupported(E, "wide string");
816 return "FIXME";
817 }
818
Daniel Dunbar3c670e12008-08-10 20:25:57 +0000819 const char *StrData = E->getStrData();
820 unsigned Len = E->getByteLength();
821
822 const ConstantArrayType *CAT =
823 getContext().getAsConstantArrayType(E->getType());
824 assert(CAT && "String isn't pointer or array!");
825
826 // Resize the string to the right size
827 // FIXME: What about wchar_t strings?
828 std::string Str(StrData, StrData+Len);
829 uint64_t RealLen = CAT->getSize().getZExtValue();
830 Str.resize(RealLen, '\0');
831
832 return Str;
833}
834
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000835/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
836/// constant array for the given string literal.
837llvm::Constant *
838CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
839 // FIXME: This can be more efficient.
840 return GetAddrOfConstantString(GetStringForStringLiteral(S));
841}
842
Chris Lattnera6dcce32008-02-11 00:02:17 +0000843/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000844static llvm::Constant *GenerateStringLiteral(const std::string &str,
845 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000846 CodeGenModule &CGM) {
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000847 // Create Constant for this string literal. Don't add a '\0'.
848 llvm::Constant *C = llvm::ConstantArray::get(str, false);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000849
850 // Create a global variable for this string
851 C = new llvm::GlobalVariable(C->getType(), constant,
852 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000853 C, ".str", &CGM.getModule());
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000854
Chris Lattnerdb6be562007-11-28 05:34:05 +0000855 return C;
856}
857
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000858/// GetAddrOfConstantString - Returns a pointer to a character array
859/// containing the literal. This contents are exactly that of the
860/// given string, i.e. it will not be null terminated automatically;
861/// see GetAddrOfConstantCString. Note that whether the result is
862/// actually a pointer to an LLVM constant depends on
863/// Feature.WriteableStrings.
864///
865/// The result has pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000866llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
867 // Don't share any string literals if writable-strings is turned on.
868 if (Features.WritableStrings)
869 return GenerateStringLiteral(str, false, *this);
870
871 llvm::StringMapEntry<llvm::Constant *> &Entry =
872 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
873
874 if (Entry.getValue())
875 return Entry.getValue();
876
877 // Create a global variable for this.
878 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
879 Entry.setValue(C);
880 return C;
881}
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000882
883/// GetAddrOfConstantCString - Returns a pointer to a character
884/// array containing the literal and a terminating '\-'
885/// character. The result has pointer to array type.
886llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
Daniel Dunbarb4278222008-08-15 18:29:12 +0000887 return GetAddrOfConstantString(str + "\0");
Daniel Dunbar31fe9c32008-08-13 23:20:05 +0000888}
Daniel Dunbar27250d32008-08-15 23:26:23 +0000889
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000890/// EmitObjCPropertyImplementations - Emit information for synthesized
891/// properties for an implementation.
892void CodeGenModule::EmitObjCPropertyImplementations(const
893 ObjCImplementationDecl *D) {
894 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
895 e = D->propimpl_end(); i != e; ++i) {
896 ObjCPropertyImplDecl *PID = *i;
897
898 // Dynamic is just for type-checking.
899 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
900 ObjCPropertyDecl *PD = PID->getPropertyDecl();
901
902 // Determine which methods need to be implemented, some may have
903 // been overridden. Note that ::isSynthesized is not the method
904 // we want, that just indicates if the decl came from a
905 // property. What we want to know is if the method is defined in
906 // this implementation.
907 if (!D->getInstanceMethod(PD->getGetterName()))
908 CodeGenFunction(*this).GenerateObjCGetter(PID);
909 if (!PD->isReadOnly() &&
910 !D->getInstanceMethod(PD->getSetterName()))
911 CodeGenFunction(*this).GenerateObjCSetter(PID);
912 }
913 }
914}
915
Daniel Dunbar27250d32008-08-15 23:26:23 +0000916/// EmitTopLevelDecl - Emit code for a single top level declaration.
917void CodeGenModule::EmitTopLevelDecl(Decl *D) {
918 // If an error has occurred, stop code generation, but continue
919 // parsing and semantic analysis (to ensure all warnings and errors
920 // are emitted).
921 if (Diags.hasErrorOccurred())
922 return;
923
924 switch (D->getKind()) {
925 case Decl::Function:
926 case Decl::Var:
927 EmitGlobal(cast<ValueDecl>(D));
928 break;
929
930 case Decl::Namespace:
Daniel Dunbar952f4732008-08-29 17:28:43 +0000931 ErrorUnsupported(D, "namespace");
Daniel Dunbar27250d32008-08-15 23:26:23 +0000932 break;
933
934 // Objective-C Decls
935
936 // Forward declarations, no (immediate) code generation.
937 case Decl::ObjCClass:
938 case Decl::ObjCCategory:
939 case Decl::ObjCForwardProtocol:
940 case Decl::ObjCInterface:
941 break;
942
943 case Decl::ObjCProtocol:
944 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
945 break;
946
947 case Decl::ObjCCategoryImpl:
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000948 // Categories have properties but don't support synthesize so we
949 // can ignore them here.
950
Daniel Dunbar27250d32008-08-15 23:26:23 +0000951 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
952 break;
953
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000954 case Decl::ObjCImplementation: {
955 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
956 EmitObjCPropertyImplementations(OMD);
957 Runtime->GenerateClass(OMD);
Daniel Dunbar27250d32008-08-15 23:26:23 +0000958 break;
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000959 }
Daniel Dunbar27250d32008-08-15 23:26:23 +0000960 case Decl::ObjCMethod: {
961 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
962 // If this is not a prototype, emit the body.
963 if (OMD->getBody())
964 CodeGenFunction(*this).GenerateObjCMethod(OMD);
965 break;
966 }
Daniel Dunbar27250d32008-08-15 23:26:23 +0000967 case Decl::ObjCCompatibleAlias:
Daniel Dunbar952f4732008-08-29 17:28:43 +0000968 ErrorUnsupported(D, "Objective-C compatible alias");
Daniel Dunbar27250d32008-08-15 23:26:23 +0000969 break;
970
971 case Decl::LinkageSpec: {
972 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
973 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
Daniel Dunbar9503b782008-08-16 00:56:44 +0000974 ErrorUnsupported(LSD, "linkage spec");
Daniel Dunbar27250d32008-08-15 23:26:23 +0000975 // FIXME: implement C++ linkage, C linkage works mostly by C
976 // language reuse already.
977 break;
978 }
979
980 case Decl::FileScopeAsm: {
981 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
982 std::string AsmString(AD->getAsmString()->getStrData(),
983 AD->getAsmString()->getByteLength());
984
985 const std::string &S = getModule().getModuleInlineAsm();
986 if (S.empty())
987 getModule().setModuleInlineAsm(AsmString);
988 else
989 getModule().setModuleInlineAsm(S + '\n' + AsmString);
990 break;
991 }
992
993 default:
994 // Make sure we handled everything we should, every other kind is
995 // a non-top-level decl. FIXME: Would be nice to have an
996 // isTopLevelDeclKind function. Need to recode Decl::Kind to do
997 // that easily.
998 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
999 }
1000}
1001