blob: 51d0a89cea396f21b4d8a8b5d0752b6a89419774 [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//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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"
Nate Begeman8a704172008-04-19 04:17:09 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000022#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000025#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000027#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattnerdb6be562007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
34 Diagnostic &diags)
35 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattnercbfb5512008-03-01 08:45:05 +000036 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
37 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000038 Runtime = CreateObjCRuntime(M,
39 getTypes().ConvertType(getContext().IntTy),
40 getTypes().ConvertType(getContext().LongTy));
Chris Lattnercbfb5512008-03-01 08:45:05 +000041}
42
43CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000044 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000045 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000046 AddGlobalCtor(ObjCInitFunction);
Nate Begemanad320b62008-04-20 06:29:50 +000047 EmitStatics();
Chris Lattner753d2592008-03-14 17:18:18 +000048 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000049 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000050 delete Runtime;
51}
Chris Lattner4b009652007-07-25 00:24:17 +000052
Chris Lattnercf9c9d02007-12-02 07:19:18 +000053/// WarnUnsupported - Print out a warning that codegen doesn't support the
54/// specified stmt yet.
55void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
56 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
57 "cannot codegen this %0 yet");
58 SourceRange Range = S->getSourceRange();
59 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000060 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000061 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000062}
Chris Lattner0e4755d2007-12-02 06:27:33 +000063
Chris Lattner806a5f52008-01-12 07:05:38 +000064/// WarnUnsupported - Print out a warning that codegen doesn't support the
65/// specified decl yet.
66void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
67 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
68 "cannot codegen this %0 yet");
69 std::string Msg = Type;
70 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
71 &Msg, 1);
72}
73
Chris Lattner753d2592008-03-14 17:18:18 +000074/// AddGlobalCtor - Add a function to the list that will be called before
75/// main() runs.
76void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
77 // TODO: Type coercion of void()* types.
78 GlobalCtors.push_back(Ctor);
79}
80
Chris Lattnerb326b172008-03-30 23:03:07 +000081/// EmitGlobalCtors - Generates the array of contsturctor functions to be
82/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +000083void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +000084 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000085
Chris Lattner753d2592008-03-14 17:18:18 +000086 // Get the type of @llvm.global_ctors
87 std::vector<const llvm::Type*> CtorFields;
88 CtorFields.push_back(llvm::IntegerType::get(32));
89 // Constructor function type
90 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000091 llvm::FunctionType* CtorFuncTy =
92 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
93
Chris Lattner753d2592008-03-14 17:18:18 +000094 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +000095 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
96 llvm::StructType* CtorStructTy =
97 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +000098 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +000099 llvm::ArrayType* GlobalCtorsTy =
100 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000101
Chris Lattner753d2592008-03-14 17:18:18 +0000102 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000103 llvm::GlobalVariable *GlobalCtorsVal =
104 new llvm::GlobalVariable(GlobalCtorsTy, false,
105 llvm::GlobalValue::AppendingLinkage,
106 (llvm::Constant*)0, "llvm.global_ctors",
107 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000108
109 // Populate the array
110 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000111 llvm::Constant *MagicNumber =
112 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
113 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000114 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000115 E = GlobalCtors.end(); I != E; ++I) {
116 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000117 StructValues.push_back(MagicNumber);
118 StructValues.push_back(*I);
119
Chris Lattnera18c12e2008-03-19 05:24:56 +0000120 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000121 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000122
123 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
124 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000125}
126
Chris Lattnerb326b172008-03-30 23:03:07 +0000127
128
Nate Begeman52da5c72008-04-18 23:43:57 +0000129void CodeGenModule::EmitAnnotations() {
130 if (Annotations.empty())
131 return;
132
133 // Create a new global variable for the ConstantStruct in the Module.
134 llvm::Constant *Array =
135 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
136 Annotations.size()),
137 Annotations);
138 llvm::GlobalValue *gv =
139 new llvm::GlobalVariable(Array->getType(), false,
140 llvm::GlobalValue::AppendingLinkage, Array,
141 "llvm.global.annotations", &TheModule);
142 gv->setSection("llvm.metadata");
143}
144
Chris Lattner0e4755d2007-12-02 06:27:33 +0000145/// ReplaceMapValuesWith - This is a really slow and bad function that
146/// searches for any entries in GlobalDeclMap that point to OldVal, changing
147/// them to point to NewVal. This is badbadbad, FIXME!
148void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
149 llvm::Constant *NewVal) {
150 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
151 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
152 if (I->second == OldVal) I->second = NewVal;
153}
154
155
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000156llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
157 bool isDefinition) {
158 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000159 llvm::Constant *&Entry = GlobalDeclMap[D];
160 if (Entry) return Entry;
161
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000162 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
163
164 // Check to see if the function already exists.
165 llvm::Function *F = getModule().getFunction(D->getName());
166 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
167
168 // If it doesn't already exist, just create and return an entry.
169 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000170 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000171 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
172 D->getName(), &getModule());
Nate Begemandc6262e2008-03-09 03:09:36 +0000173
174 // Set the appropriate calling convention for the Function.
175 if (D->getAttr<FastCallAttr>())
176 F->setCallingConv(llvm::CallingConv::Fast);
177 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
179
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000180 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000181 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000182 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000183
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000184 // If this isn't a definition, just return it casted to the right type.
185 if (!isDefinition)
186 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
187
188 // Otherwise, we have a definition after a prototype with the wrong type.
189 // F is the Function* for the one with the wrong type, we must make a new
190 // Function* and update everything that used F (a declaration) with the new
191 // Function* (which will be a definition).
192 //
193 // This happens if there is a prototype for a function (e.g. "int f()") and
194 // then a definition of a different type (e.g. "int f(int x)"). Start by
195 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000196 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000197 llvm::Function::ExternalLinkage,
198 "", &getModule());
199 NewFn->takeName(F);
200
201 // Replace uses of F with the Function we will endow with a body.
202 llvm::Constant *NewPtrForOldDecl =
203 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
204 F->replaceAllUsesWith(NewPtrForOldDecl);
205
206 // FIXME: Update the globaldeclmap for the previous decl of this name. We
207 // really want a way to walk all of these, but we don't have it yet. This
208 // is incredibly slow!
209 ReplaceMapValuesWith(F, NewPtrForOldDecl);
210
211 // Ok, delete the old function now, which is dead.
212 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
213 F->eraseFromParent();
214
215 // Return the new function which has the right type.
216 return Entry = NewFn;
217}
218
Chris Lattner0db06992008-02-05 06:37:34 +0000219static bool IsZeroElementArray(const llvm::Type *Ty) {
220 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
221 return ATy->getNumElements() == 0;
222 return false;
223}
224
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000225llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
226 bool isDefinition) {
227 assert(D->hasGlobalStorage() && "Not a global variable");
228
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000229 // See if it is already in the map.
230 llvm::Constant *&Entry = GlobalDeclMap[D];
231 if (Entry) return Entry;
232
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000233 QualType ASTTy = D->getType();
234 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000235
236 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000237 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000238
239 // If it doesn't already exist, just create and return an entry.
240 if (GV == 0) {
241 return Entry = new llvm::GlobalVariable(Ty, false,
242 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000243 0, D->getName(), &getModule(), 0,
244 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000245 }
246
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000247 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000248 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000249 if (PTy == GV->getType()) return Entry = GV;
250
251 // If this isn't a definition, just return it casted to the right type.
252 if (!isDefinition)
253 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
254
255
256 // Otherwise, we have a definition after a prototype with the wrong type.
257 // GV is the GlobalVariable* for the one with the wrong type, we must make a
258 /// new GlobalVariable* and update everything that used GV (a declaration)
259 // with the new GlobalVariable* (which will be a definition).
260 //
261 // This happens if there is a prototype for a global (e.g. "extern int x[];")
262 // and then a definition of a different type (e.g. "int x[10];"). Start by
263 // making a new global of the correct type, RAUW, then steal the name.
264 llvm::GlobalVariable *NewGV =
265 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000266 0, D->getName(), &getModule(), 0,
267 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000268 NewGV->takeName(GV);
269
270 // Replace uses of GV with the globalvalue we will endow with a body.
271 llvm::Constant *NewPtrForOldDecl =
272 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
273 GV->replaceAllUsesWith(NewPtrForOldDecl);
274
275 // FIXME: Update the globaldeclmap for the previous decl of this name. We
276 // really want a way to walk all of these, but we don't have it yet. This
277 // is incredibly slow!
278 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
279
Chris Lattner0db06992008-02-05 06:37:34 +0000280 // Verify that GV was a declaration or something like x[] which turns into
281 // [0 x type].
282 assert((GV->isDeclaration() ||
283 IsZeroElementArray(GV->getType()->getElementType())) &&
284 "Shouldn't replace non-declaration");
285
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000286 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000287 GV->eraseFromParent();
288
289 // Return the new global which has the right type.
290 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000291}
292
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000293
Chris Lattnerb326b172008-03-30 23:03:07 +0000294void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
295 // If this is not a prototype, emit the body.
296 if (OMD->getBody())
297 CodeGenFunction(*this).GenerateObjCMethod(OMD);
298}
299
Chris Lattner4b009652007-07-25 00:24:17 +0000300void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
301 // If this is not a prototype, emit the body.
Nate Begemanad320b62008-04-20 06:29:50 +0000302 if (FD->getBody()) {
303 // If the function is a static, defer code generation until later so we can
304 // easily omit unused statics.
305 if (FD->getStorageClass() == FunctionDecl::Static) {
306 StaticDecls.push_back(FD);
307 return;
308 }
Chris Lattner4b009652007-07-25 00:24:17 +0000309 CodeGenFunction(*this).GenerateCode(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000310 }
311}
312
313void CodeGenModule::EmitStatics() {
314 // Emit code for each used static decl encountered. Since a previously unused
315 // static decl may become used during the generation of code for a static
316 // function, iterate until no changes are made.
317 bool Changed;
318 do {
319 Changed = false;
320 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
321 // Check the map of used decls for our static. If not found, continue.
322 const Decl *D = StaticDecls[i];
323 if (GlobalDeclMap[D] == 0)
324 continue;
325
326 // If this is a function decl, generate code for the static function if it
327 // has a body. Otherwise, we must have a var decl for a static global
328 // variable.
329 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
330 if (FD->getBody())
331 CodeGenFunction(*this).GenerateCode(FD);
332 } else {
333 const VarDecl *VD = cast<VarDecl>(D);
334 EmitGlobalVarInit(VD);
335 }
336 // Erase the used decl from the list.
337 StaticDecls[i] = StaticDecls.back();
338 StaticDecls.pop_back();
339 --i;
340 --e;
341
342 // Remember that we made a change.
343 Changed = true;
344 }
345 } while (Changed);
346
347 // Warn about all statics that are still unused at end of code generation.
348 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
349 const Decl *D = StaticDecls[i];
350 std::string Msg = cast<NamedDecl>(D)->getName();
351 getDiags().Report(Context.getFullLoc(D->getLocation()),
352 diag::warn_unused_static, &Msg, 1);
353 }
Chris Lattner4b009652007-07-25 00:24:17 +0000354}
355
Anders Carlssond76cead2008-01-26 01:36:00 +0000356llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
357 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000358}
359
Nate Begeman8a704172008-04-19 04:17:09 +0000360/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
361/// annotation information for a given GlobalValue. The annotation struct is
362/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
363/// GlobalValue being annotated. The second filed is thee constant string
364/// created from the AnnotateAttr's annotation. The third field is a constant
365/// string containing the name of the translation unit. The fourth field is
366/// the line number in the file of the annotated value declaration.
367///
368/// FIXME: this does not unique the annotation string constants, as llvm-gcc
369/// appears to.
370///
371llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
372 const AnnotateAttr *AA,
373 unsigned LineNo) {
374 llvm::Module *M = &getModule();
375
376 // get [N x i8] constants for the annotation string, and the filename string
377 // which are the 2nd and 3rd elements of the global annotation structure.
378 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
379 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
380 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
381 true);
382
383 // Get the two global values corresponding to the ConstantArrays we just
384 // created to hold the bytes of the strings.
385 llvm::GlobalValue *annoGV =
386 new llvm::GlobalVariable(anno->getType(), false,
387 llvm::GlobalValue::InternalLinkage, anno,
388 GV->getName() + ".str", M);
389 // translation unit name string, emitted into the llvm.metadata section.
390 llvm::GlobalValue *unitGV =
391 new llvm::GlobalVariable(unit->getType(), false,
392 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
393
394 // Create the ConstantStruct that is the global annotion.
395 llvm::Constant *Fields[4] = {
396 llvm::ConstantExpr::getBitCast(GV, SBP),
397 llvm::ConstantExpr::getBitCast(annoGV, SBP),
398 llvm::ConstantExpr::getBitCast(unitGV, SBP),
399 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
400 };
401 return llvm::ConstantStruct::get(Fields, 4, false);
402}
403
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000404void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000405 // If the VarDecl is a static, defer code generation until later so we can
406 // easily omit unused statics.
407 if (D->getStorageClass() == VarDecl::Static) {
408 StaticDecls.push_back(D);
409 return;
410 }
411
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000412 // If this is just a forward declaration of the variable, don't emit it now,
413 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000414 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
415 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000416
Nate Begemanad320b62008-04-20 06:29:50 +0000417 EmitGlobalVarInit(D);
418}
419
420void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000421 // Get the global, forcing it to be a direct reference.
422 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000423 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000424
425 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000426 llvm::Constant *Init = 0;
427 if (D->getInit() == 0) {
428 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
429 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000430 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000431 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000432 if (D->getInit()->isIntegerConstantExpr(Value, Context))
433 Init = llvm::ConstantInt::get(Value);
434 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000435
Devang Patel08a10cc2007-10-30 21:27:20 +0000436 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000437 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000438
Nate Begeman8a704172008-04-19 04:17:09 +0000439 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
440 SourceManager &SM = Context.getSourceManager();
441 AddAnnotation(EmitAnnotateAttr(GV, AA,
442 SM.getLogicalLineNumber(D->getLocation())));
443 }
444
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000445 assert(GV->getType()->getElementType() == Init->getType() &&
446 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000447 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000448
449 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
450 GV->setVisibility(attr->getVisibility());
451 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000452
453 // Set the llvm linkage type as appropriate.
Chris Lattner402b3372008-03-03 03:28:21 +0000454 if (D->getAttr<DLLImportAttr>())
455 GV->setLinkage(llvm::Function::DLLImportLinkage);
456 else if (D->getAttr<DLLExportAttr>())
457 GV->setLinkage(llvm::Function::DLLExportLinkage);
458 else if (D->getAttr<WeakAttr>()) {
459 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
460
461 } else {
462 // FIXME: This isn't right. This should handle common linkage and other
463 // stuff.
464 switch (D->getStorageClass()) {
465 case VarDecl::Auto:
466 case VarDecl::Register:
467 assert(0 && "Can't have auto or register globals");
468 case VarDecl::None:
469 if (!D->getInit())
470 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
471 break;
472 case VarDecl::Extern:
473 case VarDecl::PrivateExtern:
474 // todo: common
475 break;
476 case VarDecl::Static:
477 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
478 break;
479 }
Chris Lattner4b009652007-07-25 00:24:17 +0000480 }
481}
482
483/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
484/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000485void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
486 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
487 if (D->isFileVarDecl())
488 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000489}
490
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000491void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
492 // Make sure that this type is translated.
493 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000494}
495
496
Chris Lattnerab862cc2007-08-31 04:31:45 +0000497/// getBuiltinLibFunction
498llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000499 if (BuiltinID > BuiltinFunctions.size())
500 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000501
Chris Lattner9f2d6892007-12-13 00:38:03 +0000502 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
503 // a slot for it.
504 assert(BuiltinID && "Invalid Builtin ID");
505 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000506 if (FunctionSlot)
507 return FunctionSlot;
508
509 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
510
511 // Get the name, skip over the __builtin_ prefix.
512 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
513
514 // Get the type for the builtin.
515 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
516 const llvm::FunctionType *Ty =
517 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
518
519 // FIXME: This has a serious problem with code like this:
520 // void abs() {}
521 // ... __builtin_abs(x);
522 // The two versions of abs will collide. The fix is for the builtin to win,
523 // and for the existing one to be turned into a constantexpr cast of the
524 // builtin. In the case where the existing one is a static function, it
525 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000526 if (llvm::Function *Existing = getModule().getFunction(Name)) {
527 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
528 return FunctionSlot = Existing;
529 assert(Existing == 0 && "FIXME: Name collision");
530 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000531
532 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000533 return FunctionSlot =
534 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
535 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000536}
537
Chris Lattner4b23f942007-12-18 00:25:38 +0000538llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
539 unsigned NumTys) {
540 return llvm::Intrinsic::getDeclaration(&getModule(),
541 (llvm::Intrinsic::ID)IID, Tys, NumTys);
542}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000543
Chris Lattner4b009652007-07-25 00:24:17 +0000544llvm::Function *CodeGenModule::getMemCpyFn() {
545 if (MemCpyFn) return MemCpyFn;
546 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000547 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000548 default: assert(0 && "Unknown ptr width");
549 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
550 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
551 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000552 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000553}
Anders Carlsson36a04872007-08-21 00:21:21 +0000554
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000555llvm::Function *CodeGenModule::getMemSetFn() {
556 if (MemSetFn) return MemSetFn;
557 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000558 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000559 default: assert(0 && "Unknown ptr width");
560 case 32: IID = llvm::Intrinsic::memset_i32; break;
561 case 64: IID = llvm::Intrinsic::memset_i64; break;
562 }
563 return MemSetFn = getIntrinsic(IID);
564}
Chris Lattner4b23f942007-12-18 00:25:38 +0000565
Chris Lattnerab862cc2007-08-31 04:31:45 +0000566llvm::Constant *CodeGenModule::
567GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000568 llvm::StringMapEntry<llvm::Constant *> &Entry =
569 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
570
571 if (Entry.getValue())
572 return Entry.getValue();
573
574 std::vector<llvm::Constant*> Fields;
575
576 if (!CFConstantStringClassRef) {
577 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
578 Ty = llvm::ArrayType::get(Ty, 0);
579
580 CFConstantStringClassRef =
581 new llvm::GlobalVariable(Ty, false,
582 llvm::GlobalVariable::ExternalLinkage, 0,
583 "__CFConstantStringClassReference",
584 &getModule());
585 }
586
587 // Class pointer.
588 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
589 llvm::Constant *Zeros[] = { Zero, Zero };
590 llvm::Constant *C =
591 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
592 Fields.push_back(C);
593
594 // Flags.
595 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
596 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
597
598 // String pointer.
599 C = llvm::ConstantArray::get(str);
600 C = new llvm::GlobalVariable(C->getType(), true,
601 llvm::GlobalValue::InternalLinkage,
602 C, ".str", &getModule());
603
604 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
605 Fields.push_back(C);
606
607 // String length.
608 Ty = getTypes().ConvertType(getContext().LongTy);
609 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
610
611 // The struct.
612 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
613 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000614 llvm::GlobalVariable *GV =
615 new llvm::GlobalVariable(C->getType(), true,
616 llvm::GlobalVariable::InternalLinkage,
617 C, "", &getModule());
618 GV->setSection("__DATA,__cfstring");
619 Entry.setValue(GV);
620 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000621}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000622
Chris Lattnera6dcce32008-02-11 00:02:17 +0000623/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000624static llvm::Constant *GenerateStringLiteral(const std::string &str,
625 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000626 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000627 // Create Constant for this string literal
628 llvm::Constant *C=llvm::ConstantArray::get(str);
629
630 // Create a global variable for this string
631 C = new llvm::GlobalVariable(C->getType(), constant,
632 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000633 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000634 return C;
635}
636
Chris Lattnera6dcce32008-02-11 00:02:17 +0000637/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
638/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000639llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
640 // Don't share any string literals if writable-strings is turned on.
641 if (Features.WritableStrings)
642 return GenerateStringLiteral(str, false, *this);
643
644 llvm::StringMapEntry<llvm::Constant *> &Entry =
645 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
646
647 if (Entry.getValue())
648 return Entry.getValue();
649
650 // Create a global variable for this.
651 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
652 Entry.setValue(C);
653 return C;
654}