blob: 6ef620654429377004fcd47eea79966327a0f243 [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"
25using namespace clang;
26using namespace CodeGen;
27
28
Chris Lattner45e8cbd2007-11-28 05:34:05 +000029CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-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 Patel7a4718e2007-10-31 20:01:01 +000033 Types(C, M, TD), MemCpyFn(0), CFConstantStringClassRef(0) {}
Reid Spencer5f016e22007-07-11 17:01:13 +000034
Chris Lattner2c8569d2007-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 Lattner58c3f9e2007-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 Lattner9cd4fe42007-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.
Reid Spencer5f016e22007-07-11 17:01:13 +000059 llvm::Constant *&Entry = GlobalDeclMap[D];
60 if (Entry) return Entry;
61
Chris Lattner9cd4fe42007-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) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner9cd4fe42007-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 Lattnerfafad832007-12-02 06:30:46 +000078
Chris Lattner9cd4fe42007-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 Lattnerfafad832007-12-02 06:30:46 +0000130 }
131
Chris Lattner9cd4fe42007-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;
Reid Spencer5f016e22007-07-11 17:01:13 +0000170}
171
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000172
Chris Lattner88a69ad2007-07-13 05:13:43 +0000173void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 // If this is not a prototype, emit the body.
175 if (FD->getBody())
176 CodeGenFunction(*this).GenerateCode(FD);
177}
178
Chris Lattner75cf2882007-11-23 22:07:55 +0000179static llvm::Constant *GenerateConstantExpr(const Expr *Expression,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000180 CodeGenModule &CGM);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000181
Chris Lattner75cf2882007-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 Lattner2c8569d2007-12-02 07:19:18 +0000205 CodeGenModule &CGM) {
206 CodeGenTypes& Types = CGM.getTypes();
Chris Lattner75cf2882007-11-23 22:07:55 +0000207 QualType Source = Expression->getType().getCanonicalType();
208 Target = Target.getCanonicalType();
209
210 assert (!Target->isVoidType());
211
Chris Lattner2c8569d2007-12-02 07:19:18 +0000212 llvm::Constant *SubExpr = GenerateConstantExpr(Expression, CGM);
Chris Lattner75cf2882007-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 Lattner75cf2882007-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 Lattner2c8569d2007-12-02 07:19:18 +0000281 CodeGenModule &CGM) {
Chris Lattner75cf2882007-11-23 22:07:55 +0000282 assert (ILE->getType()->isArrayType() || ILE->getType()->isStructureType());
Chris Lattner2c8569d2007-12-02 07:19:18 +0000283 CodeGenTypes& Types = CGM.getTypes();
Devang Patel9e32d4b2007-10-30 21:27:20 +0000284
285 unsigned NumInitElements = ILE->getNumInits();
286
Chris Lattner75cf2882007-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 Patel9e32d4b2007-10-30 21:27:20 +0000292 // Copy initializer elements.
293 unsigned i = 0;
294 for (i = 0; i < NumInitElements; ++i) {
Chris Lattner2c8569d2007-12-02 07:19:18 +0000295 llvm::Constant *C = GenerateConstantExpr(ILE->getInit(i), CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000296 assert (C && "Failed to create initialiser expression");
297 Elts.push_back(C);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000298 }
299
Chris Lattner75cf2882007-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 Patel9e32d4b2007-10-30 21:27:20 +0000307 const llvm::Type *AElemTy = AType->getElementType();
Chris Lattner75cf2882007-11-23 22:07:55 +0000308 unsigned NumArrayElements = AType->getNumElements();
309 // Initialize remaining array elements.
Devang Patel9e32d4b2007-10-30 21:27:20 +0000310 for (; i < NumArrayElements; ++i)
Chris Lattner75cf2882007-11-23 22:07:55 +0000311 Elts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel9e32d4b2007-10-30 21:27:20 +0000312
Chris Lattner75cf2882007-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 Lattner2c8569d2007-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 Lattner75cf2882007-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 Lattner45e8cbd2007-11-28 05:34:05 +0000346 const char *StrData = SLiteral->getStrData();
347 unsigned Len = SLiteral->getByteLength();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000348 return CGM.GetAddrOfConstantString(std::string(StrData, StrData + Len));
Chris Lattner75cf2882007-11-23 22:07:55 +0000349 }
350
351 // Elide parenthesis.
352 case Stmt::ParenExprClass:
Chris Lattner2c8569d2007-12-02 07:19:18 +0000353 return GenerateConstantExpr(cast<ParenExpr>(Expression)->getSubExpr(), CGM);
Chris Lattner75cf2882007-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 Lattner2c8569d2007-12-02 07:19:18 +0000367 CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000368
369 case Stmt::ImplicitCastExprClass: {
370 const ImplicitCastExpr *ICExpr = cast<ImplicitCastExpr>(Expression);
Chris Lattner2c8569d2007-12-02 07:19:18 +0000371 return GenerateConstantCast(ICExpr->getSubExpr(), type, CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000372 }
373
374 // Generate a constant array access expression
375 // FIXME: Clang's semantic analysis incorrectly prevents array access in
376 // global initialisers, preventing us from testing this.
377 case Stmt::ArraySubscriptExprClass: {
378 const ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(Expression);
Chris Lattner2c8569d2007-12-02 07:19:18 +0000379 llvm::Constant *Base = GenerateConstantExpr(ASExpr->getBase(), CGM);
380 llvm::Constant *Index = GenerateConstantExpr(ASExpr->getIdx(), CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000381 return llvm::ConstantExpr::getExtractElement(Base, Index);
382 }
383
384 // Generate a constant expression to initialise an aggregate type, such as
385 // an array or struct.
386 case Stmt::InitListExprClass:
Chris Lattner2c8569d2007-12-02 07:19:18 +0000387 return GenerateAggregateInit(cast<InitListExpr>(Expression), CGM);
Chris Lattner75cf2882007-11-23 22:07:55 +0000388
389 default:
Chris Lattner2c8569d2007-12-02 07:19:18 +0000390 CGM.WarnUnsupported(Expression, "initializer");
391 return llvm::UndefValue::get(Types.ConvertType(type));
Chris Lattner75cf2882007-11-23 22:07:55 +0000392 }
Chris Lattner75cf2882007-11-23 22:07:55 +0000393}
394
Oliver Hunt28247232007-12-02 00:11:25 +0000395llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expression) {
396 return GenerateConstantExpr(Expression, *this);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000397}
398
Chris Lattner88a69ad2007-07-13 05:13:43 +0000399void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000400 // If this is just a forward declaration of the variable, don't emit it now,
401 // allow it to be emitted lazily on its first use.
Chris Lattner88a69ad2007-07-13 05:13:43 +0000402 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
403 return;
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000404
405 // Get the global, forcing it to be a direct reference.
406 llvm::GlobalVariable *GV =
407 cast<llvm::GlobalVariable>(GetAddrOfFileVarDecl(D, true));
408
409 // Convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000410 llvm::Constant *Init = 0;
411 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000412 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000413 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000414 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner47f7dbf2007-09-04 02:34:27 +0000415 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner590b6642007-07-15 23:26:56 +0000416 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000417 Init = llvm::ConstantInt::get(Value);
418 }
Devang Patel8e53e722007-10-26 16:31:40 +0000419
Devang Patel9e32d4b2007-10-30 21:27:20 +0000420 if (!Init)
Oliver Hunt28247232007-12-02 00:11:25 +0000421 Init = EmitGlobalInit(D->getInit());
Devang Patel8e53e722007-10-26 16:31:40 +0000422
Devang Patel9e32d4b2007-10-30 21:27:20 +0000423 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner8f32f712007-07-14 00:23:28 +0000424
Chris Lattner88a69ad2007-07-13 05:13:43 +0000425 GV->setInitializer(Init);
426
427 // Set the llvm linkage type as appropriate.
428 // FIXME: This isn't right. This should handle common linkage and other
429 // stuff.
430 switch (D->getStorageClass()) {
431 case VarDecl::Auto:
432 case VarDecl::Register:
433 assert(0 && "Can't have auto or register globals");
434 case VarDecl::None:
435 case VarDecl::Extern:
436 // todo: common
437 break;
438 case VarDecl::Static:
439 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
440 break;
441 }
442}
Reid Spencer5f016e22007-07-11 17:01:13 +0000443
Chris Lattner32b266c2007-07-14 00:16:50 +0000444/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
445/// declarator chain.
446void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
447 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
448 EmitGlobalVar(D);
449}
Reid Spencer5f016e22007-07-11 17:01:13 +0000450
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000451/// getBuiltinLibFunction
452llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
453 if (BuiltinFunctions.size() <= BuiltinID)
454 BuiltinFunctions.resize(BuiltinID);
455
456 // Already available?
457 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
458 if (FunctionSlot)
459 return FunctionSlot;
460
461 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
462
463 // Get the name, skip over the __builtin_ prefix.
464 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
465
466 // Get the type for the builtin.
467 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
468 const llvm::FunctionType *Ty =
469 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
470
471 // FIXME: This has a serious problem with code like this:
472 // void abs() {}
473 // ... __builtin_abs(x);
474 // The two versions of abs will collide. The fix is for the builtin to win,
475 // and for the existing one to be turned into a constantexpr cast of the
476 // builtin. In the case where the existing one is a static function, it
477 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000478 if (llvm::Function *Existing = getModule().getFunction(Name)) {
479 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
480 return FunctionSlot = Existing;
481 assert(Existing == 0 && "FIXME: Name collision");
482 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000483
484 // FIXME: param attributes for sext/zext etc.
485 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
486 Name, &getModule());
487}
488
489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490llvm::Function *CodeGenModule::getMemCpyFn() {
491 if (MemCpyFn) return MemCpyFn;
492 llvm::Intrinsic::ID IID;
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000493 uint64_t Size; unsigned Align;
494 Context.Target.getPointerInfo(Size, Align, SourceLocation());
495 switch (Size) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 default: assert(0 && "Unknown ptr width");
497 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
498 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
499 }
500 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
501}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000502
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000503llvm::Constant *CodeGenModule::
504GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000505 llvm::StringMapEntry<llvm::Constant *> &Entry =
506 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
507
508 if (Entry.getValue())
509 return Entry.getValue();
510
511 std::vector<llvm::Constant*> Fields;
512
513 if (!CFConstantStringClassRef) {
514 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
515 Ty = llvm::ArrayType::get(Ty, 0);
516
517 CFConstantStringClassRef =
518 new llvm::GlobalVariable(Ty, false,
519 llvm::GlobalVariable::ExternalLinkage, 0,
520 "__CFConstantStringClassReference",
521 &getModule());
522 }
523
524 // Class pointer.
525 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
526 llvm::Constant *Zeros[] = { Zero, Zero };
527 llvm::Constant *C =
528 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
529 Fields.push_back(C);
530
531 // Flags.
532 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
533 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
534
535 // String pointer.
536 C = llvm::ConstantArray::get(str);
537 C = new llvm::GlobalVariable(C->getType(), true,
538 llvm::GlobalValue::InternalLinkage,
539 C, ".str", &getModule());
540
541 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
542 Fields.push_back(C);
543
544 // String length.
545 Ty = getTypes().ConvertType(getContext().LongTy);
546 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
547
548 // The struct.
549 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
550 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000551 llvm::GlobalVariable *GV =
552 new llvm::GlobalVariable(C->getType(), true,
553 llvm::GlobalVariable::InternalLinkage,
554 C, "", &getModule());
555 GV->setSection("__DATA,__cfstring");
556 Entry.setValue(GV);
557 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000558}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000559
560/// GenerateWritableString -- Creates storage for a string literal
561static llvm::Constant *GenerateStringLiteral(const std::string &str,
562 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000563 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000564 // Create Constant for this string literal
565 llvm::Constant *C=llvm::ConstantArray::get(str);
566
567 // Create a global variable for this string
568 C = new llvm::GlobalVariable(C->getType(), constant,
569 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000570 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000571 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
572 llvm::Constant *Zeros[] = { Zero, Zero };
573 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
574 return C;
575}
576
577/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the first
578/// element of a character array containing the literal.
579llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
580 // Don't share any string literals if writable-strings is turned on.
581 if (Features.WritableStrings)
582 return GenerateStringLiteral(str, false, *this);
583
584 llvm::StringMapEntry<llvm::Constant *> &Entry =
585 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
586
587 if (Entry.getValue())
588 return Entry.getValue();
589
590 // Create a global variable for this.
591 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
592 Entry.setValue(C);
593 return C;
594}