blob: 7ef4fe19deb1a1d3afd1678ade500ac378584cd8 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Chris Lattner45e8cbd2007-11-28 05:34:05 +000018#include "clang/Basic/LangOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Basic/TargetInfo.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000020#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000022#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "llvm/Intrinsics.h"
24using namespace clang;
25using namespace CodeGen;
26
27
Chris Lattner45e8cbd2007-11-28 05:34:05 +000028CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000029 llvm::Module &M, const llvm::TargetData &TD,
30 Diagnostic &diags)
31 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patel7a4718e2007-10-31 20:01:01 +000032 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Reid Spencer5f016e22007-07-11 17:01:13 +000033
Chris Lattner58c3f9e2007-12-02 06:27:33 +000034
35/// ReplaceMapValuesWith - This is a really slow and bad function that
36/// searches for any entries in GlobalDeclMap that point to OldVal, changing
37/// them to point to NewVal. This is badbadbad, FIXME!
38void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
39 llvm::Constant *NewVal) {
40 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
41 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
42 if (I->second == OldVal) I->second = NewVal;
43}
44
45
Steve Naroff8e74c932007-09-13 21:41:19 +000046llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000047 // See if it is already in the map.
48 llvm::Constant *&Entry = GlobalDeclMap[D];
49 if (Entry) return Entry;
50
51 QualType ASTTy = cast<ValueDecl>(D)->getType();
52 const llvm::Type *Ty = getTypes().ConvertType(ASTTy);
53 if (isa<FunctionDecl>(D)) {
Chris Lattner028380e2007-12-02 05:56:05 +000054 // Check to see if the function already exists.
55 if (llvm::Function *F = getModule().getFunction(D->getName())) {
56 // If so, make sure it is the correct type.
Chris Lattnerfafad832007-12-02 06:30:46 +000057 return Entry = llvm::ConstantExpr::getBitCast(F,
58 llvm::PointerType::get(Ty));
Chris Lattner028380e2007-12-02 05:56:05 +000059 }
60
Reid Spencer5f016e22007-07-11 17:01:13 +000061 // FIXME: param attributes for sext/zext etc.
Chris Lattnerfafad832007-12-02 06:30:46 +000062 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +000063 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
64 D->getName(), &getModule());
65 }
66
67 assert(isa<FileVarDecl>(D) && "Unknown global decl!");
68
Chris Lattnerfafad832007-12-02 06:30:46 +000069 if (llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName())) {
70 // If so, make sure it is the correct type.
71 return Entry = llvm::ConstantExpr::getBitCast(GV,
72 llvm::PointerType::get(Ty));
73
74 }
75
Reid Spencer5f016e22007-07-11 17:01:13 +000076 return Entry = new llvm::GlobalVariable(Ty, false,
77 llvm::GlobalValue::ExternalLinkage,
78 0, D->getName(), &getModule());
79}
80
Chris Lattner88a69ad2007-07-13 05:13:43 +000081void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +000082 // If this is not a prototype, emit the body.
83 if (FD->getBody())
84 CodeGenFunction(*this).GenerateCode(FD);
85}
86
Chris Lattner75cf2882007-11-23 22:07:55 +000087static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
88 CodeGenModule& CGModule);
Devang Patel9e32d4b2007-10-30 21:27:20 +000089
Chris Lattner75cf2882007-11-23 22:07:55 +000090/// GenerateConversionToBool - Generate comparison to zero for conversion to
91/// bool
92static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
93 QualType Source) {
94 if (Source->isRealFloatingType()) {
95 // Compare against 0.0 for fp scalars.
96 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
97 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
98 Zero);
99 }
100
101 assert((Source->isIntegerType() || Source->isPointerType()) &&
102 "Unknown scalar type to convert");
103
104 // Compare against an integer or pointer null.
105 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
106 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
107}
108
109/// GenerateConstantCast - Generates a constant cast to convert the Expression
110/// into the Target type.
111static llvm::Constant *GenerateConstantCast(const Expr *Expression,
112 QualType Target,
113 CodeGenModule& CGModule) {
114 CodeGenTypes& Types = CGModule.getTypes();
115 QualType Source = Expression->getType().getCanonicalType();
116 Target = Target.getCanonicalType();
117
118 assert (!Target->isVoidType());
119
120 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGModule);
121
122 if (Source == Target)
123 return SubExpr;
124
125 // Handle conversions to bool first, they are special: comparisons against 0.
126 if (Target->isBooleanType())
127 return GenerateConversionToBool(SubExpr, Source);
128
129 const llvm::Type *SourceType = Types.ConvertType(Source);
130 const llvm::Type *TargetType = Types.ConvertType(Target);
131
132 // Ignore conversions like int -> uint.
133 if (SubExpr->getType() == TargetType)
134 return SubExpr;
135
136 // Handle pointer conversions next: pointers can only be converted to/from
137 // other pointers and integers.
138 if (isa<llvm::PointerType>(TargetType)) {
139 // The source value may be an integer, or a pointer.
140 if (isa<llvm::PointerType>(SubExpr->getType()))
141 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
142 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
143 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
144 }
145
146 if (isa<llvm::PointerType>(SourceType)) {
147 // Must be an ptr to int cast.
148 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
149 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
150 }
151
152 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
153 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
154 }
155
156 // Finally, we have the arithmetic types: real int/float.
157 if (isa<llvm::IntegerType>(SourceType)) {
158 bool InputSigned = Source->isSignedIntegerType();
159 if (isa<llvm::IntegerType>(TargetType))
160 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
161 InputSigned);
162 else if (InputSigned)
163 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
164 else
165 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
166 }
167
168 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
169 if (isa<llvm::IntegerType>(TargetType)) {
170 if (Target->isSignedIntegerType())
171 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
172 else
173 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
174 }
175
176 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
177 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
178 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
179 else
180 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
181
182 assert (!"Unsupported cast type in global intialiser.");
183 return 0;
184}
185
Chris Lattner75cf2882007-11-23 22:07:55 +0000186/// GenerateAggregateInit - Generate a Constant initaliser for global array or
187/// struct typed variables.
188static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
189 CodeGenModule& CGModule) {
190 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
191 CodeGenTypes& Types = CGModule.getTypes();
Devang Patel9e32d4b2007-10-30 21:27:20 +0000192
193 unsigned NumInitElements = ILE->getNumInits();
194
Chris Lattner75cf2882007-11-23 22:07:55 +0000195 const llvm::CompositeType *CType =
196 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
197 assert(CType);
198 std::vector<llvm::Constant*> Elts;
199
Devang Patel9e32d4b2007-10-30 21:27:20 +0000200 // Copy initializer elements.
201 unsigned i = 0;
202 for (i = 0; i < NumInitElements; ++i) {
Chris Lattner75cf2882007-11-23 22:07:55 +0000203 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGModule);
204 assert (C && "Failed to create initialiser expression");
205 Elts.push_back(C);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000206 }
207
Chris Lattner75cf2882007-11-23 22:07:55 +0000208 if (ILE->getType()->isStructureType())
209 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
210
211 // Initialising an array requires us to automatically initialise any
212 // elements that have not been initialised explicitly
213 const llvm::ArrayType *AType = cast<llvm::ArrayType>(CType);
214 assert(AType);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000215 const llvm::Type *AElemTy = AType->getElementType();
Chris Lattner75cf2882007-11-23 22:07:55 +0000216 unsigned NumArrayElements = AType->getNumElements();
217 // Initialize remaining array elements.
Devang Patel9e32d4b2007-10-30 21:27:20 +0000218 for (; i < NumArrayElements; ++i)
Chris Lattner75cf2882007-11-23 22:07:55 +0000219 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel9e32d4b2007-10-30 21:27:20 +0000220
Chris Lattner75cf2882007-11-23 22:07:55 +0000221 return llvm::ConstantArray::get(AType, Elts);
222}
223
224/// GenerateConstantExpr - Recursively builds a constant initialiser for the
225/// given expression.
226static llvm::Constant *GenerateConstantExpr(const Expr* Expression,
227 CodeGenModule& CGModule) {
228 CodeGenTypes& Types = CGModule.getTypes();
229 ASTContext& Context = CGModule.getContext();
230 assert ((Expression->isConstantExpr(Context, 0) ||
231 Expression->getStmtClass() == Stmt::InitListExprClass) &&
232 "Only constant global initialisers are supported.");
233
234 QualType type = Expression->getType().getCanonicalType();
235
236 if (type->isIntegerType()) {
237 llvm::APSInt
238 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
239 if (Expression->isIntegerConstantExpr(Value, Context)) {
240 return llvm::ConstantInt::get(Value);
241 }
242 }
243
244 switch (Expression->getStmtClass()) {
245 // Generate constant for floating point literal values.
246 case Stmt::FloatingLiteralClass: {
247 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
248 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
249 }
250
251 // Generate constant for string literal values.
252 case Stmt::StringLiteralClass: {
253 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000254 const char *StrData = SLiteral->getStrData();
255 unsigned Len = SLiteral->getByteLength();
256 return CGModule.GetAddrOfConstantString(std::string(StrData,
257 StrData + Len));
Chris Lattner75cf2882007-11-23 22:07:55 +0000258 }
259
260 // Elide parenthesis.
261 case Stmt::ParenExprClass:
262 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(),
263 CGModule);
264
265 // Generate constant for sizeof operator.
266 // FIXME: Need to support AlignOf
267 case Stmt::SizeOfAlignOfTypeExprClass: {
268 const SizeOfAlignOfTypeExpr *SOExpr =
269 cast<SizeOfAlignOfTypeExpr>(Expression);
270 assert (SOExpr->isSizeOf());
271 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
272 }
273
274 // Generate constant cast expressions.
275 case Stmt::CastExprClass:
276 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
277 CGModule);
278
279 case Stmt::ImplicitCastExprClass: {
280 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
281 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGModule);
282 }
283
284 // Generate a constant array access expression
285 // FIXME: Clang's semantic analysis incorrectly prevents array access in
286 // global initialisers, preventing us from testing this.
287 case Stmt::ArraySubscriptExprClass: {
288 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
289 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGModule);
290 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGModule);
291 return llvm::ConstantExpr::getExtractElement(Base, Index);
292 }
293
294 // Generate a constant expression to initialise an aggregate type, such as
295 // an array or struct.
296 case Stmt::InitListExprClass:
297 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGModule);
298
299 default:
300 assert (!"Unsupported expression in global initialiser.");
301 }
302 return 0;
303}
304
Oliver Hunt28247232007-12-02 00:11:25 +0000305llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
306 return GenerateConstantExpr(Expression, *this);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000307}
308
Chris Lattner88a69ad2007-07-13 05:13:43 +0000309void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
310 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
311
312 // If the storage class is external and there is no initializer, just leave it
313 // as a declaration.
314 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
315 return;
316
317 // Otherwise, convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000318 llvm::Constant *Init = 0;
319 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000320 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000321 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000322 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner47f7dbf2007-09-04 02:34:27 +0000323 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner590b6642007-07-15 23:26:56 +0000324 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000325 Init = llvm::ConstantInt::get(Value);
326 }
Devang Patel8e53e722007-10-26 16:31:40 +0000327
Devang Patel9e32d4b2007-10-30 21:27:20 +0000328 if (!Init)
Oliver Hunt28247232007-12-02 00:11:25 +0000329 Init = EmitGlobalInit(D->getInit());
Devang Patel8e53e722007-10-26 16:31:40 +0000330
Devang Patel9e32d4b2007-10-30 21:27:20 +0000331 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner8f32f712007-07-14 00:23:28 +0000332
Chris Lattner88a69ad2007-07-13 05:13:43 +0000333 GV->setInitializer(Init);
334
335 // Set the llvm linkage type as appropriate.
336 // FIXME: This isn't right. This should handle common linkage and other
337 // stuff.
338 switch (D->getStorageClass()) {
339 case VarDecl::Auto:
340 case VarDecl::Register:
341 assert(0 && "Can't have auto or register globals");
342 case VarDecl::None:
343 case VarDecl::Extern:
344 // todo: common
345 break;
346 case VarDecl::Static:
347 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
348 break;
349 }
350}
Reid Spencer5f016e22007-07-11 17:01:13 +0000351
Chris Lattner32b266c2007-07-14 00:16:50 +0000352/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
353/// declarator chain.
354void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
355 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
356 EmitGlobalVar(D);
357}
Reid Spencer5f016e22007-07-11 17:01:13 +0000358
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000359/// getBuiltinLibFunction
360llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
361 if (BuiltinFunctions.size() <= BuiltinID)
362 BuiltinFunctions.resize(BuiltinID);
363
364 // Already available?
365 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
366 if (FunctionSlot)
367 return FunctionSlot;
368
369 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
370
371 // Get the name, skip over the __builtin_ prefix.
372 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
373
374 // Get the type for the builtin.
375 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
376 const llvm::FunctionType *Ty =
377 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
378
379 // FIXME: This has a serious problem with code like this:
380 // void abs() {}
381 // ... __builtin_abs(x);
382 // The two versions of abs will collide. The fix is for the builtin to win,
383 // and for the existing one to be turned into a constantexpr cast of the
384 // builtin. In the case where the existing one is a static function, it
385 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000386 if (llvm::Function *Existing = getModule().getFunction(Name)) {
387 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
388 return FunctionSlot = Existing;
389 assert(Existing == 0 && "FIXME: Name collision");
390 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000391
392 // FIXME: param attributes for sext/zext etc.
393 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
394 Name, &getModule());
395}
396
397
Reid Spencer5f016e22007-07-11 17:01:13 +0000398llvm::Function *CodeGenModule::getMemCpyFn() {
399 if (MemCpyFn) return MemCpyFn;
400 llvm::Intrinsic::ID IID;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000401 uint64_t Size; unsigned Align;
402 Context.Target.getPointerInfo(Size, Align, SourceLocation());
403 switch (Size) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 default: assert(0 && "Unknown ptr width");
405 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
406 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
407 }
408 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
409}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000410
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000411llvm::Constant *CodeGenModule::
412GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000413 llvm::StringMapEntry<llvm::Constant *> &Entry =
414 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
415
416 if (Entry.getValue())
417 return Entry.getValue();
418
419 std::vector<llvm::Constant*> Fields;
420
421 if (!CFConstantStringClassRef) {
422 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
423 Ty = llvm::ArrayType::get(Ty, 0);
424
425 CFConstantStringClassRef =
426 new llvm::GlobalVariable(Ty, false,
427 llvm::GlobalVariable::ExternalLinkage, 0,
428 "__CFConstantStringClassReference",
429 &getModule());
430 }
431
432 // Class pointer.
433 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
434 llvm::Constant *Zeros[] = { Zero, Zero };
435 llvm::Constant *C =
436 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
437 Fields.push_back(C);
438
439 // Flags.
440 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
441 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
442
443 // String pointer.
444 C = llvm::ConstantArray::get(str);
445 C = new llvm::GlobalVariable(C->getType(), true,
446 llvm::GlobalValue::InternalLinkage,
447 C, ".str", &getModule());
448
449 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
450 Fields.push_back(C);
451
452 // String length.
453 Ty = getTypes().ConvertType(getContext().LongTy);
454 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
455
456 // The struct.
457 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
458 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000459 llvm::GlobalVariable *GV =
460 new llvm::GlobalVariable(C->getType(), true,
461 llvm::GlobalVariable::InternalLinkage,
462 C, "", &getModule());
463 GV->setSection("__DATA,__cfstring");
464 Entry.setValue(GV);
465 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000466}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000467
468/// GenerateWritableString -- Creates storage for a string literal
469static llvm::Constant *GenerateStringLiteral(const std::string &str,
470 bool constant,
471 CodeGenModule& CGModule) {
472 // Create Constant for this string literal
473 llvm::Constant *C=llvm::ConstantArray::get(str);
474
475 // Create a global variable for this string
476 C = new llvm::GlobalVariable(C->getType(), constant,
477 llvm::GlobalValue::InternalLinkage,
478 C, ".str", &CGModule.getModule());
479 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
480 llvm::Constant *Zeros[] = { Zero, Zero };
481 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
482 return C;
483}
484
485/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
486/// element of a character array containing the literal.
487llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
488 // Don't share any string literals if writable-strings is turned on.
489 if (Features.WritableStrings)
490 return GenerateStringLiteral(str, false, *this);
491
492 llvm::StringMapEntry<llvm::Constant *> &Entry =
493 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
494
495 if (Entry.getValue())
496 return Entry.getValue();
497
498 // Create a global variable for this.
499 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
500 Entry.setValue(C);
501 return C;
502}