blob: d6412a745eac1ba1d5be3fd1954a78a6fa4eeeb2 [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 Lattner2c8569d2007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattner45e8cbd2007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000021#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000023#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "llvm/Intrinsics.h"
Christopher Lambce39faa2007-12-02 08:49:54 +000025#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27using namespace CodeGen;
28
29
Chris Lattner45e8cbd2007-11-28 05:34:05 +000030CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-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 Patel7a4718e2007-10-31 20:01:01 +000034 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Reid Spencer5f016e22007-07-11 17:01:13 +000035
Chris Lattner2c8569d2007-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;
Ted Kremenek9c728dc2007-12-12 22:39:36 +000043 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000044 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000045}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000046
47/// ReplaceMapValuesWith - This is a really slow and bad function that
48/// searches for any entries in GlobalDeclMap that point to OldVal, changing
49/// them to point to NewVal. This is badbadbad, FIXME!
50void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
51 llvm::Constant *NewVal) {
52 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
53 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
54 if (I->second == OldVal) I->second = NewVal;
55}
56
57
Chris Lattner9cd4fe42007-12-02 07:09:19 +000058llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
59 bool isDefinition) {
60 // See if it is already in the map. If so, just return it.
Reid Spencer5f016e22007-07-11 17:01:13 +000061 llvm::Constant *&Entry = GlobalDeclMap[D];
62 if (Entry) return Entry;
63
Chris Lattner9cd4fe42007-12-02 07:09:19 +000064 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
65
66 // Check to see if the function already exists.
67 llvm::Function *F = getModule().getFunction(D->getName());
68 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
69
70 // If it doesn't already exist, just create and return an entry.
71 if (F == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000072 // FIXME: param attributes for sext/zext etc.
73 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
74 D->getName(), &getModule());
75 }
76
Chris Lattner9cd4fe42007-12-02 07:09:19 +000077 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +000078 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +000079 if (PFTy == F->getType()) return Entry = F;
Chris Lattnerfafad832007-12-02 06:30:46 +000080
Chris Lattner9cd4fe42007-12-02 07:09:19 +000081 // If this isn't a definition, just return it casted to the right type.
82 if (!isDefinition)
83 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
84
85 // Otherwise, we have a definition after a prototype with the wrong type.
86 // F is the Function* for the one with the wrong type, we must make a new
87 // Function* and update everything that used F (a declaration) with the new
88 // Function* (which will be a definition).
89 //
90 // This happens if there is a prototype for a function (e.g. "int f()") and
91 // then a definition of a different type (e.g. "int f(int x)"). Start by
92 // making a new function of the correct type, RAUW, then steal the name.
93 llvm::Function *NewFn = new llvm::Function(FTy,
94 llvm::Function::ExternalLinkage,
95 "", &getModule());
96 NewFn->takeName(F);
97
98 // Replace uses of F with the Function we will endow with a body.
99 llvm::Constant *NewPtrForOldDecl =
100 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
101 F->replaceAllUsesWith(NewPtrForOldDecl);
102
103 // FIXME: Update the globaldeclmap for the previous decl of this name. We
104 // really want a way to walk all of these, but we don't have it yet. This
105 // is incredibly slow!
106 ReplaceMapValuesWith(F, NewPtrForOldDecl);
107
108 // Ok, delete the old function now, which is dead.
109 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
110 F->eraseFromParent();
111
112 // Return the new function which has the right type.
113 return Entry = NewFn;
114}
115
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000116llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
117 bool isDefinition) {
118 assert(D->hasGlobalStorage() && "Not a global variable");
119
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000120 // See if it is already in the map.
121 llvm::Constant *&Entry = GlobalDeclMap[D];
122 if (Entry) return Entry;
123
124 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
125
126 // Check to see if the global already exists.
127 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
128
129 // If it doesn't already exist, just create and return an entry.
130 if (GV == 0) {
131 return Entry = new llvm::GlobalVariable(Ty, false,
132 llvm::GlobalValue::ExternalLinkage,
133 0, D->getName(), &getModule());
Chris Lattnerfafad832007-12-02 06:30:46 +0000134 }
135
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000136 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000137 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000138 if (PTy == GV->getType()) return Entry = GV;
139
140 // If this isn't a definition, just return it casted to the right type.
141 if (!isDefinition)
142 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
143
144
145 // Otherwise, we have a definition after a prototype with the wrong type.
146 // GV is the GlobalVariable* for the one with the wrong type, we must make a
147 /// new GlobalVariable* and update everything that used GV (a declaration)
148 // with the new GlobalVariable* (which will be a definition).
149 //
150 // This happens if there is a prototype for a global (e.g. "extern int x[];")
151 // and then a definition of a different type (e.g. "int x[10];"). Start by
152 // making a new global of the correct type, RAUW, then steal the name.
153 llvm::GlobalVariable *NewGV =
154 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
155 0, D->getName(), &getModule());
156 NewGV->takeName(GV);
157
158 // Replace uses of GV with the globalvalue we will endow with a body.
159 llvm::Constant *NewPtrForOldDecl =
160 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
161 GV->replaceAllUsesWith(NewPtrForOldDecl);
162
163 // FIXME: Update the globaldeclmap for the previous decl of this name. We
164 // really want a way to walk all of these, but we don't have it yet. This
165 // is incredibly slow!
166 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
167
168 // Ok, delete the old global now, which is dead.
169 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
170 GV->eraseFromParent();
171
172 // Return the new global which has the right type.
173 return Entry = NewGV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000174}
175
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000176
Chris Lattner88a69ad2007-07-13 05:13:43 +0000177void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 // If this is not a prototype, emit the body.
179 if (FD->getBody())
180 CodeGenFunction(*this).GenerateCode(FD);
181}
182
Chris Lattner75cf2882007-11-23 22:07:55 +0000183static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000184 CodeGenModule &CGM);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000185
Chris Lattner75cf2882007-11-23 22:07:55 +0000186/// GenerateConversionToBool - Generate comparison to zero for conversion to
187/// bool
188static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
189 QualType Source) {
190 if (Source->isRealFloatingType()) {
191 // Compare against 0.0 for fp scalars.
192 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
193 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
194 Zero);
195 }
196
197 assert((Source->isIntegerType() || Source->isPointerType()) &&
198 "Unknown scalar type to convert");
199
200 // Compare against an integer or pointer null.
201 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
202 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
203}
204
205/// GenerateConstantCast - Generates a constant cast to convert the Expression
206/// into the Target type.
207static llvm::Constant *GenerateConstantCast(const Expr *Expression,
Chris Lattner2ea81a82007-12-09 00:36:01 +0000208 QualType Target,
209 CodeGenModule &CGM) {
Chris Lattner2c8569d2007-12-02 07:19:18 +0000210 CodeGenTypes& Types = CGM.getTypes();
Chris Lattner75cf2882007-11-23 22:07:55 +0000211 QualType Source = Expression->getType().getCanonicalType();
212 Target = Target.getCanonicalType();
213
214 assert (!Target->isVoidType());
215
Chris Lattner2c8569d2007-12-02 07:19:18 +0000216 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000217
218 if (Source == Target)
219 return SubExpr;
220
221 // Handle conversions to bool first, they are special: comparisons against 0.
222 if (Target->isBooleanType())
223 return GenerateConversionToBool(SubExpr, Source);
224
225 const llvm::Type *SourceType = Types.ConvertType(Source);
226 const llvm::Type *TargetType = Types.ConvertType(Target);
227
228 // Ignore conversions like int -> uint.
229 if (SubExpr->getType() == TargetType)
230 return SubExpr;
231
232 // Handle pointer conversions next: pointers can only be converted to/from
233 // other pointers and integers.
234 if (isa<llvm::PointerType>(TargetType)) {
235 // The source value may be an integer, or a pointer.
236 if (isa<llvm::PointerType>(SubExpr->getType()))
237 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
238 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
239 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
240 }
241
242 if (isa<llvm::PointerType>(SourceType)) {
243 // Must be an ptr to int cast.
244 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
245 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
246 }
247
248 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
249 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
250 }
251
252 // Finally, we have the arithmetic types: real int/float.
253 if (isa<llvm::IntegerType>(SourceType)) {
254 bool InputSigned = Source->isSignedIntegerType();
255 if (isa<llvm::IntegerType>(TargetType))
256 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
257 InputSigned);
258 else if (InputSigned)
259 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
260 else
261 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
262 }
263
264 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
265 if (isa<llvm::IntegerType>(TargetType)) {
266 if (Target->isSignedIntegerType())
267 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
268 else
269 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
270 }
271
272 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
273 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
274 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
275 else
276 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
277
278 assert (!"Unsupported cast type in global intialiser.");
279 return 0;
280}
281
Chris Lattner75cf2882007-11-23 22:07:55 +0000282/// GenerateAggregateInit - Generate a Constant initaliser for global array or
283/// struct typed variables.
284static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000285 CodeGenModule &CGM) {
Chris Lattner0113edd2007-12-17 05:17:42 +0000286 if (ILE->getType()->isVoidType()) {
287 // FIXME: Remove this when sema of initializers is finished (and the code
288 // below).
289 CGM.WarnUnsupported(ILE, "initializer");
290 return 0;
291 }
292
293 assert((ILE->getType()->isArrayType() || ILE->getType()->isStructureType()) &&
294 "Bad type for init list!");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000295 CodeGenTypes& Types = CGM.getTypes();
Devang Patel9e32d4b2007-10-30 21:27:20 +0000296
297 unsigned NumInitElements = ILE->getNumInits();
Christopher Lambce39faa2007-12-02 08:49:54 +0000298 unsigned NumInitableElts = NumInitElements;
Devang Patel9e32d4b2007-10-30 21:27:20 +0000299
Chris Lattner75cf2882007-11-23 22:07:55 +0000300 const llvm::CompositeType *CType =
301 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
302 assert(CType);
303 std::vector<llvm::Constant*> Elts;
304
Christopher Lambce39faa2007-12-02 08:49:54 +0000305 // Initialising an array requires us to automatically initialise any
306 // elements that have not been initialised explicitly
307 const llvm::ArrayType *AType = 0;
308 const llvm::Type *AElemTy = 0;
309 unsigned NumArrayElements = 0;
310
311 // If this is an array, we may have to truncate the initializer
312 if ((AType = dyn_cast<llvm::ArrayType>(CType))) {
313 NumArrayElements = AType->getNumElements();
314 AElemTy = AType->getElementType();
315 NumInitableElts = std::min(NumInitableElts, NumArrayElements);
316 }
317
Devang Patel9e32d4b2007-10-30 21:27:20 +0000318 // Copy initializer elements.
319 unsigned i = 0;
Christopher Lambce39faa2007-12-02 08:49:54 +0000320 for (i = 0; i < NumInitableElts; ++i) {
Chris Lattner2c8569d2007-12-02 07:19:18 +0000321 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattner0113edd2007-12-17 05:17:42 +0000322 // FIXME: Remove this when sema of initializers is finished (and the code
323 // above).
324 if (C == 0 && ILE->getInit(i)->getType()->isVoidType()) {
325 if (ILE->getType()->isVoidType()) return 0;
326 return llvm::UndefValue::get(CType);
327 }
Chris Lattner75cf2882007-11-23 22:07:55 +0000328 assert (C && "Failed to create initialiser expression");
329 Elts.push_back(C);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000330 }
331
Chris Lattner75cf2882007-11-23 22:07:55 +0000332 if (ILE->getType()->isStructureType())
333 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
Christopher Lambce39faa2007-12-02 08:49:54 +0000334
335 // Make sure we have an array at this point
Chris Lattner75cf2882007-11-23 22:07:55 +0000336 assert(AType);
Christopher Lambce39faa2007-12-02 08:49:54 +0000337
Chris Lattner75cf2882007-11-23 22:07:55 +0000338 // Initialize remaining array elements.
Devang Patel9e32d4b2007-10-30 21:27:20 +0000339 for (; i < NumArrayElements; ++i)
Chris Lattner75cf2882007-11-23 22:07:55 +0000340 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Christopher Lambce39faa2007-12-02 08:49:54 +0000341
Chris Lattner75cf2882007-11-23 22:07:55 +0000342 return llvm::ConstantArray::get(AType, Elts);
343}
344
345/// GenerateConstantExpr - Recursively builds a constant initialiser for the
346/// given expression.
Chris Lattner2c8569d2007-12-02 07:19:18 +0000347static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
348 CodeGenModule &CGM) {
349 CodeGenTypes& Types = CGM.getTypes();
350 ASTContext& Context = CGM.getContext();
Chris Lattner75cf2882007-11-23 22:07:55 +0000351 assert ((Expression->isConstantExpr(Context, 0) ||
352 Expression->getStmtClass() == Stmt::InitListExprClass) &&
353 "Only constant global initialisers are supported.");
354
355 QualType type = Expression->getType().getCanonicalType();
356
357 if (type->isIntegerType()) {
358 llvm::APSInt
359 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
360 if (Expression->isIntegerConstantExpr(Value, Context)) {
361 return llvm::ConstantInt::get(Value);
362 }
363 }
364
365 switch (Expression->getStmtClass()) {
Chris Lattner2ea81a82007-12-09 00:36:01 +0000366 default: break; // default emits a warning and returns bogus value.
367 case Stmt::DeclRefExprClass: {
368 const ValueDecl *Decl = cast<DeclRefExpr>(Expression)->getDecl();
369 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
370 return CGM.GetAddrOfFunctionDecl(FD, false);
371 break;
372 }
373
Chris Lattner75cf2882007-11-23 22:07:55 +0000374 // Generate constant for floating point literal values.
375 case Stmt::FloatingLiteralClass: {
376 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
377 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
378 }
379
380 // Generate constant for string literal values.
381 case Stmt::StringLiteralClass: {
Chris Lattnerdf5eb712007-12-11 01:38:45 +0000382 const StringLiteral *String = cast<StringLiteral>(Expression);
383 const char *StrData = String->getStrData();
384 unsigned Len = String->getByteLength();
385
386 // If the string has a pointer type, emit it as a global and use the pointer
387 // to the global as its value.
388 if (String->getType()->isPointerType())
389 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
390
391 // Otherwise this must be a string initializing an array in a static
392 // initializer. Don't emit it as the address of the string, emit the string
393 // data itself as an inline array.
394 const ConstantArrayType *CAT = String->getType()->getAsConstantArrayType();
395 assert(CAT && "String isn't pointer or array!");
396
397 std::string Str(StrData, StrData + Len);
398 // Null terminate the string before potentially truncating it.
399 // FIXME: What about wchar_t strings?
400 Str.push_back(0);
401
402 uint64_t RealLen = CAT->getSize().getZExtValue();
403 // String or grow the initializer to the required size.
404 if (RealLen != Str.size())
405 Str.resize(RealLen);
406
407 return llvm::ConstantArray::get(Str, false);
Chris Lattner75cf2882007-11-23 22:07:55 +0000408 }
409
410 // Elide parenthesis.
411 case Stmt::ParenExprClass:
Chris Lattner2c8569d2007-12-02 07:19:18 +0000412 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000413
414 // Generate constant for sizeof operator.
415 // FIXME: Need to support AlignOf
416 case Stmt::SizeOfAlignOfTypeExprClass: {
417 const SizeOfAlignOfTypeExpr *SOExpr =
418 cast<SizeOfAlignOfTypeExpr>(Expression);
419 assert (SOExpr->isSizeOf());
420 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
421 }
422
423 // Generate constant cast expressions.
424 case Stmt::CastExprClass:
425 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000426 CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000427
428 case Stmt::ImplicitCastExprClass: {
429 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattner9615bf82007-12-02 07:30:13 +0000430
431 // If this is due to array->pointer conversion, emit the array expression as
432 // an l-value.
433 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
Chris Lattner9a64cf72007-12-02 07:32:25 +0000434 // Note that VLAs can't exist for global variables.
Chris Lattner9615bf82007-12-02 07:30:13 +0000435 // The only thing that can have array type like this is a
436 // DeclRefExpr(FileVarDecl)?
437 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000438 const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
439 llvm::Constant *C = CGM.GetAddrOfGlobalVar(VD, false);
Chris Lattner9615bf82007-12-02 07:30:13 +0000440 assert(isa<llvm::PointerType>(C->getType()) &&
441 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
Chris Lattner9a64cf72007-12-02 07:32:25 +0000442 ->getElementType()));
Chris Lattner9615bf82007-12-02 07:30:13 +0000443 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
444
445 llvm::Constant *Ops[] = {Idx0, Idx0};
Chris Lattner4fd46bc2007-12-10 19:50:32 +0000446 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
447
448 // The resultant pointer type can be implicitly casted to other pointer
449 // types as well, for example void*.
450 const llvm::Type *DestPTy = Types.ConvertType(type);
451 assert(isa<llvm::PointerType>(DestPTy) &&
452 "Only expect implicit cast to pointer");
453 return llvm::ConstantExpr::getBitCast(C, DestPTy);
Chris Lattner9615bf82007-12-02 07:30:13 +0000454 }
455
Chris Lattner2c8569d2007-12-02 07:19:18 +0000456 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000457 }
458
459 // Generate a constant array access expression
460 // FIXME: Clang's semantic analysis incorrectly prevents array access in
461 // global initialisers, preventing us from testing this.
462 case Stmt::ArraySubscriptExprClass: {
463 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattner2c8569d2007-12-02 07:19:18 +0000464 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
465 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000466 return llvm::ConstantExpr::getExtractElement(Base, Index);
467 }
468
469 // Generate a constant expression to initialise an aggregate type, such as
470 // an array or struct.
471 case Stmt::InitListExprClass:
Chris Lattner2c8569d2007-12-02 07:19:18 +0000472 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000473 }
Chris Lattner2ea81a82007-12-09 00:36:01 +0000474
475 CGM.WarnUnsupported(Expression, "initializer");
476 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattner75cf2882007-11-23 22:07:55 +0000477}
478
Oliver Hunt28247232007-12-02 00:11:25 +0000479llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
480 return GenerateConstantExpr(Expression, *this);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000481}
482
Chris Lattner88a69ad2007-07-13 05:13:43 +0000483void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000484 // If this is just a forward declaration of the variable, don't emit it now,
485 // allow it to be emitted lazily on its first use.
Chris Lattner88a69ad2007-07-13 05:13:43 +0000486 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
487 return;
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000488
489 // Get the global, forcing it to be a direct reference.
490 llvm::GlobalVariable *GV =
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000491 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000492
493 // Convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000494 llvm::Constant *Init = 0;
495 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000496 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000497 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000498 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner47f7dbf2007-09-04 02:34:27 +0000499 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner590b6642007-07-15 23:26:56 +0000500 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000501 Init = llvm::ConstantInt::get(Value);
502 }
Devang Patel8e53e722007-10-26 16:31:40 +0000503
Devang Patel9e32d4b2007-10-30 21:27:20 +0000504 if (!Init)
Oliver Hunt28247232007-12-02 00:11:25 +0000505 Init = EmitGlobalInit(D->getInit());
Devang Patel8e53e722007-10-26 16:31:40 +0000506
Chris Lattnerf89dfb22007-12-10 00:05:55 +0000507 assert(GV->getType()->getElementType() == Init->getType() &&
508 "Initializer codegen type mismatch!");
Chris Lattner88a69ad2007-07-13 05:13:43 +0000509 GV->setInitializer(Init);
510
511 // Set the llvm linkage type as appropriate.
512 // FIXME: This isn't right. This should handle common linkage and other
513 // stuff.
514 switch (D->getStorageClass()) {
515 case VarDecl::Auto:
516 case VarDecl::Register:
517 assert(0 && "Can't have auto or register globals");
518 case VarDecl::None:
519 case VarDecl::Extern:
520 // todo: common
521 break;
522 case VarDecl::Static:
523 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
524 break;
525 }
526}
Reid Spencer5f016e22007-07-11 17:01:13 +0000527
Chris Lattner32b266c2007-07-14 00:16:50 +0000528/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
529/// declarator chain.
530void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
531 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
532 EmitGlobalVar(D);
533}
Reid Spencer5f016e22007-07-11 17:01:13 +0000534
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000535/// getBuiltinLibFunction
536llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000537 if (BuiltinID > BuiltinFunctions.size())
538 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000539
Chris Lattner1426fec2007-12-13 00:38:03 +0000540 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
541 // a slot for it.
542 assert(BuiltinID && "Invalid Builtin ID");
543 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000544 if (FunctionSlot)
545 return FunctionSlot;
546
547 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
548
549 // Get the name, skip over the __builtin_ prefix.
550 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
551
552 // Get the type for the builtin.
553 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
554 const llvm::FunctionType *Ty =
555 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
556
557 // FIXME: This has a serious problem with code like this:
558 // void abs() {}
559 // ... __builtin_abs(x);
560 // The two versions of abs will collide. The fix is for the builtin to win,
561 // and for the existing one to be turned into a constantexpr cast of the
562 // builtin. In the case where the existing one is a static function, it
563 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000564 if (llvm::Function *Existing = getModule().getFunction(Name)) {
565 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
566 return FunctionSlot = Existing;
567 assert(Existing == 0 && "FIXME: Name collision");
568 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000569
570 // FIXME: param attributes for sext/zext etc.
571 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
572 Name, &getModule());
573}
574
Chris Lattner7acda7c2007-12-18 00:25:38 +0000575llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
576 unsigned NumTys) {
577 return llvm::Intrinsic::getDeclaration(&getModule(),
578 (llvm::Intrinsic::ID)IID, Tys, NumTys);
579}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000580
Reid Spencer5f016e22007-07-11 17:01:13 +0000581llvm::Function *CodeGenModule::getMemCpyFn() {
582 if (MemCpyFn) return MemCpyFn;
583 llvm::Intrinsic::ID IID;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000584 uint64_t Size; unsigned Align;
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000585 Context.Target.getPointerInfo(Size, Align, FullSourceLoc());
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000586 switch (Size) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000587 default: assert(0 && "Unknown ptr width");
588 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
589 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
590 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000591 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000592}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000593
Chris Lattner7acda7c2007-12-18 00:25:38 +0000594
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000595llvm::Constant *CodeGenModule::
596GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000597 llvm::StringMapEntry<llvm::Constant *> &Entry =
598 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
599
600 if (Entry.getValue())
601 return Entry.getValue();
602
603 std::vector<llvm::Constant*> Fields;
604
605 if (!CFConstantStringClassRef) {
606 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
607 Ty = llvm::ArrayType::get(Ty, 0);
608
609 CFConstantStringClassRef =
610 new llvm::GlobalVariable(Ty, false,
611 llvm::GlobalVariable::ExternalLinkage, 0,
612 "__CFConstantStringClassReference",
613 &getModule());
614 }
615
616 // Class pointer.
617 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
618 llvm::Constant *Zeros[] = { Zero, Zero };
619 llvm::Constant *C =
620 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
621 Fields.push_back(C);
622
623 // Flags.
624 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
625 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
626
627 // String pointer.
628 C = llvm::ConstantArray::get(str);
629 C = new llvm::GlobalVariable(C->getType(), true,
630 llvm::GlobalValue::InternalLinkage,
631 C, ".str", &getModule());
632
633 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
634 Fields.push_back(C);
635
636 // String length.
637 Ty = getTypes().ConvertType(getContext().LongTy);
638 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
639
640 // The struct.
641 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
642 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000643 llvm::GlobalVariable *GV =
644 new llvm::GlobalVariable(C->getType(), true,
645 llvm::GlobalVariable::InternalLinkage,
646 C, "", &getModule());
647 GV->setSection("__DATA,__cfstring");
648 Entry.setValue(GV);
649 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000650}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000651
652/// GenerateWritableString -- Creates storage for a string literal
653static llvm::Constant *GenerateStringLiteral(const std::string &str,
654 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000655 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000656 // Create Constant for this string literal
657 llvm::Constant *C=llvm::ConstantArray::get(str);
658
659 // Create a global variable for this string
660 C = new llvm::GlobalVariable(C->getType(), constant,
661 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000662 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000663 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
664 llvm::Constant *Zeros[] = { Zero, Zero };
665 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
666 return C;
667}
668
669/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
670/// element of a character array containing the literal.
671llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
672 // Don't share any string literals if writable-strings is turned on.
673 if (Features.WritableStrings)
674 return GenerateStringLiteral(str, false, *this);
675
676 llvm::StringMapEntry<llvm::Constant *> &Entry =
677 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
678
679 if (Entry.getValue())
680 return Entry.getValue();
681
682 // Create a global variable for this.
683 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
684 Entry.setValue(C);
685 return C;
686}