blob: 6b9e69e13dd9fc944278481e9b482a7f19abb2aa [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"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.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 Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000029#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000030#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerdb6be562007-11-28 05:34:05 +000035CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000037 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000038 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000039 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
40 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000041 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000042 Runtime = CreateObjCRuntime(M,
43 getTypes().ConvertType(getContext().IntTy),
44 getTypes().ConvertType(getContext().LongTy));
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000045
46 // If debug info generation is enabled, create the CGDebugInfo object.
47 if (GenerateDebugInfo)
48 DebugInfo = new CGDebugInfo(this);
49 else
50 DebugInfo = NULL;
Chris Lattnercbfb5512008-03-01 08:45:05 +000051}
52
53CodeGenModule::~CodeGenModule() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000054 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000055 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000056 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000057 AddGlobalCtor(ObjCInitFunction);
Chris Lattner753d2592008-03-14 17:18:18 +000058 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000059 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000060 delete Runtime;
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000061 delete DebugInfo;
Chris Lattnerb033c4a2008-04-30 16:05:42 +000062 // Run the verifier to check that the generated code is consistent.
63 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000064}
Chris Lattner4b009652007-07-25 00:24:17 +000065
Chris Lattnercf9c9d02007-12-02 07:19:18 +000066/// WarnUnsupported - Print out a warning that codegen doesn't support the
67/// specified stmt yet.
68void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
69 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
70 "cannot codegen this %0 yet");
71 SourceRange Range = S->getSourceRange();
72 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000073 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000074 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000075}
Chris Lattner0e4755d2007-12-02 06:27:33 +000076
Chris Lattner806a5f52008-01-12 07:05:38 +000077/// WarnUnsupported - Print out a warning that codegen doesn't support the
78/// specified decl yet.
79void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
80 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
81 "cannot codegen this %0 yet");
82 std::string Msg = Type;
83 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
84 &Msg, 1);
85}
86
Dan Gohman4751a3a2008-05-22 00:50:06 +000087/// setVisibility - Set the visibility for the given LLVM GlobalValue
88/// according to the given clang AST visibility value.
89void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
90 VisibilityAttr::VisibilityTypes Vis) {
91 switch (Vis) {
92 default: assert(0 && "Unknown visibility!");
93 case VisibilityAttr::DefaultVisibility:
94 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
95 break;
96 case VisibilityAttr::HiddenVisibility:
97 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
98 break;
99 case VisibilityAttr::ProtectedVisibility:
100 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
101 break;
102 }
103}
104
Chris Lattner753d2592008-03-14 17:18:18 +0000105/// AddGlobalCtor - Add a function to the list that will be called before
106/// main() runs.
107void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
108 // TODO: Type coercion of void()* types.
109 GlobalCtors.push_back(Ctor);
110}
111
Chris Lattnerb326b172008-03-30 23:03:07 +0000112/// EmitGlobalCtors - Generates the array of contsturctor functions to be
113/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +0000114void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +0000115 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000116
Chris Lattner753d2592008-03-14 17:18:18 +0000117 // Get the type of @llvm.global_ctors
118 std::vector<const llvm::Type*> CtorFields;
119 CtorFields.push_back(llvm::IntegerType::get(32));
120 // Constructor function type
121 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000122 llvm::FunctionType* CtorFuncTy =
123 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
124
Chris Lattner753d2592008-03-14 17:18:18 +0000125 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +0000126 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
127 llvm::StructType* CtorStructTy =
128 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000129 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000130 llvm::ArrayType* GlobalCtorsTy =
131 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000132
Chris Lattner753d2592008-03-14 17:18:18 +0000133 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000134 llvm::GlobalVariable *GlobalCtorsVal =
135 new llvm::GlobalVariable(GlobalCtorsTy, false,
136 llvm::GlobalValue::AppendingLinkage,
137 (llvm::Constant*)0, "llvm.global_ctors",
138 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000139
140 // Populate the array
141 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000142 llvm::Constant *MagicNumber =
143 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
144 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000145 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000146 E = GlobalCtors.end(); I != E; ++I) {
147 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000148 StructValues.push_back(MagicNumber);
149 StructValues.push_back(*I);
150
Chris Lattnera18c12e2008-03-19 05:24:56 +0000151 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000152 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000153
154 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
155 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000156}
157
Chris Lattnerb326b172008-03-30 23:03:07 +0000158
159
Nate Begeman52da5c72008-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
Chris Lattner0e4755d2007-12-02 06:27:33 +0000176/// ReplaceMapValuesWith - This is a really slow and bad function that
177/// searches for any entries in GlobalDeclMap that point to OldVal, changing
178/// them to point to NewVal. This is badbadbad, FIXME!
179void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
180 llvm::Constant *NewVal) {
181 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
182 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
183 if (I->second == OldVal) I->second = NewVal;
184}
185
186
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000187llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
188 bool isDefinition) {
189 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000190 llvm::Constant *&Entry = GlobalDeclMap[D];
Eli Friedman5dcae522008-05-30 11:13:18 +0000191 if (!isDefinition && Entry) return Entry;
Eli Friedman725d2be2008-05-20 09:21:07 +0000192
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000193 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
194
195 // Check to see if the function already exists.
196 llvm::Function *F = getModule().getFunction(D->getName());
197 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
198
199 // If it doesn't already exist, just create and return an entry.
200 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000201 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000202 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
203 D->getName(), &getModule());
Nate Begemandc6262e2008-03-09 03:09:36 +0000204
205 // Set the appropriate calling convention for the Function.
206 if (D->getAttr<FastCallAttr>())
207 F->setCallingConv(llvm::CallingConv::Fast);
208 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000209 }
210
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000211 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000212 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000213 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000214
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000215 // If this isn't a definition, just return it casted to the right type.
216 if (!isDefinition)
217 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
218
219 // Otherwise, we have a definition after a prototype with the wrong type.
220 // F is the Function* for the one with the wrong type, we must make a new
221 // Function* and update everything that used F (a declaration) with the new
222 // Function* (which will be a definition).
223 //
224 // This happens if there is a prototype for a function (e.g. "int f()") and
225 // then a definition of a different type (e.g. "int f(int x)"). Start by
226 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000227 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000228 llvm::Function::ExternalLinkage,
229 "", &getModule());
230 NewFn->takeName(F);
231
232 // Replace uses of F with the Function we will endow with a body.
233 llvm::Constant *NewPtrForOldDecl =
234 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
235 F->replaceAllUsesWith(NewPtrForOldDecl);
236
237 // FIXME: Update the globaldeclmap for the previous decl of this name. We
238 // really want a way to walk all of these, but we don't have it yet. This
239 // is incredibly slow!
240 ReplaceMapValuesWith(F, NewPtrForOldDecl);
241
242 // Ok, delete the old function now, which is dead.
243 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
244 F->eraseFromParent();
245
246 // Return the new function which has the right type.
247 return Entry = NewFn;
248}
249
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000250llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
251 bool isDefinition) {
252 assert(D->hasGlobalStorage() && "Not a global variable");
Eli Friedman43a0ce82008-05-30 19:50:47 +0000253 assert(!isDefinition && "This shouldn't be called for definitions!");
254
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000255 // See if it is already in the map.
256 llvm::Constant *&Entry = GlobalDeclMap[D];
257 if (Entry) return Entry;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000258
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000259 QualType ASTTy = D->getType();
260 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000261
262 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000263 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000264
265 // If it doesn't already exist, just create and return an entry.
266 if (GV == 0) {
267 return Entry = new llvm::GlobalVariable(Ty, false,
268 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000269 0, D->getName(), &getModule(), 0,
270 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000271 }
Chris Lattner4b009652007-07-25 00:24:17 +0000272
Eli Friedman43a0ce82008-05-30 19:50:47 +0000273 // Otherwise, it already exists; return the existing version
274 llvm::PointerType *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
275 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
276}
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000277
Chris Lattnerb326b172008-03-30 23:03:07 +0000278void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
279 // If this is not a prototype, emit the body.
280 if (OMD->getBody())
281 CodeGenFunction(*this).GenerateObjCMethod(OMD);
282}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000283void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
284 llvm::SmallVector<std::string, 16> Protocols;
285 for (unsigned i = 0, e = PD->getNumReferencedProtocols() ; i < e ; i++)
286 Protocols.push_back(PD->getReferencedProtocols()[i]->getName());
287 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
288 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
289 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
290 endIter = PD->instmeth_end() ; iter != endIter ; iter++) {
291 std::string TypeStr;
292 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
293 InstanceMethodNames.push_back(
294 GetAddrOfConstantString((*iter)->getSelector().getName()));
295 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
296 }
297 // Collect information about class methods:
298 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
299 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
300 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
301 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
302 std::string TypeStr;
303 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
304 ClassMethodNames.push_back(
305 GetAddrOfConstantString((*iter)->getSelector().getName()));
306 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
307 }
308 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
309 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
310}
311
312void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
313
314 // Collect information about instance methods
315 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
316 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
317 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
318 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
319 std::string TypeStr;
320 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
321 InstanceMethodNames.push_back(
322 GetAddrOfConstantString((*iter)->getSelector().getName()));
323 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
324 }
325
326 // Collect information about class methods
327 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
328 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
329 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
330 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
331 std::string TypeStr;
332 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
333 ClassMethodNames.push_back(
334 GetAddrOfConstantString((*iter)->getSelector().getName()));
335 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
336 }
337
338 // Collect the names of referenced protocols
339 llvm::SmallVector<std::string, 16> Protocols;
340 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OCD->getClassInterface();
341 for (unsigned i=0 ; i<ClassDecl->getNumIntfRefProtocols() ; i++)
342 Protocols.push_back(ClassDecl->getReferencedProtocols()[i]->getName());
343
344 // Generate the category
345 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
346 OCD->getName(), InstanceMethodNames, InstanceMethodTypes,
347 ClassMethodNames, ClassMethodTypes, Protocols);
348}
349
350void CodeGenModule::EmitObjCClassImplementation(
351 const ObjCImplementationDecl *OID) {
352 // Get the superclass name.
353 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
354 const char * SCName = NULL;
355 if (SCDecl) {
356 SCName = SCDecl->getName();
357 }
358
359 // Get the class name
360 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
361 const char * ClassName = ClassDecl->getName();
362
363 // Get the size of instances. For runtimes that support late-bound instances
364 // this should probably be something different (size just of instance
365 // varaibles in this class, not superclasses?).
366 int instanceSize = 0;
367 const llvm::Type *ObjTy;
368 if (!Runtime->LateBoundIVars()) {
369 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
370 instanceSize = TheTargetData.getABITypeSize(ObjTy);
371 }
372
373 // Collect information about instance variables.
374 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
375 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
376 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
377 const llvm::StructLayout *Layout =
378 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
379 ObjTy = llvm::PointerType::getUnqual(ObjTy);
380 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
381 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
382 // Store the name
383 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
384 // Get the type encoding for this ivar
385 std::string TypeStr;
386 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
387 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
388 EncodingRecordTypes);
389 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
390 // Get the offset
391 int offset =
392 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
393 IvarOffsets.push_back(
394 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
395 }
396
397 // Collect information about instance methods
398 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
399 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
400 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
401 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
402 std::string TypeStr;
403 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
404 InstanceMethodNames.push_back(
405 GetAddrOfConstantString((*iter)->getSelector().getName()));
406 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
407 }
408
409 // Collect information about class methods
410 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
411 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
412 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
413 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
414 std::string TypeStr;
415 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
416 ClassMethodNames.push_back(
417 GetAddrOfConstantString((*iter)->getSelector().getName()));
418 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
419 }
420 // Collect the names of referenced protocols
421 llvm::SmallVector<std::string, 16> Protocols;
422 for (unsigned i = 0, e = ClassDecl->getNumIntfRefProtocols() ; i < e ; i++)
423 Protocols.push_back(ClassDecl->getReferencedProtocols()[i]->getName());
424
425 // Generate the category
426 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
427 IvarOffsets, InstanceMethodNames, InstanceMethodTypes, ClassMethodNames,
428 ClassMethodTypes, Protocols);
429}
430
Chris Lattnerb326b172008-03-30 23:03:07 +0000431
Chris Lattner4b009652007-07-25 00:24:17 +0000432void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
433 // If this is not a prototype, emit the body.
Chris Lattner74bf5552008-05-04 02:29:49 +0000434 if (!FD->isThisDeclarationADefinition())
435 return;
436
437 // If the function is a static, defer code generation until later so we can
438 // easily omit unused statics.
439 if (FD->getStorageClass() != FunctionDecl::Static) {
Chris Lattner4b009652007-07-25 00:24:17 +0000440 CodeGenFunction(*this).GenerateCode(FD);
Chris Lattner74bf5552008-05-04 02:29:49 +0000441 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000442 }
Chris Lattner74bf5552008-05-04 02:29:49 +0000443
444 StaticDecls.push_back(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000445}
446
447void CodeGenModule::EmitStatics() {
448 // Emit code for each used static decl encountered. Since a previously unused
449 // static decl may become used during the generation of code for a static
450 // function, iterate until no changes are made.
451 bool Changed;
452 do {
453 Changed = false;
454 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Nate Begemanad320b62008-04-20 06:29:50 +0000455 const Decl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000456
457 // Check if we have used a decl with the same name
458 // FIXME: The AST should have some sort of aggregate decls or
459 // global symbol map.
460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
461 if (!getModule().getFunction(FD->getName()))
462 continue;
463 } else {
464 if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
465 continue;
466 }
467
Nate Begemanad320b62008-04-20 06:29:50 +0000468 // If this is a function decl, generate code for the static function if it
469 // has a body. Otherwise, we must have a var decl for a static global
470 // variable.
471 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
472 if (FD->getBody())
473 CodeGenFunction(*this).GenerateCode(FD);
474 } else {
Nate Begeman91f52012008-04-20 20:38:08 +0000475 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begemanad320b62008-04-20 06:29:50 +0000476 }
477 // Erase the used decl from the list.
478 StaticDecls[i] = StaticDecls.back();
479 StaticDecls.pop_back();
480 --i;
481 --e;
482
483 // Remember that we made a change.
484 Changed = true;
485 }
486 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000487}
488
Anders Carlssond76cead2008-01-26 01:36:00 +0000489llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
490 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000491}
492
Nate Begeman8a704172008-04-19 04:17:09 +0000493/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
494/// annotation information for a given GlobalValue. The annotation struct is
495/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
496/// GlobalValue being annotated. The second filed is thee constant string
497/// created from the AnnotateAttr's annotation. The third field is a constant
498/// string containing the name of the translation unit. The fourth field is
499/// the line number in the file of the annotated value declaration.
500///
501/// FIXME: this does not unique the annotation string constants, as llvm-gcc
502/// appears to.
503///
504llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
505 const AnnotateAttr *AA,
506 unsigned LineNo) {
507 llvm::Module *M = &getModule();
508
509 // get [N x i8] constants for the annotation string, and the filename string
510 // which are the 2nd and 3rd elements of the global annotation structure.
511 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
512 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
513 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
514 true);
515
516 // Get the two global values corresponding to the ConstantArrays we just
517 // created to hold the bytes of the strings.
518 llvm::GlobalValue *annoGV =
519 new llvm::GlobalVariable(anno->getType(), false,
520 llvm::GlobalValue::InternalLinkage, anno,
521 GV->getName() + ".str", M);
522 // translation unit name string, emitted into the llvm.metadata section.
523 llvm::GlobalValue *unitGV =
524 new llvm::GlobalVariable(unit->getType(), false,
525 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
526
527 // Create the ConstantStruct that is the global annotion.
528 llvm::Constant *Fields[4] = {
529 llvm::ConstantExpr::getBitCast(GV, SBP),
530 llvm::ConstantExpr::getBitCast(annoGV, SBP),
531 llvm::ConstantExpr::getBitCast(unitGV, SBP),
532 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
533 };
534 return llvm::ConstantStruct::get(Fields, 4, false);
535}
536
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000537void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000538 // If the VarDecl is a static, defer code generation until later so we can
539 // easily omit unused statics.
540 if (D->getStorageClass() == VarDecl::Static) {
541 StaticDecls.push_back(D);
542 return;
543 }
544
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000545 // If this is just a forward declaration of the variable, don't emit it now,
546 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000547 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
548 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000549
Nate Begemanad320b62008-04-20 06:29:50 +0000550 EmitGlobalVarInit(D);
551}
552
553void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000554 assert(D->hasGlobalStorage() && "Not a global variable");
555
Chris Lattner4b009652007-07-25 00:24:17 +0000556 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000557 QualType ASTTy = D->getType();
558 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
559 const llvm::Type *VarPtrTy =
560 llvm::PointerType::get(VarTy, ASTTy.getAddressSpace());
561
Chris Lattner4b009652007-07-25 00:24:17 +0000562 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000563 // This is a tentative definition; tentative definitions are
564 // implicitly initialized with { 0 }
565 const llvm::Type* InitTy;
566 if (ASTTy->isIncompleteArrayType()) {
567 // An incomplete array is normally [ TYPE x 0 ], but we need
568 // to fix it to [ TYPE x 1 ].
569 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
570 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
571 } else {
572 InitTy = VarTy;
573 }
574 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000575 } else {
576 Init = EmitGlobalInit(D->getInit());
577 }
578 const llvm::Type* InitType = Init->getType();
579
580 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
581
582 if (!GV) {
583 GV = new llvm::GlobalVariable(InitType, false,
584 llvm::GlobalValue::ExternalLinkage,
585 0, D->getName(), &getModule(), 0,
586 ASTTy.getAddressSpace());
587 } else if (GV->getType()->getElementType() != InitType ||
588 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
589 // We have a definition after a prototype with the wrong type.
590 // We must make a new GlobalVariable* and update everything that used OldGV
591 // (a declaration or tentative definition) with the new GlobalVariable*
592 // (which will be a definition).
593 //
594 // This happens if there is a prototype for a global (e.g. "extern int x[];")
595 // and then a definition of a different type (e.g. "int x[10];"). This also
596 // happens when an initializer has a different type from the type of the
597 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000598 //
599 // FIXME: This also ends up happening if there's a definition followed by
600 // a tentative definition! (Although Sema rejects that construct
601 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000602
603 // Save the old global
604 llvm::GlobalVariable *OldGV = GV;
605
606 // Make a new global with the correct type
607 GV = new llvm::GlobalVariable(InitType, false,
608 llvm::GlobalValue::ExternalLinkage,
609 0, D->getName(), &getModule(), 0,
610 ASTTy.getAddressSpace());
611 // Steal the name of the old global
612 GV->takeName(OldGV);
613
614 // Replace all uses of the old global with the new global
615 llvm::Constant *NewPtrForOldDecl =
616 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
617 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
618 // Make sure we don't keep around any stale references to globals
619 // FIXME: This is really slow; we need a better way to walk all
620 // the decls with the same name
621 ReplaceMapValuesWith(OldGV, NewPtrForOldDecl);
622
623 // Erase the old global, since it is no longer used.
624 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000625 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000626
Eli Friedman43a0ce82008-05-30 19:50:47 +0000627 GlobalDeclMap[D] = llvm::ConstantExpr::getBitCast(GV, VarPtrTy);
Devang Patel8b5f5302007-10-26 16:31:40 +0000628
Nate Begeman8a704172008-04-19 04:17:09 +0000629 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
630 SourceManager &SM = Context.getSourceManager();
631 AddAnnotation(EmitAnnotateAttr(GV, AA,
632 SM.getLogicalLineNumber(D->getLocation())));
633 }
634
Chris Lattner4b009652007-07-25 00:24:17 +0000635 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000636
Eli Friedman7008e9a2008-05-30 20:39:54 +0000637 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
638 unsigned Align;
639 if (const IncompleteArrayType* IAT = D->getType()->getAsIncompleteArrayType())
640 Align = Context.getTypeAlign(IAT->getElementType());
641 else
642 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000643 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
644 Align = std::max(Align, AA->getAlignment());
645 }
646 GV->setAlignment(Align / 8);
647
Chris Lattner402b3372008-03-03 03:28:21 +0000648 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000649 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000650 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000651
652 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000653 if (D->getStorageClass() == VarDecl::Static)
654 GV->setLinkage(llvm::Function::InternalLinkage);
655 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000656 GV->setLinkage(llvm::Function::DLLImportLinkage);
657 else if (D->getAttr<DLLExportAttr>())
658 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000659 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000660 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000661 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000662 // FIXME: This isn't right. This should handle common linkage and other
663 // stuff.
664 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000665 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000666 case VarDecl::Auto:
667 case VarDecl::Register:
668 assert(0 && "Can't have auto or register globals");
669 case VarDecl::None:
670 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000671 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000672 break;
673 case VarDecl::Extern:
674 case VarDecl::PrivateExtern:
675 // todo: common
676 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000677 }
Chris Lattner4b009652007-07-25 00:24:17 +0000678 }
679}
680
681/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
682/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000683void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
684 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
685 if (D->isFileVarDecl())
686 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000687}
688
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000689void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
690 // Make sure that this type is translated.
691 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000692}
693
694
Chris Lattnerab862cc2007-08-31 04:31:45 +0000695/// getBuiltinLibFunction
696llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000697 if (BuiltinID > BuiltinFunctions.size())
698 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000699
Chris Lattner9f2d6892007-12-13 00:38:03 +0000700 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
701 // a slot for it.
702 assert(BuiltinID && "Invalid Builtin ID");
703 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000704 if (FunctionSlot)
705 return FunctionSlot;
706
707 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
708
709 // Get the name, skip over the __builtin_ prefix.
710 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
711
712 // Get the type for the builtin.
713 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
714 const llvm::FunctionType *Ty =
715 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
716
717 // FIXME: This has a serious problem with code like this:
718 // void abs() {}
719 // ... __builtin_abs(x);
720 // The two versions of abs will collide. The fix is for the builtin to win,
721 // and for the existing one to be turned into a constantexpr cast of the
722 // builtin. In the case where the existing one is a static function, it
723 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000724 if (llvm::Function *Existing = getModule().getFunction(Name)) {
725 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
726 return FunctionSlot = Existing;
727 assert(Existing == 0 && "FIXME: Name collision");
728 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000729
730 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000731 return FunctionSlot =
732 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
733 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000734}
735
Chris Lattner4b23f942007-12-18 00:25:38 +0000736llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
737 unsigned NumTys) {
738 return llvm::Intrinsic::getDeclaration(&getModule(),
739 (llvm::Intrinsic::ID)IID, Tys, NumTys);
740}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000741
Chris Lattner4b009652007-07-25 00:24:17 +0000742llvm::Function *CodeGenModule::getMemCpyFn() {
743 if (MemCpyFn) return MemCpyFn;
744 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000745 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000746 default: assert(0 && "Unknown ptr width");
747 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
748 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
749 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000750 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000751}
Anders Carlsson36a04872007-08-21 00:21:21 +0000752
Eli Friedman8f08a252008-05-26 12:59:39 +0000753llvm::Function *CodeGenModule::getMemMoveFn() {
754 if (MemMoveFn) return MemMoveFn;
755 llvm::Intrinsic::ID IID;
756 switch (Context.Target.getPointerWidth(0)) {
757 default: assert(0 && "Unknown ptr width");
758 case 32: IID = llvm::Intrinsic::memmove_i32; break;
759 case 64: IID = llvm::Intrinsic::memmove_i64; break;
760 }
761 return MemMoveFn = getIntrinsic(IID);
762}
763
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000764llvm::Function *CodeGenModule::getMemSetFn() {
765 if (MemSetFn) return MemSetFn;
766 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000767 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000768 default: assert(0 && "Unknown ptr width");
769 case 32: IID = llvm::Intrinsic::memset_i32; break;
770 case 64: IID = llvm::Intrinsic::memset_i64; break;
771 }
772 return MemSetFn = getIntrinsic(IID);
773}
Chris Lattner4b23f942007-12-18 00:25:38 +0000774
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000775// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000776llvm::Constant *CodeGenModule::
777GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000778 llvm::StringMapEntry<llvm::Constant *> &Entry =
779 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
780
781 if (Entry.getValue())
782 return Entry.getValue();
783
784 std::vector<llvm::Constant*> Fields;
785
786 if (!CFConstantStringClassRef) {
787 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
788 Ty = llvm::ArrayType::get(Ty, 0);
789
790 CFConstantStringClassRef =
791 new llvm::GlobalVariable(Ty, false,
792 llvm::GlobalVariable::ExternalLinkage, 0,
793 "__CFConstantStringClassReference",
794 &getModule());
795 }
796
797 // Class pointer.
798 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
799 llvm::Constant *Zeros[] = { Zero, Zero };
800 llvm::Constant *C =
801 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
802 Fields.push_back(C);
803
804 // Flags.
805 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
806 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
807
808 // String pointer.
809 C = llvm::ConstantArray::get(str);
810 C = new llvm::GlobalVariable(C->getType(), true,
811 llvm::GlobalValue::InternalLinkage,
812 C, ".str", &getModule());
813
814 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
815 Fields.push_back(C);
816
817 // String length.
818 Ty = getTypes().ConvertType(getContext().LongTy);
819 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
820
821 // The struct.
822 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
823 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000824 llvm::GlobalVariable *GV =
825 new llvm::GlobalVariable(C->getType(), true,
826 llvm::GlobalVariable::InternalLinkage,
827 C, "", &getModule());
828 GV->setSection("__DATA,__cfstring");
829 Entry.setValue(GV);
830 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000831}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000832
Chris Lattnera6dcce32008-02-11 00:02:17 +0000833/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000834static llvm::Constant *GenerateStringLiteral(const std::string &str,
835 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000836 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000837 // Create Constant for this string literal
838 llvm::Constant *C=llvm::ConstantArray::get(str);
839
840 // Create a global variable for this string
841 C = new llvm::GlobalVariable(C->getType(), constant,
842 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000843 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000844 return C;
845}
846
Chris Lattnera6dcce32008-02-11 00:02:17 +0000847/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
848/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000849llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
850 // Don't share any string literals if writable-strings is turned on.
851 if (Features.WritableStrings)
852 return GenerateStringLiteral(str, false, *this);
853
854 llvm::StringMapEntry<llvm::Constant *> &Entry =
855 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
856
857 if (Entry.getValue())
858 return Entry.getValue();
859
860 // Create a global variable for this.
861 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
862 Entry.setValue(C);
863 return C;
864}