blob: 97ff705a39fcdddd742b8139db69762eaca59642 [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"
25using namespace clang;
26using namespace CodeGen;
27
28
Chris Lattnerdb6be562007-11-28 05:34:05 +000029CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000030 llvm::Module &M, const llvm::TargetData &TD,
31 Diagnostic &diags)
32 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Devang Patela8fccb82007-10-31 20:01:01 +000033 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000034
Chris Lattnercf9c9d02007-12-02 07:19:18 +000035/// WarnUnsupported - Print out a warning that codegen doesn't support the
36/// specified stmt yet.
37void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
38 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
39 "cannot codegen this %0 yet");
40 SourceRange Range = S->getSourceRange();
41 std::string Msg = Type;
42 getDiags().Report(S->getLocStart(), DiagID, &Msg, 1, &Range, 1);
43}
Chris Lattner0e4755d2007-12-02 06:27:33 +000044
45/// ReplaceMapValuesWith - This is a really slow and bad function that
46/// searches for any entries in GlobalDeclMap that point to OldVal, changing
47/// them to point to NewVal. This is badbadbad, FIXME!
48void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
49 llvm::Constant *NewVal) {
50 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
51 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
52 if (I->second == OldVal) I->second = NewVal;
53}
54
55
Chris Lattner1a3c1e22007-12-02 07:09:19 +000056llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
57 bool isDefinition) {
58 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +000059 llvm::Constant *&Entry = GlobalDeclMap[D];
60 if (Entry) return Entry;
61
Chris Lattner1a3c1e22007-12-02 07:09:19 +000062 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
63
64 // Check to see if the function already exists.
65 llvm::Function *F = getModule().getFunction(D->getName());
66 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
67
68 // If it doesn't already exist, just create and return an entry.
69 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +000070 // FIXME: param attributes for sext/zext etc.
71 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
72 D->getName(), &getModule());
73 }
74
Chris Lattner1a3c1e22007-12-02 07:09:19 +000075 // If the pointer type matches, just return it.
76 llvm::Type *PFTy = llvm::PointerType::get(Ty);
77 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +000078
Chris Lattner1a3c1e22007-12-02 07:09:19 +000079 // If this isn't a definition, just return it casted to the right type.
80 if (!isDefinition)
81 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
82
83 // Otherwise, we have a definition after a prototype with the wrong type.
84 // F is the Function* for the one with the wrong type, we must make a new
85 // Function* and update everything that used F (a declaration) with the new
86 // Function* (which will be a definition).
87 //
88 // This happens if there is a prototype for a function (e.g. "int f()") and
89 // then a definition of a different type (e.g. "int f(int x)"). Start by
90 // making a new function of the correct type, RAUW, then steal the name.
91 llvm::Function *NewFn = new llvm::Function(FTy,
92 llvm::Function::ExternalLinkage,
93 "", &getModule());
94 NewFn->takeName(F);
95
96 // Replace uses of F with the Function we will endow with a body.
97 llvm::Constant *NewPtrForOldDecl =
98 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
99 F->replaceAllUsesWith(NewPtrForOldDecl);
100
101 // FIXME: Update the globaldeclmap for the previous decl of this name. We
102 // really want a way to walk all of these, but we don't have it yet. This
103 // is incredibly slow!
104 ReplaceMapValuesWith(F, NewPtrForOldDecl);
105
106 // Ok, delete the old function now, which is dead.
107 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
108 F->eraseFromParent();
109
110 // Return the new function which has the right type.
111 return Entry = NewFn;
112}
113
114llvm::Constant *CodeGenModule::GetAddrOfFileVarDecl(const FileVarDecl *D,
115 bool isDefinition) {
116 // See if it is already in the map.
117 llvm::Constant *&Entry = GlobalDeclMap[D];
118 if (Entry) return Entry;
119
120 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
121
122 // Check to see if the global already exists.
123 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName());
124
125 // If it doesn't already exist, just create and return an entry.
126 if (GV == 0) {
127 return Entry = new llvm::GlobalVariable(Ty, false,
128 llvm::GlobalValue::ExternalLinkage,
129 0, D->getName(), &getModule());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000130 }
131
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000132 // If the pointer type matches, just return it.
133 llvm::Type *PTy = llvm::PointerType::get(Ty);
134 if (PTy == GV->getType()) return Entry = GV;
135
136 // If this isn't a definition, just return it casted to the right type.
137 if (!isDefinition)
138 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
139
140
141 // Otherwise, we have a definition after a prototype with the wrong type.
142 // GV is the GlobalVariable* for the one with the wrong type, we must make a
143 /// new GlobalVariable* and update everything that used GV (a declaration)
144 // with the new GlobalVariable* (which will be a definition).
145 //
146 // This happens if there is a prototype for a global (e.g. "extern int x[];")
147 // and then a definition of a different type (e.g. "int x[10];"). Start by
148 // making a new global of the correct type, RAUW, then steal the name.
149 llvm::GlobalVariable *NewGV =
150 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
151 0, D->getName(), &getModule());
152 NewGV->takeName(GV);
153
154 // Replace uses of GV with the globalvalue we will endow with a body.
155 llvm::Constant *NewPtrForOldDecl =
156 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
157 GV->replaceAllUsesWith(NewPtrForOldDecl);
158
159 // FIXME: Update the globaldeclmap for the previous decl of this name. We
160 // really want a way to walk all of these, but we don't have it yet. This
161 // is incredibly slow!
162 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
163
164 // Ok, delete the old global now, which is dead.
165 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
166 GV->eraseFromParent();
167
168 // Return the new global which has the right type.
169 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000170}
171
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000172
Chris Lattner4b009652007-07-25 00:24:17 +0000173void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
174 // If this is not a prototype, emit the body.
175 if (FD->getBody())
176 CodeGenFunction(*this).GenerateCode(FD);
177}
178
Chris Lattnercef01ec2007-11-23 22:07:55 +0000179static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000180 CodeGenModule &CGM);
Devang Patel08a10cc2007-10-30 21:27:20 +0000181
Chris Lattnercef01ec2007-11-23 22:07:55 +0000182/// GenerateConversionToBool - Generate comparison to zero for conversion to
183/// bool
184static llvm::Constant *GenerateConversionToBool(llvm::Constant *Expression,
185 QualType Source) {
186 if (Source->isRealFloatingType()) {
187 // Compare against 0.0 for fp scalars.
188 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
189 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Expression,
190 Zero);
191 }
192
193 assert((Source->isIntegerType() || Source->isPointerType()) &&
194 "Unknown scalar type to convert");
195
196 // Compare against an integer or pointer null.
197 llvm::Constant *Zero = llvm::Constant::getNullValue(Expression->getType());
198 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Expression, Zero);
199}
200
201/// GenerateConstantCast - Generates a constant cast to convert the Expression
202/// into the Target type.
203static llvm::Constant *GenerateConstantCast(const Expr *Expression,
204 QualType Target,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000205 CodeGenModule &CGM) {
206 CodeGenTypes& Types = CGM.getTypes();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000207 QualType Source = Expression->getType().getCanonicalType();
208 Target = Target.getCanonicalType();
209
210 assert (!Target->isVoidType());
211
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000212 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000213
214 if (Source == Target)
215 return SubExpr;
216
217 // Handle conversions to bool first, they are special: comparisons against 0.
218 if (Target->isBooleanType())
219 return GenerateConversionToBool(SubExpr, Source);
220
221 const llvm::Type *SourceType = Types.ConvertType(Source);
222 const llvm::Type *TargetType = Types.ConvertType(Target);
223
224 // Ignore conversions like int -> uint.
225 if (SubExpr->getType() == TargetType)
226 return SubExpr;
227
228 // Handle pointer conversions next: pointers can only be converted to/from
229 // other pointers and integers.
230 if (isa<llvm::PointerType>(TargetType)) {
231 // The source value may be an integer, or a pointer.
232 if (isa<llvm::PointerType>(SubExpr->getType()))
233 return llvm::ConstantExpr::getBitCast(SubExpr, TargetType);
234 assert(Source->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
235 return llvm::ConstantExpr::getIntToPtr(SubExpr, TargetType);
236 }
237
238 if (isa<llvm::PointerType>(SourceType)) {
239 // Must be an ptr to int cast.
240 assert(isa<llvm::IntegerType>(TargetType) && "not ptr->int?");
241 return llvm::ConstantExpr::getPtrToInt(SubExpr, TargetType);
242 }
243
244 if (Source->isRealFloatingType() && Target->isRealFloatingType()) {
245 return llvm::ConstantExpr::getFPCast(SubExpr, TargetType);
246 }
247
248 // Finally, we have the arithmetic types: real int/float.
249 if (isa<llvm::IntegerType>(SourceType)) {
250 bool InputSigned = Source->isSignedIntegerType();
251 if (isa<llvm::IntegerType>(TargetType))
252 return llvm::ConstantExpr::getIntegerCast(SubExpr, TargetType,
253 InputSigned);
254 else if (InputSigned)
255 return llvm::ConstantExpr::getSIToFP(SubExpr, TargetType);
256 else
257 return llvm::ConstantExpr::getUIToFP(SubExpr, TargetType);
258 }
259
260 assert(SubExpr->getType()->isFloatingPoint() && "Unknown real conversion");
261 if (isa<llvm::IntegerType>(TargetType)) {
262 if (Target->isSignedIntegerType())
263 return llvm::ConstantExpr::getFPToSI(SubExpr, TargetType);
264 else
265 return llvm::ConstantExpr::getFPToUI(SubExpr, TargetType);
266 }
267
268 assert(TargetType->isFloatingPoint() && "Unknown real conversion");
269 if (TargetType->getTypeID() < SubExpr->getType()->getTypeID())
270 return llvm::ConstantExpr::getFPTrunc(SubExpr, TargetType);
271 else
272 return llvm::ConstantExpr::getFPExtend(SubExpr, TargetType);
273
274 assert (!"Unsupported cast type in global intialiser.");
275 return 0;
276}
277
Chris Lattnercef01ec2007-11-23 22:07:55 +0000278/// GenerateAggregateInit - Generate a Constant initaliser for global array or
279/// struct typed variables.
280static llvm::Constant *GenerateAggregateInit(const InitListExpr *ILE,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000281 CodeGenModule &CGM) {
Chris Lattnercef01ec2007-11-23 22:07:55 +0000282 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000283 CodeGenTypes& Types = CGM.getTypes();
Devang Patel08a10cc2007-10-30 21:27:20 +0000284
285 unsigned NumInitElements = ILE->getNumInits();
286
Chris Lattnercef01ec2007-11-23 22:07:55 +0000287 const llvm::CompositeType *CType =
288 cast<llvm::CompositeType>(Types.ConvertType(ILE->getType()));
289 assert(CType);
290 std::vector<llvm::Constant*> Elts;
291
Devang Patel08a10cc2007-10-30 21:27:20 +0000292 // Copy initializer elements.
293 unsigned i = 0;
294 for (i = 0; i < NumInitElements; ++i) {
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000295 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000296 assert (C && "Failed to create initialiser expression");
297 Elts.push_back(C);
Devang Patel08a10cc2007-10-30 21:27:20 +0000298 }
299
Chris Lattnercef01ec2007-11-23 22:07:55 +0000300 if (ILE->getType()->isStructureType())
301 return llvm::ConstantStruct::get(cast<llvm::StructType>(CType), Elts);
302
303 // Initialising an array requires us to automatically initialise any
304 // elements that have not been initialised explicitly
305 const llvm::ArrayType *AType = cast<llvm::ArrayType>(CType);
306 assert(AType);
Devang Patel08a10cc2007-10-30 21:27:20 +0000307 const llvm::Type *AElemTy = AType->getElementType();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000308 unsigned NumArrayElements = AType->getNumElements();
309 // Initialize remaining array elements.
Devang Patel08a10cc2007-10-30 21:27:20 +0000310 for (; i < NumArrayElements; ++i)
Chris Lattnercef01ec2007-11-23 22:07:55 +0000311 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel08a10cc2007-10-30 21:27:20 +0000312
Chris Lattnercef01ec2007-11-23 22:07:55 +0000313 return llvm::ConstantArray::get(AType, Elts);
314}
315
316/// GenerateConstantExpr - Recursively builds a constant initialiser for the
317/// given expression.
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000318static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
319 CodeGenModule &CGM) {
320 CodeGenTypes& Types = CGM.getTypes();
321 ASTContext& Context = CGM.getContext();
Chris Lattnercef01ec2007-11-23 22:07:55 +0000322 assert ((Expression->isConstantExpr(Context, 0) ||
323 Expression->getStmtClass() == Stmt::InitListExprClass) &&
324 "Only constant global initialisers are supported.");
325
326 QualType type = Expression->getType().getCanonicalType();
327
328 if (type->isIntegerType()) {
329 llvm::APSInt
330 Value(static_cast<uint32_t>(Context.getTypeSize(type, SourceLocation())));
331 if (Expression->isIntegerConstantExpr(Value, Context)) {
332 return llvm::ConstantInt::get(Value);
333 }
334 }
335
336 switch (Expression->getStmtClass()) {
337 // Generate constant for floating point literal values.
338 case Stmt::FloatingLiteralClass: {
339 const FloatingLiteral *FLiteral = cast<FloatingLiteral>(Expression);
340 return llvm::ConstantFP::get(Types.ConvertType(type), FLiteral->getValue());
341 }
342
343 // Generate constant for string literal values.
344 case Stmt::StringLiteralClass: {
345 const StringLiteral *SLiteral = cast<StringLiteral>(Expression);
Chris Lattnerdb6be562007-11-28 05:34:05 +0000346 const char *StrData = SLiteral->getStrData();
347 unsigned Len = SLiteral->getByteLength();
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000348 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000349 }
350
351 // Elide parenthesis.
352 case Stmt::ParenExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000353 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000354
355 // Generate constant for sizeof operator.
356 // FIXME: Need to support AlignOf
357 case Stmt::SizeOfAlignOfTypeExprClass: {
358 const SizeOfAlignOfTypeExpr *SOExpr =
359 cast<SizeOfAlignOfTypeExpr>(Expression);
360 assert (SOExpr->isSizeOf());
361 return llvm::ConstantExpr::getSizeOf(Types.ConvertType(type));
362 }
363
364 // Generate constant cast expressions.
365 case Stmt::CastExprClass:
366 return GenerateConstantCast(cast<CastExpr>(Expression)->getSubExpr(), type,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000367 CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000368
369 case Stmt::ImplicitCastExprClass: {
370 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattnerb656f7d2007-12-02 07:30:13 +0000371
372 // If this is due to array->pointer conversion, emit the array expression as
373 // an l-value.
374 if (ICExpr->getSubExpr()->getType()->isArrayType()) {
375 // FIXME: For now we assume that all source arrays map to LLVM arrays.
376 // This will not true when we add support for VLAs.
377 // The only thing that can have array type like this is a
378 // DeclRefExpr(FileVarDecl)?
379 const DeclRefExpr *DRE = cast<DeclRefExpr>(ICExpr->getSubExpr());
380 const FileVarDecl *FVD = cast<FileVarDecl>(DRE->getDecl());
381 llvm::Constant *C = CGM.GetAddrOfFileVarDecl(FVD, false);
382 assert(isa<llvm::PointerType>(C->getType()) &&
383 isa<llvm::ArrayType>(cast<llvm::PointerType>(C->getType())
384 ->getElementType()) &&
385 "Doesn't support VLAs yet!");
386 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
387
388 llvm::Constant *Ops[] = {Idx0, Idx0};
389 return llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
390 }
391
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000392 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000393 }
394
395 // Generate a constant array access expression
396 // FIXME: Clang's semantic analysis incorrectly prevents array access in
397 // global initialisers, preventing us from testing this.
398 case Stmt::ArraySubscriptExprClass: {
399 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000400 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
401 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000402 return llvm::ConstantExpr::getExtractElement(Base, Index);
403 }
404
405 // Generate a constant expression to initialise an aggregate type, such as
406 // an array or struct.
407 case Stmt::InitListExprClass:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000408 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattnercef01ec2007-11-23 22:07:55 +0000409
410 default:
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000411 CGM.WarnUnsupported(Expression, "initializer");
412 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattnercef01ec2007-11-23 22:07:55 +0000413 }
Chris Lattnercef01ec2007-11-23 22:07:55 +0000414}
415
Oliver Hunt253e0a72007-12-02 00:11:25 +0000416llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
417 return GenerateConstantExpr(Expression, *this);
Devang Patel08a10cc2007-10-30 21:27:20 +0000418}
419
Chris Lattner4b009652007-07-25 00:24:17 +0000420void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000421 // If this is just a forward declaration of the variable, don't emit it now,
422 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000423 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
424 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000425
426 // Get the global, forcing it to be a direct reference.
427 llvm::GlobalVariable *GV =
428 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
429
430 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000431 llvm::Constant *Init = 0;
432 if (D->getInit() == 0) {
433 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
434 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000435 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000436 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000437 if (D->getInit()->isIntegerConstantExpr(Value, Context))
438 Init = llvm::ConstantInt::get(Value);
439 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000440
Devang Patel08a10cc2007-10-30 21:27:20 +0000441 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000442 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000443
Devang Patel08a10cc2007-10-30 21:27:20 +0000444 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000445
446 GV->setInitializer(Init);
447
448 // Set the llvm linkage type as appropriate.
449 // FIXME: This isn't right. This should handle common linkage and other
450 // stuff.
451 switch (D->getStorageClass()) {
452 case VarDecl::Auto:
453 case VarDecl::Register:
454 assert(0 && "Can't have auto or register globals");
455 case VarDecl::None:
456 case VarDecl::Extern:
457 // todo: common
458 break;
459 case VarDecl::Static:
460 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
461 break;
462 }
463}
464
465/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
466/// declarator chain.
467void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
468 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
469 EmitGlobalVar(D);
470}
471
Chris Lattnerab862cc2007-08-31 04:31:45 +0000472/// getBuiltinLibFunction
473llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
474 if (BuiltinFunctions.size() <= BuiltinID)
475 BuiltinFunctions.resize(BuiltinID);
476
477 // Already available?
478 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
479 if (FunctionSlot)
480 return FunctionSlot;
481
482 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
483
484 // Get the name, skip over the __builtin_ prefix.
485 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
486
487 // Get the type for the builtin.
488 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
489 const llvm::FunctionType *Ty =
490 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
491
492 // FIXME: This has a serious problem with code like this:
493 // void abs() {}
494 // ... __builtin_abs(x);
495 // The two versions of abs will collide. The fix is for the builtin to win,
496 // and for the existing one to be turned into a constantexpr cast of the
497 // builtin. In the case where the existing one is a static function, it
498 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000499 if (llvm::Function *Existing = getModule().getFunction(Name)) {
500 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
501 return FunctionSlot = Existing;
502 assert(Existing == 0 && "FIXME: Name collision");
503 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000504
505 // FIXME: param attributes for sext/zext etc.
506 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
507 Name, &getModule());
508}
509
510
Chris Lattner4b009652007-07-25 00:24:17 +0000511llvm::Function *CodeGenModule::getMemCpyFn() {
512 if (MemCpyFn) return MemCpyFn;
513 llvm::Intrinsic::ID IID;
514 uint64_t Size; unsigned Align;
515 Context.Target.getPointerInfo(Size, Align, SourceLocation());
516 switch (Size) {
517 default: assert(0 && "Unknown ptr width");
518 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
519 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
520 }
521 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
522}
Anders Carlsson36a04872007-08-21 00:21:21 +0000523
Chris Lattnerab862cc2007-08-31 04:31:45 +0000524llvm::Constant *CodeGenModule::
525GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000526 llvm::StringMapEntry<llvm::Constant *> &Entry =
527 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
528
529 if (Entry.getValue())
530 return Entry.getValue();
531
532 std::vector<llvm::Constant*> Fields;
533
534 if (!CFConstantStringClassRef) {
535 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
536 Ty = llvm::ArrayType::get(Ty, 0);
537
538 CFConstantStringClassRef =
539 new llvm::GlobalVariable(Ty, false,
540 llvm::GlobalVariable::ExternalLinkage, 0,
541 "__CFConstantStringClassReference",
542 &getModule());
543 }
544
545 // Class pointer.
546 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
547 llvm::Constant *Zeros[] = { Zero, Zero };
548 llvm::Constant *C =
549 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
550 Fields.push_back(C);
551
552 // Flags.
553 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
554 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
555
556 // String pointer.
557 C = llvm::ConstantArray::get(str);
558 C = new llvm::GlobalVariable(C->getType(), true,
559 llvm::GlobalValue::InternalLinkage,
560 C, ".str", &getModule());
561
562 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
563 Fields.push_back(C);
564
565 // String length.
566 Ty = getTypes().ConvertType(getContext().LongTy);
567 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
568
569 // The struct.
570 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
571 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000572 llvm::GlobalVariable *GV =
573 new llvm::GlobalVariable(C->getType(), true,
574 llvm::GlobalVariable::InternalLinkage,
575 C, "", &getModule());
576 GV->setSection("__DATA,__cfstring");
577 Entry.setValue(GV);
578 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000579}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000580
581/// GenerateWritableString -- Creates storage for a string literal
582static llvm::Constant *GenerateStringLiteral(const std::string &str,
583 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000584 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000585 // Create Constant for this string literal
586 llvm::Constant *C=llvm::ConstantArray::get(str);
587
588 // Create a global variable for this string
589 C = new llvm::GlobalVariable(C->getType(), constant,
590 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000591 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000592 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
593 llvm::Constant *Zeros[] = { Zero, Zero };
594 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
595 return C;
596}
597
598/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
599/// element of a character array containing the literal.
600llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
601 // Don't share any string literals if writable-strings is turned on.
602 if (Features.WritableStrings)
603 return GenerateStringLiteral(str, false, *this);
604
605 llvm::StringMapEntry<llvm::Constant *> &Entry =
606 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
607
608 if (Entry.getValue())
609 return Entry.getValue();
610
611 // Create a global variable for this.
612 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
613 Entry.setValue(C);
614 return C;
615}