blob: 306abd120bdd0fde412f7f3c9c166c4cdaddadcf [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"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000027#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000028#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattnerdb6be562007-11-28 05:34:05 +000033CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000034 llvm::Module &M, const llvm::TargetData &TD,
35 Diagnostic &diags)
36 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattnercbfb5512008-03-01 08:45:05 +000037 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
38 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000039 Runtime = CreateObjCRuntime(M,
40 getTypes().ConvertType(getContext().IntTy),
41 getTypes().ConvertType(getContext().LongTy));
Chris Lattnercbfb5512008-03-01 08:45:05 +000042}
43
44CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000045 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000046 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000047 AddGlobalCtor(ObjCInitFunction);
Nate Begemanad320b62008-04-20 06:29:50 +000048 EmitStatics();
Chris Lattner753d2592008-03-14 17:18:18 +000049 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000050 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000051 delete Runtime;
Chris Lattnerb033c4a2008-04-30 16:05:42 +000052
53 // Run the verifier to check that the generated code is consistent.
54 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000055}
Chris Lattner4b009652007-07-25 00:24:17 +000056
Chris Lattnercf9c9d02007-12-02 07:19:18 +000057/// WarnUnsupported - Print out a warning that codegen doesn't support the
58/// specified stmt yet.
59void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
60 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
61 "cannot codegen this %0 yet");
62 SourceRange Range = S->getSourceRange();
63 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000064 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000065 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000066}
Chris Lattner0e4755d2007-12-02 06:27:33 +000067
Chris Lattner806a5f52008-01-12 07:05:38 +000068/// WarnUnsupported - Print out a warning that codegen doesn't support the
69/// specified decl yet.
70void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
71 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
72 "cannot codegen this %0 yet");
73 std::string Msg = Type;
74 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
75 &Msg, 1);
76}
77
Chris Lattner753d2592008-03-14 17:18:18 +000078/// AddGlobalCtor - Add a function to the list that will be called before
79/// main() runs.
80void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
81 // TODO: Type coercion of void()* types.
82 GlobalCtors.push_back(Ctor);
83}
84
Chris Lattnerb326b172008-03-30 23:03:07 +000085/// EmitGlobalCtors - Generates the array of contsturctor functions to be
86/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +000087void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +000088 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000089
Chris Lattner753d2592008-03-14 17:18:18 +000090 // Get the type of @llvm.global_ctors
91 std::vector<const llvm::Type*> CtorFields;
92 CtorFields.push_back(llvm::IntegerType::get(32));
93 // Constructor function type
94 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000095 llvm::FunctionType* CtorFuncTy =
96 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
97
Chris Lattner753d2592008-03-14 17:18:18 +000098 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +000099 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
100 llvm::StructType* CtorStructTy =
101 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000102 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000103 llvm::ArrayType* GlobalCtorsTy =
104 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000105
Chris Lattner753d2592008-03-14 17:18:18 +0000106 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000107 llvm::GlobalVariable *GlobalCtorsVal =
108 new llvm::GlobalVariable(GlobalCtorsTy, false,
109 llvm::GlobalValue::AppendingLinkage,
110 (llvm::Constant*)0, "llvm.global_ctors",
111 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000112
113 // Populate the array
114 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000115 llvm::Constant *MagicNumber =
116 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
117 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000118 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000119 E = GlobalCtors.end(); I != E; ++I) {
120 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000121 StructValues.push_back(MagicNumber);
122 StructValues.push_back(*I);
123
Chris Lattnera18c12e2008-03-19 05:24:56 +0000124 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000125 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000126
127 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
128 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000129}
130
Chris Lattnerb326b172008-03-30 23:03:07 +0000131
132
Nate Begeman52da5c72008-04-18 23:43:57 +0000133void CodeGenModule::EmitAnnotations() {
134 if (Annotations.empty())
135 return;
136
137 // Create a new global variable for the ConstantStruct in the Module.
138 llvm::Constant *Array =
139 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
140 Annotations.size()),
141 Annotations);
142 llvm::GlobalValue *gv =
143 new llvm::GlobalVariable(Array->getType(), false,
144 llvm::GlobalValue::AppendingLinkage, Array,
145 "llvm.global.annotations", &TheModule);
146 gv->setSection("llvm.metadata");
147}
148
Chris Lattner0e4755d2007-12-02 06:27:33 +0000149/// ReplaceMapValuesWith - This is a really slow and bad function that
150/// searches for any entries in GlobalDeclMap that point to OldVal, changing
151/// them to point to NewVal. This is badbadbad, FIXME!
152void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
153 llvm::Constant *NewVal) {
154 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
155 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
156 if (I->second == OldVal) I->second = NewVal;
157}
158
159
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000160llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
161 bool isDefinition) {
162 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000163 llvm::Constant *&Entry = GlobalDeclMap[D];
164 if (Entry) return Entry;
165
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000166 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
167
168 // Check to see if the function already exists.
169 llvm::Function *F = getModule().getFunction(D->getName());
170 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
171
172 // If it doesn't already exist, just create and return an entry.
173 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000174 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000175 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
176 D->getName(), &getModule());
Nate Begemandc6262e2008-03-09 03:09:36 +0000177
178 // Set the appropriate calling convention for the Function.
179 if (D->getAttr<FastCallAttr>())
180 F->setCallingConv(llvm::CallingConv::Fast);
181 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000182 }
183
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000184 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000185 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000186 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000187
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000188 // If this isn't a definition, just return it casted to the right type.
189 if (!isDefinition)
190 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
191
192 // Otherwise, we have a definition after a prototype with the wrong type.
193 // F is the Function* for the one with the wrong type, we must make a new
194 // Function* and update everything that used F (a declaration) with the new
195 // Function* (which will be a definition).
196 //
197 // This happens if there is a prototype for a function (e.g. "int f()") and
198 // then a definition of a different type (e.g. "int f(int x)"). Start by
199 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000200 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000201 llvm::Function::ExternalLinkage,
202 "", &getModule());
203 NewFn->takeName(F);
204
205 // Replace uses of F with the Function we will endow with a body.
206 llvm::Constant *NewPtrForOldDecl =
207 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
208 F->replaceAllUsesWith(NewPtrForOldDecl);
209
210 // FIXME: Update the globaldeclmap for the previous decl of this name. We
211 // really want a way to walk all of these, but we don't have it yet. This
212 // is incredibly slow!
213 ReplaceMapValuesWith(F, NewPtrForOldDecl);
214
215 // Ok, delete the old function now, which is dead.
216 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
217 F->eraseFromParent();
218
219 // Return the new function which has the right type.
220 return Entry = NewFn;
221}
222
Chris Lattner0db06992008-02-05 06:37:34 +0000223static bool IsZeroElementArray(const llvm::Type *Ty) {
224 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
225 return ATy->getNumElements() == 0;
226 return false;
227}
228
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000229llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
230 bool isDefinition) {
231 assert(D->hasGlobalStorage() && "Not a global variable");
232
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000233 // See if it is already in the map.
234 llvm::Constant *&Entry = GlobalDeclMap[D];
235 if (Entry) return Entry;
236
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000237 QualType ASTTy = D->getType();
238 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000239
240 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000241 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000242
243 // If it doesn't already exist, just create and return an entry.
244 if (GV == 0) {
245 return Entry = new llvm::GlobalVariable(Ty, false,
246 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000247 0, D->getName(), &getModule(), 0,
248 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000249 }
250
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000251 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000252 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000253 if (PTy == GV->getType()) return Entry = GV;
254
255 // If this isn't a definition, just return it casted to the right type.
256 if (!isDefinition)
257 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
258
259
260 // Otherwise, we have a definition after a prototype with the wrong type.
261 // GV is the GlobalVariable* for the one with the wrong type, we must make a
262 /// new GlobalVariable* and update everything that used GV (a declaration)
263 // with the new GlobalVariable* (which will be a definition).
264 //
265 // This happens if there is a prototype for a global (e.g. "extern int x[];")
266 // and then a definition of a different type (e.g. "int x[10];"). Start by
267 // making a new global of the correct type, RAUW, then steal the name.
268 llvm::GlobalVariable *NewGV =
269 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000270 0, D->getName(), &getModule(), 0,
271 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000272 NewGV->takeName(GV);
273
274 // Replace uses of GV with the globalvalue we will endow with a body.
275 llvm::Constant *NewPtrForOldDecl =
276 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
277 GV->replaceAllUsesWith(NewPtrForOldDecl);
278
279 // FIXME: Update the globaldeclmap for the previous decl of this name. We
280 // really want a way to walk all of these, but we don't have it yet. This
281 // is incredibly slow!
282 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
283
Chris Lattner0db06992008-02-05 06:37:34 +0000284 // Verify that GV was a declaration or something like x[] which turns into
285 // [0 x type].
286 assert((GV->isDeclaration() ||
287 IsZeroElementArray(GV->getType()->getElementType())) &&
288 "Shouldn't replace non-declaration");
289
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000290 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000291 GV->eraseFromParent();
292
293 // Return the new global which has the right type.
294 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000295}
296
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000297
Chris Lattnerb326b172008-03-30 23:03:07 +0000298void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
299 // If this is not a prototype, emit the body.
300 if (OMD->getBody())
301 CodeGenFunction(*this).GenerateObjCMethod(OMD);
302}
303
Chris Lattner4b009652007-07-25 00:24:17 +0000304void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
305 // If this is not a prototype, emit the body.
Nate Begemanad320b62008-04-20 06:29:50 +0000306 if (FD->getBody()) {
307 // If the function is a static, defer code generation until later so we can
308 // easily omit unused statics.
309 if (FD->getStorageClass() == FunctionDecl::Static) {
Nate Begeman91f52012008-04-20 20:38:08 +0000310 // We need to check the Module here to see if GetAddrOfFunctionDecl() has
311 // already added this function to the Module because the address of the
312 // function's prototype was taken. If this is the case, call
313 // GetAddrOfFunctionDecl to insert the static FunctionDecl into the used
314 // GlobalDeclsMap, so that EmitStatics will generate code for it later.
315 //
316 // Example:
317 // static int foo();
318 // int bar() { return foo(); }
319 // static int foo() { return 5; }
320 if (getModule().getFunction(FD->getName()))
321 GetAddrOfFunctionDecl(FD, true);
322
Nate Begemanad320b62008-04-20 06:29:50 +0000323 StaticDecls.push_back(FD);
324 return;
325 }
Chris Lattner4b009652007-07-25 00:24:17 +0000326 CodeGenFunction(*this).GenerateCode(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000327 }
328}
329
330void CodeGenModule::EmitStatics() {
331 // Emit code for each used static decl encountered. Since a previously unused
332 // static decl may become used during the generation of code for a static
333 // function, iterate until no changes are made.
334 bool Changed;
335 do {
336 Changed = false;
337 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
338 // Check the map of used decls for our static. If not found, continue.
339 const Decl *D = StaticDecls[i];
Nate Begeman91f52012008-04-20 20:38:08 +0000340 if (!GlobalDeclMap.count(D))
Nate Begemanad320b62008-04-20 06:29:50 +0000341 continue;
342
343 // If this is a function decl, generate code for the static function if it
344 // has a body. Otherwise, we must have a var decl for a static global
345 // variable.
346 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
347 if (FD->getBody())
348 CodeGenFunction(*this).GenerateCode(FD);
349 } else {
Nate Begeman91f52012008-04-20 20:38:08 +0000350 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begemanad320b62008-04-20 06:29:50 +0000351 }
352 // Erase the used decl from the list.
353 StaticDecls[i] = StaticDecls.back();
354 StaticDecls.pop_back();
355 --i;
356 --e;
357
358 // Remember that we made a change.
359 Changed = true;
360 }
361 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000362}
363
Anders Carlssond76cead2008-01-26 01:36:00 +0000364llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
365 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000366}
367
Nate Begeman8a704172008-04-19 04:17:09 +0000368/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
369/// annotation information for a given GlobalValue. The annotation struct is
370/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
371/// GlobalValue being annotated. The second filed is thee constant string
372/// created from the AnnotateAttr's annotation. The third field is a constant
373/// string containing the name of the translation unit. The fourth field is
374/// the line number in the file of the annotated value declaration.
375///
376/// FIXME: this does not unique the annotation string constants, as llvm-gcc
377/// appears to.
378///
379llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
380 const AnnotateAttr *AA,
381 unsigned LineNo) {
382 llvm::Module *M = &getModule();
383
384 // get [N x i8] constants for the annotation string, and the filename string
385 // which are the 2nd and 3rd elements of the global annotation structure.
386 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
387 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
388 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
389 true);
390
391 // Get the two global values corresponding to the ConstantArrays we just
392 // created to hold the bytes of the strings.
393 llvm::GlobalValue *annoGV =
394 new llvm::GlobalVariable(anno->getType(), false,
395 llvm::GlobalValue::InternalLinkage, anno,
396 GV->getName() + ".str", M);
397 // translation unit name string, emitted into the llvm.metadata section.
398 llvm::GlobalValue *unitGV =
399 new llvm::GlobalVariable(unit->getType(), false,
400 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
401
402 // Create the ConstantStruct that is the global annotion.
403 llvm::Constant *Fields[4] = {
404 llvm::ConstantExpr::getBitCast(GV, SBP),
405 llvm::ConstantExpr::getBitCast(annoGV, SBP),
406 llvm::ConstantExpr::getBitCast(unitGV, SBP),
407 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
408 };
409 return llvm::ConstantStruct::get(Fields, 4, false);
410}
411
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000412void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000413 // If the VarDecl is a static, defer code generation until later so we can
414 // easily omit unused statics.
415 if (D->getStorageClass() == VarDecl::Static) {
416 StaticDecls.push_back(D);
417 return;
418 }
419
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000420 // If this is just a forward declaration of the variable, don't emit it now,
421 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000422 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
423 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000424
Nate Begemanad320b62008-04-20 06:29:50 +0000425 EmitGlobalVarInit(D);
426}
427
428void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000429 // Get the global, forcing it to be a direct reference.
430 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000431 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000432
433 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000434 llvm::Constant *Init = 0;
435 if (D->getInit() == 0) {
436 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
437 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000438 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000439 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000440 if (D->getInit()->isIntegerConstantExpr(Value, Context))
441 Init = llvm::ConstantInt::get(Value);
442 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000443
Devang Patel08a10cc2007-10-30 21:27:20 +0000444 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000445 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000446
Nate Begeman8a704172008-04-19 04:17:09 +0000447 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
448 SourceManager &SM = Context.getSourceManager();
449 AddAnnotation(EmitAnnotateAttr(GV, AA,
450 SM.getLogicalLineNumber(D->getLocation())));
451 }
452
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000453 assert(GV->getType()->getElementType() == Init->getType() &&
454 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000455 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000456
457 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
458 GV->setVisibility(attr->getVisibility());
459 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000460
461 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000462 if (D->getStorageClass() == VarDecl::Static)
463 GV->setLinkage(llvm::Function::InternalLinkage);
464 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000465 GV->setLinkage(llvm::Function::DLLImportLinkage);
466 else if (D->getAttr<DLLExportAttr>())
467 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000468 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000469 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000470 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000471 // FIXME: This isn't right. This should handle common linkage and other
472 // stuff.
473 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000474 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000475 case VarDecl::Auto:
476 case VarDecl::Register:
477 assert(0 && "Can't have auto or register globals");
478 case VarDecl::None:
479 if (!D->getInit())
480 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
481 break;
482 case VarDecl::Extern:
483 case VarDecl::PrivateExtern:
484 // todo: common
485 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000486 }
Chris Lattner4b009652007-07-25 00:24:17 +0000487 }
488}
489
490/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
491/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000492void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
493 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
494 if (D->isFileVarDecl())
495 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000496}
497
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000498void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
499 // Make sure that this type is translated.
500 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000501}
502
503
Chris Lattnerab862cc2007-08-31 04:31:45 +0000504/// getBuiltinLibFunction
505llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000506 if (BuiltinID > BuiltinFunctions.size())
507 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000508
Chris Lattner9f2d6892007-12-13 00:38:03 +0000509 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
510 // a slot for it.
511 assert(BuiltinID && "Invalid Builtin ID");
512 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000513 if (FunctionSlot)
514 return FunctionSlot;
515
516 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
517
518 // Get the name, skip over the __builtin_ prefix.
519 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
520
521 // Get the type for the builtin.
522 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
523 const llvm::FunctionType *Ty =
524 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
525
526 // FIXME: This has a serious problem with code like this:
527 // void abs() {}
528 // ... __builtin_abs(x);
529 // The two versions of abs will collide. The fix is for the builtin to win,
530 // and for the existing one to be turned into a constantexpr cast of the
531 // builtin. In the case where the existing one is a static function, it
532 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000533 if (llvm::Function *Existing = getModule().getFunction(Name)) {
534 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
535 return FunctionSlot = Existing;
536 assert(Existing == 0 && "FIXME: Name collision");
537 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000538
539 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000540 return FunctionSlot =
541 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
542 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000543}
544
Chris Lattner4b23f942007-12-18 00:25:38 +0000545llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
546 unsigned NumTys) {
547 return llvm::Intrinsic::getDeclaration(&getModule(),
548 (llvm::Intrinsic::ID)IID, Tys, NumTys);
549}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000550
Chris Lattner4b009652007-07-25 00:24:17 +0000551llvm::Function *CodeGenModule::getMemCpyFn() {
552 if (MemCpyFn) return MemCpyFn;
553 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000554 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000555 default: assert(0 && "Unknown ptr width");
556 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
557 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
558 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000559 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000560}
Anders Carlsson36a04872007-08-21 00:21:21 +0000561
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000562llvm::Function *CodeGenModule::getMemSetFn() {
563 if (MemSetFn) return MemSetFn;
564 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000565 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000566 default: assert(0 && "Unknown ptr width");
567 case 32: IID = llvm::Intrinsic::memset_i32; break;
568 case 64: IID = llvm::Intrinsic::memset_i64; break;
569 }
570 return MemSetFn = getIntrinsic(IID);
571}
Chris Lattner4b23f942007-12-18 00:25:38 +0000572
Chris Lattnerab862cc2007-08-31 04:31:45 +0000573llvm::Constant *CodeGenModule::
574GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000575 llvm::StringMapEntry<llvm::Constant *> &Entry =
576 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
577
578 if (Entry.getValue())
579 return Entry.getValue();
580
581 std::vector<llvm::Constant*> Fields;
582
583 if (!CFConstantStringClassRef) {
584 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
585 Ty = llvm::ArrayType::get(Ty, 0);
586
587 CFConstantStringClassRef =
588 new llvm::GlobalVariable(Ty, false,
589 llvm::GlobalVariable::ExternalLinkage, 0,
590 "__CFConstantStringClassReference",
591 &getModule());
592 }
593
594 // Class pointer.
595 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
596 llvm::Constant *Zeros[] = { Zero, Zero };
597 llvm::Constant *C =
598 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
599 Fields.push_back(C);
600
601 // Flags.
602 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
603 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
604
605 // String pointer.
606 C = llvm::ConstantArray::get(str);
607 C = new llvm::GlobalVariable(C->getType(), true,
608 llvm::GlobalValue::InternalLinkage,
609 C, ".str", &getModule());
610
611 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
612 Fields.push_back(C);
613
614 // String length.
615 Ty = getTypes().ConvertType(getContext().LongTy);
616 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
617
618 // The struct.
619 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
620 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000621 llvm::GlobalVariable *GV =
622 new llvm::GlobalVariable(C->getType(), true,
623 llvm::GlobalVariable::InternalLinkage,
624 C, "", &getModule());
625 GV->setSection("__DATA,__cfstring");
626 Entry.setValue(GV);
627 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000628}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000629
Chris Lattnera6dcce32008-02-11 00:02:17 +0000630/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000631static llvm::Constant *GenerateStringLiteral(const std::string &str,
632 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000633 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000634 // Create Constant for this string literal
635 llvm::Constant *C=llvm::ConstantArray::get(str);
636
637 // Create a global variable for this string
638 C = new llvm::GlobalVariable(C->getType(), constant,
639 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000640 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000641 return C;
642}
643
Chris Lattnera6dcce32008-02-11 00:02:17 +0000644/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
645/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000646llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
647 // Don't share any string literals if writable-strings is turned on.
648 if (Features.WritableStrings)
649 return GenerateStringLiteral(str, false, *this);
650
651 llvm::StringMapEntry<llvm::Constant *> &Entry =
652 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
653
654 if (Entry.getValue())
655 return Entry.getValue();
656
657 // Create a global variable for this.
658 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
659 Entry.setValue(C);
660 return C;
661}