blob: a5f7df18d41a985f583c2097ae8ab55c61e17890 [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//
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 Lattnercf9c9d02007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Basic/TargetInfo.h"
21#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000023#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000025#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000026using namespace clang;
27using namespace CodeGen;
28
29
Chris Lattnerdb6be562007-11-28 05:34:05 +000030CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000031 llvm::Module &M, const llvm::TargetData &TD,
32 Diagnostic &diags)
33 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patela8fccb82007-10-31 20:01:01 +000034 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000035
Chris Lattnercf9c9d02007-12-02 07:19:18 +000036/// WarnUnsupported - Print out a warning that codegen doesn't support the
37/// specified stmt yet.
38void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
39 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
40 "cannot codegen this %0 yet");
41 SourceRange Range = S->getSourceRange();
42 std::string Msg = Type;
43 getDiags().Report(S->getLocStart(), DiagID, &Msg, 1, &Range, 1);
44}
Chris Lattner0e4755d2007-12-02 06:27:33 +000045
46/// ReplaceMapValuesWith - This is a really slow and bad function that
47/// searches for any entries in GlobalDeclMap that point to OldVal, changing
48/// them to point to NewVal. This is badbadbad, FIXME!
49void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
50 llvm::Constant *NewVal) {
51 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
52 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
53 if (I->second == OldVal) I->second = NewVal;
54}
55
56
Chris Lattner1a3c1e22007-12-02 07:09:19 +000057llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
58 bool isDefinition) {
59 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +000060 llvm::Constant *&Entry = GlobalDeclMap[D];
61 if (Entry) return Entry;
62
Chris Lattner1a3c1e22007-12-02 07:09:19 +000063 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
64
65 // Check to see if the function already exists.
66 llvm::Function *F = getModule().getFunction(D->getName());
67 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
68
69 // If it doesn't already exist, just create and return an entry.
70 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +000071 // FIXME: param attributes for sext/zext etc.
72 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
73 D->getName(), &getModule());
74 }
75
Chris Lattner1a3c1e22007-12-02 07:09:19 +000076 // If the pointer type matches, just return it.
77 llvm::Type *PFTy = llvm::PointerType::get(Ty);
78 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +000079
Chris Lattner1a3c1e22007-12-02 07:09:19 +000080 // If this isn't a definition, just return it casted to the right type.
81 if (!isDefinition)
82 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
83
84 // Otherwise, we have a definition after a prototype with the wrong type.
85 // F is the Function* for the one with the wrong type, we must make a new
86 // Function* and update everything that used F (a declaration) with the new
87 // Function* (which will be a definition).
88 //
89 // This happens if there is a prototype for a function (e.g. "int f()") and
90 // then a definition of a different type (e.g. "int f(int x)"). Start by
91 // making a new function of the correct type, RAUW, then steal the name.
92 llvm::Function *NewFn = new llvm::Function(FTy,
93 llvm::Function::ExternalLinkage,
94 "", &getModule());
95 NewFn->takeName(F);
96
97 // Replace uses of F with the Function we will endow with a body.
98 llvm::Constant *NewPtrForOldDecl =
99 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
100 F->replaceAllUsesWith(NewPtrForOldDecl);
101
102 // FIXME: Update the globaldeclmap for the previous decl of this name. We
103 // really want a way to walk all of these, but we don't have it yet. This
104 // is incredibly slow!
105 ReplaceMapValuesWith(F, NewPtrForOldDecl);
106
107 // Ok, delete the old function now, which is dead.
108 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
109 F->eraseFromParent();
110
111 // Return the new function which has the right type.
112 return Entry = NewFn;
113}
114
115llvm::Constant *CodeGenModule::GetAddrOfFileVarDecl(const FileVarDecl *D,
116 bool isDefinition) {
117 // See if it is already in the map.
118 llvm::Constant *&Entry = GlobalDeclMap[D];
119 if (Entry) return Entry;
120
121 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
122
123 // Check to see if the global already exists.
124 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
125
126 // If it doesn't already exist, just create and return an entry.
127 if (GV == 0) {
128 return Entry = new llvm::GlobalVariable(Ty, false,
129 llvm::GlobalValue::ExternalLinkage,
130 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000131 }
132
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000133 // If the pointer type matches, just return it.
134 llvm::Type *PTy = llvm::PointerType::get(Ty);
135 if (PTy == GV->getType()) return Entry = GV;
136
137 // If this isn't a definition, just return it casted to the right type.
138 if (!isDefinition)
139 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
140
141
142 // Otherwise, we have a definition after a prototype with the wrong type.
143 // GV is the GlobalVariable* for the one with the wrong type, we must make a
144 /// new GlobalVariable* and update everything that used GV (a declaration)
145 // with the new GlobalVariable* (which will be a definition).
146 //
147 // This happens if there is a prototype for a global (e.g. "extern int x[];")
148 // and then a definition of a different type (e.g. "int x[10];"). Start by
149 // making a new global of the correct type, RAUW, then steal the name.
150 llvm::GlobalVariable *NewGV =
151 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
152 0, D->getName(), &getModule());
153 NewGV->takeName(GV);
154
155 // Replace uses of GV with the globalvalue we will endow with a body.
156 llvm::Constant *NewPtrForOldDecl =
157 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
158 GV->replaceAllUsesWith(NewPtrForOldDecl);
159
160 // FIXME: Update the globaldeclmap for the previous decl of this name. We
161 // really want a way to walk all of these, but we don't have it yet. This
162 // is incredibly slow!
163 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
164
165 // Ok, delete the old global now, which is dead.
166 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
167 GV->eraseFromParent();
168
169 // Return the new global which has the right type.
170 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000171}
172
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000173
Chris Lattner4b009652007-07-25 00:24:17 +0000174void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
175 // If this is not a prototype, emit the body.
176 if (FD->getBody())
177 CodeGenFunction(*this).GenerateCode(FD);
178}
179
Chris Lattnercef01ec2007-11-23 22:07:55 +0000180static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000181 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000182
Chris Lattnercef01ec2007-11-23 22:07:55 +0000183/// GenerateConversionToBool - Generate comparison to zero for conversion to
184/// bool
185static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
186 QualType Source) {
187 if (Source->isRealFloatingType()) {
188 // Compare against 0.0 for fp scalars.
189 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
190 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
191 Zero);
192 }
193
194 assert((Source->isIntegerType() || Source->isPointerType()) &&
195 "Unknown scalar type to convert");
196
197 // Compare against an integer or pointer null.
198 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
199 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
200}
201
202/// GenerateConstantCast - Generates a constant cast to convert the Expression
203/// into the Target type.
204static llvm::Constant *GenerateConstantCast(const Expr *Expression,
Chris Lattner2ab28c92007-12-09 00:36:01 +0000205 QualType Target,
206 CodeGenModule &CGM) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000207 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000208 QualType Source = Expression->getType().getCanonicalType();
209 Target = Target.getCanonicalType();
210
211 assert (!Target->isVoidType());
212
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000213 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000214
215 if (Source == Target)
216 return SubExpr;
217
218 // Handle conversions to bool first, they are special: comparisons against 0.
219 if (Target->isBooleanType())
220 return GenerateConversionToBool(SubExpr, Source);
221
222 const llvm::Type *SourceType = Types.ConvertType(Source);
223 const llvm::Type *TargetType = Types.ConvertType(Target);
224
225 // Ignore conversions like int -> uint.
226 if (SubExpr->getType() == TargetType)
227 return SubExpr;
228
229 // Handle pointer conversions next: pointers can only be converted to/from
230 // other pointers and integers.
231 if (isa<llvm::PointerType>(TargetType)) {
232 // The source value may be an integer, or a pointer.
233 if (isa<llvm::PointerType>(SubExpr->getType()))
234 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
235 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
236 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
237 }
238
239 if (isa<llvm::PointerType>(SourceType)) {
240 // Must be an ptr to int cast.
241 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
242 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
243 }
244
245 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
246 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
247 }
248
249 // Finally, we have the arithmetic types: real int/float.
250 if (isa<llvm::IntegerType>(SourceType)) {
251 bool InputSigned = Source->isSignedIntegerType();
252 if (isa<llvm::IntegerType>(TargetType))
253 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
254 InputSigned);
255 else if (InputSigned)
256 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
257 else
258 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
259 }
260
261 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
262 if (isa<llvm::IntegerType>(TargetType)) {
263 if (Target->isSignedIntegerType())
264 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
265 else
266 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
267 }
268
269 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
270 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
271 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
272 else
273 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
274
275 assert (!"Unsupported cast type in global intialiser.");
276 return 0;
277}
278
Chris Lattnercef01ec2007-11-23 22:07:55 +0000279/// GenerateAggregateInit - Generate a Constant initaliser for global array or
280/// struct typed variables.
281static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000282 CodeGenModule &CGM) {
Chris Lattnercef01ec2007-11-23 22:07:55 +0000283 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000284 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000285
286 unsigned NumInitElements = ILE->getNumInits();
Christopher Lamb6db92f32007-12-02 08:49:54 +0000287 unsigned NumInitableElts = NumInitElements;
Devang Patel08a10cc2007-10-30 21:27:20 +0000288
Chris Lattnercef01ec2007-11-23 22:07:55 +0000289 const llvm::CompositeType *CType =
290 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
291 assert(CType);
292 std::vector<llvm::Constant*> Elts;
293
Christopher Lamb6db92f32007-12-02 08:49:54 +0000294 // Initialising an array requires us to automatically initialise any
295 // elements that have not been initialised explicitly
296 const llvm::ArrayType *AType = 0;
297 const llvm::Type *AElemTy = 0;
298 unsigned NumArrayElements = 0;
299
300 // If this is an array, we may have to truncate the initializer
301 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
302 NumArrayElements = AType->getNumElements();
303 AElemTy = AType->getElementType();
304 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
305 }
306
Devang Patel08a10cc2007-10-30 21:27:20 +0000307 // Copy initializer elements.
308 unsigned i = 0;
Christopher Lamb6db92f32007-12-02 08:49:54 +0000309 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000310 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000311 assert (C && "Failed to create initialiser expression");
312 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000313 }
314
Chris Lattnercef01ec2007-11-23 22:07:55 +0000315 if (ILE->getType()->isStructureType())
316 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000317
318 // Make sure we have an array at this point
Chris Lattnercef01ec2007-11-23 22:07:55 +0000319 assert(AType);
Christopher Lamb6db92f32007-12-02 08:49:54 +0000320
Chris Lattnercef01ec2007-11-23 22:07:55 +0000321 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000322 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000323 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lamb6db92f32007-12-02 08:49:54 +0000324
Chris Lattnercef01ec2007-11-23 22:07:55 +0000325 return llvm::ConstantArray::get(AType, Elts);
326}
327
328/// GenerateConstantExpr - Recursively builds a constant initialiser for the
329/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000330static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
331 CodeGenModule &CGM) {
332 CodeGenTypes& Types = CGM.getTypes();
333 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000334 assert ((Expression->isConstantExpr(Context, 0) ||
335 Expression->getStmtClass() == Stmt::InitListExprClass) &&
336 "Only constant global initialisers are supported.");
337
338 QualType type = Expression->getType().getCanonicalType();
339
340 if (type->isIntegerType()) {
341 llvm::APSInt
342 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
343 if (Expression->isIntegerConstantExpr(Value, Context)) {
344 return llvm::ConstantInt::get(Value);
345 }
346 }
347
348 switch (Expression->getStmtClass()) {
Chris Lattner2ab28c92007-12-09 00:36:01 +0000349 default: break; // default emits a warning and returns bogus value.
350 case Stmt::DeclRefExprClass: {
351 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
352 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
353 return CGM.GetAddrOfFunctionDecl(FD, false);
354 break;
355 }
356
Chris Lattnercef01ec2007-11-23 22:07:55 +0000357 // Generate constant for floating point literal values.
358 case Stmt::FloatingLiteralClass: {
359 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
360 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
361 }
362
363 // Generate constant for string literal values.
364 case Stmt::StringLiteralClass: {
365 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000366 const char *StrData = SLiteral->getStrData();
367 unsigned Len = SLiteral->getByteLength();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000368 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000369 }
370
371 // Elide parenthesis.
372 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000373 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000374
375 // Generate constant for sizeof operator.
376 // FIXME: Need to support AlignOf
377 case Stmt::SizeOfAlignOfTypeExprClass: {
378 const SizeOfAlignOfTypeExpr *SOExpr =
379 cast<SizeOfAlignOfTypeExpr>(Expression);
380 assert (SOExpr->isSizeOf());
381 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
382 }
383
384 // Generate constant cast expressions.
385 case Stmt::CastExprClass:
386 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000387 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000388
389 case Stmt::ImplicitCastExprClass: {
390 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000391
392 // If this is due to array->pointer conversion, emit the array expression as
393 // an l-value.
394 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner21811c72007-12-02 07:32:25 +0000395 // Note that VLAs can't exist for global variables.
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000396 // The only thing that can have array type like this is a
397 // DeclRefExpr(FileVarDecl)?
398 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
399 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
400 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
401 assert(isa<llvm::PointerType>(C->getType()) &&
402 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner21811c72007-12-02 07:32:25 +0000403 ->getElementType()));
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000404 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
405
406 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattnerf67265f2007-12-10 19:50:32 +0000407 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
408
409 // The resultant pointer type can be implicitly casted to other pointer
410 // types as well, for example void*.
411 const llvm::Type *DestPTy = Types.ConvertType(type);
412 assert(isa<llvm::PointerType>(DestPTy) &&
413 "Only expect implicit cast to pointer");
414 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000415 }
416
Chris Lattner72c09732007-12-09 23:49:42 +0000417 // If this is an implicit cast of a string literal to an array type, this
418 // must be a string initializing an array. Don't emit it as the address of
419 // the string, emit the string data itself as an inline array.
420 if (const StringLiteral *String =
421 dyn_cast<StringLiteral>(ICExpr->getSubExpr()))
422 if (const ArrayType *AT = ICExpr->getType()->getAsArrayType()) {
423 // Verify that this is an array of char or wchar. Array of const char*
424 // can be initialized with a string literal, which does not expand the
425 // characters inline.
426 // FIXME: What about wchar_t??
427 if (AT->getElementType()->isCharType()) {
428 const char *StrData = String->getStrData();
Chris Lattner23d853d2007-12-10 00:00:56 +0000429 std::string Str(StrData, StrData + String->getByteLength());
430 // Null terminate the string before potentially truncating it.
431 Str.push_back(0);
432
433 // FIXME: The size of the cast is not always specified yet, fix this
434 // in sema.
435 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
436 uint64_t RealLen = CAT->getSize().getZExtValue();
437 // String or grow the initializer to the required size.
438 if (RealLen != Str.size())
439 Str.resize(RealLen);
440 }
441
442
443 return llvm::ConstantArray::get(Str, false);
Chris Lattner72c09732007-12-09 23:49:42 +0000444 }
445 }
446
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000447 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000448 }
449
450 // Generate a constant array access expression
451 // FIXME: Clang's semantic analysis incorrectly prevents array access in
452 // global initialisers, preventing us from testing this.
453 case Stmt::ArraySubscriptExprClass: {
454 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000455 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
456 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000457 return llvm::ConstantExpr::getExtractElement(Base, Index);
458 }
459
460 // Generate a constant expression to initialise an aggregate type, such as
461 // an array or struct.
462 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000463 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000464 }
Chris Lattner2ab28c92007-12-09 00:36:01 +0000465
466 CGM.WarnUnsupported(Expression, "initializer");
467 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000468}
469
Oliver Hunt253e0a72007-12-02 00:11:25 +0000470llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
471 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000472}
473
Chris Lattner4b009652007-07-25 00:24:17 +0000474void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000475 // If this is just a forward declaration of the variable, don't emit it now,
476 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000477 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
478 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000479
480 // Get the global, forcing it to be a direct reference.
481 llvm::GlobalVariable *GV =
482 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
483
484 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000485 llvm::Constant *Init = 0;
486 if (D->getInit() == 0) {
487 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
488 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000489 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000490 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000491 if (D->getInit()->isIntegerConstantExpr(Value, Context))
492 Init = llvm::ConstantInt::get(Value);
493 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000494
Devang Patel08a10cc2007-10-30 21:27:20 +0000495 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000496 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000497
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000498 assert(GV->getType()->getElementType() == Init->getType() &&
499 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000500 GV->setInitializer(Init);
501
502 // Set the llvm linkage type as appropriate.
503 // FIXME: This isn't right. This should handle common linkage and other
504 // stuff.
505 switch (D->getStorageClass()) {
506 case VarDecl::Auto:
507 case VarDecl::Register:
508 assert(0 && "Can't have auto or register globals");
509 case VarDecl::None:
510 case VarDecl::Extern:
511 // todo: common
512 break;
513 case VarDecl::Static:
514 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
515 break;
516 }
517}
518
519/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
520/// declarator chain.
521void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
522 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
523 EmitGlobalVar(D);
524}
525
Chris Lattnerab862cc2007-08-31 04:31:45 +0000526/// getBuiltinLibFunction
527llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
528 if (BuiltinFunctions.size() <= BuiltinID)
529 BuiltinFunctions.resize(BuiltinID);
530
531 // Already available?
532 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
533 if (FunctionSlot)
534 return FunctionSlot;
535
536 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
537
538 // Get the name, skip over the __builtin_ prefix.
539 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
540
541 // Get the type for the builtin.
542 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
543 const llvm::FunctionType *Ty =
544 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
545
546 // FIXME: This has a serious problem with code like this:
547 // void abs() {}
548 // ... __builtin_abs(x);
549 // The two versions of abs will collide. The fix is for the builtin to win,
550 // and for the existing one to be turned into a constantexpr cast of the
551 // builtin. In the case where the existing one is a static function, it
552 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000553 if (llvm::Function *Existing = getModule().getFunction(Name)) {
554 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
555 return FunctionSlot = Existing;
556 assert(Existing == 0 && "FIXME: Name collision");
557 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000558
559 // FIXME: param attributes for sext/zext etc.
560 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
561 Name, &getModule());
562}
563
564
Chris Lattner4b009652007-07-25 00:24:17 +0000565llvm::Function *CodeGenModule::getMemCpyFn() {
566 if (MemCpyFn) return MemCpyFn;
567 llvm::Intrinsic::ID IID;
568 uint64_t Size; unsigned Align;
569 Context.Target.getPointerInfo(Size, Align, SourceLocation());
570 switch (Size) {
571 default: assert(0 && "Unknown ptr width");
572 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
573 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
574 }
575 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
576}
Anders Carlsson36a04872007-08-21 00:21:21 +0000577
Chris Lattnerab862cc2007-08-31 04:31:45 +0000578llvm::Constant *CodeGenModule::
579GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000580 llvm::StringMapEntry<llvm::Constant *> &Entry =
581 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
582
583 if (Entry.getValue())
584 return Entry.getValue();
585
586 std::vector<llvm::Constant*> Fields;
587
588 if (!CFConstantStringClassRef) {
589 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
590 Ty = llvm::ArrayType::get(Ty, 0);
591
592 CFConstantStringClassRef =
593 new llvm::GlobalVariable(Ty, false,
594 llvm::GlobalVariable::ExternalLinkage, 0,
595 "__CFConstantStringClassReference",
596 &getModule());
597 }
598
599 // Class pointer.
600 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
601 llvm::Constant *Zeros[] = { Zero, Zero };
602 llvm::Constant *C =
603 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
604 Fields.push_back(C);
605
606 // Flags.
607 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
608 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
609
610 // String pointer.
611 C = llvm::ConstantArray::get(str);
612 C = new llvm::GlobalVariable(C->getType(), true,
613 llvm::GlobalValue::InternalLinkage,
614 C, ".str", &getModule());
615
616 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
617 Fields.push_back(C);
618
619 // String length.
620 Ty = getTypes().ConvertType(getContext().LongTy);
621 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
622
623 // The struct.
624 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
625 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000626 llvm::GlobalVariable *GV =
627 new llvm::GlobalVariable(C->getType(), true,
628 llvm::GlobalVariable::InternalLinkage,
629 C, "", &getModule());
630 GV->setSection("__DATA,__cfstring");
631 Entry.setValue(GV);
632 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000633}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000634
635/// GenerateWritableString -- Creates storage for a string literal
636static llvm::Constant *GenerateStringLiteral(const std::string &str,
637 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000638 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000639 // Create Constant for this string literal
640 llvm::Constant *C=llvm::ConstantArray::get(str);
641
642 // Create a global variable for this string
643 C = new llvm::GlobalVariable(C->getType(), constant,
644 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000645 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000646 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
647 llvm::Constant *Zeros[] = { Zero, Zero };
648 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
649 return C;
650}
651
652/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
653/// element of a character array containing the literal.
654llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
655 // Don't share any string literals if writable-strings is turned on.
656 if (Features.WritableStrings)
657 return GenerateStringLiteral(str, false, *this);
658
659 llvm::StringMapEntry<llvm::Constant *> &Entry =
660 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
661
662 if (Entry.getValue())
663 return Entry.getValue();
664
665 // Create a global variable for this.
666 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
667 Entry.setValue(C);
668 return C;
669}