blob: 7bf1e01b27e9e1b2e5937f701ea04980377cba50 [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
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.h"
Nate Begeman8a704172008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/Intrinsics.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000028#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000029#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattnerdb6be562007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattnercbfb5512008-03-01 08:45:05 +000038 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
39 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000040 Runtime = CreateObjCRuntime(M,
41 getTypes().ConvertType(getContext().IntTy),
42 getTypes().ConvertType(getContext().LongTy));
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000043
44 // If debug info generation is enabled, create the CGDebugInfo object.
45 if (GenerateDebugInfo)
46 DebugInfo = new CGDebugInfo(this);
47 else
48 DebugInfo = NULL;
Chris Lattnercbfb5512008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000052 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000053 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000054 AddGlobalCtor(ObjCInitFunction);
Nate Begemanad320b62008-04-20 06:29:50 +000055 EmitStatics();
Chris Lattner753d2592008-03-14 17:18:18 +000056 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000057 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000058 delete Runtime;
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000059 delete DebugInfo;
Chris Lattnerb033c4a2008-04-30 16:05:42 +000060 // Run the verifier to check that the generated code is consistent.
61 assert(!verifyModule(TheModule));
Chris Lattnercbfb5512008-03-01 08:45:05 +000062}
Chris Lattner4b009652007-07-25 00:24:17 +000063
Chris Lattnercf9c9d02007-12-02 07:19:18 +000064/// WarnUnsupported - Print out a warning that codegen doesn't support the
65/// specified stmt yet.
66void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
67 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
68 "cannot codegen this %0 yet");
69 SourceRange Range = S->getSourceRange();
70 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000071 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000072 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000073}
Chris Lattner0e4755d2007-12-02 06:27:33 +000074
Chris Lattner806a5f52008-01-12 07:05:38 +000075/// WarnUnsupported - Print out a warning that codegen doesn't support the
76/// specified decl yet.
77void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
78 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
79 "cannot codegen this %0 yet");
80 std::string Msg = Type;
81 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
82 &Msg, 1);
83}
84
Chris Lattner753d2592008-03-14 17:18:18 +000085/// AddGlobalCtor - Add a function to the list that will be called before
86/// main() runs.
87void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
88 // TODO: Type coercion of void()* types.
89 GlobalCtors.push_back(Ctor);
90}
91
Chris Lattnerb326b172008-03-30 23:03:07 +000092/// EmitGlobalCtors - Generates the array of contsturctor functions to be
93/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +000094void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +000095 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000096
Chris Lattner753d2592008-03-14 17:18:18 +000097 // Get the type of @llvm.global_ctors
98 std::vector<const llvm::Type*> CtorFields;
99 CtorFields.push_back(llvm::IntegerType::get(32));
100 // Constructor function type
101 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000102 llvm::FunctionType* CtorFuncTy =
103 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
104
Chris Lattner753d2592008-03-14 17:18:18 +0000105 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +0000106 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
107 llvm::StructType* CtorStructTy =
108 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000109 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000110 llvm::ArrayType* GlobalCtorsTy =
111 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000112
Chris Lattner753d2592008-03-14 17:18:18 +0000113 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000114 llvm::GlobalVariable *GlobalCtorsVal =
115 new llvm::GlobalVariable(GlobalCtorsTy, false,
116 llvm::GlobalValue::AppendingLinkage,
117 (llvm::Constant*)0, "llvm.global_ctors",
118 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000119
120 // Populate the array
121 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000122 llvm::Constant *MagicNumber =
123 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
124 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000125 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000126 E = GlobalCtors.end(); I != E; ++I) {
127 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000128 StructValues.push_back(MagicNumber);
129 StructValues.push_back(*I);
130
Chris Lattnera18c12e2008-03-19 05:24:56 +0000131 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000132 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000133
134 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
135 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000136}
137
Chris Lattnerb326b172008-03-30 23:03:07 +0000138
139
Nate Begeman52da5c72008-04-18 23:43:57 +0000140void CodeGenModule::EmitAnnotations() {
141 if (Annotations.empty())
142 return;
143
144 // Create a new global variable for the ConstantStruct in the Module.
145 llvm::Constant *Array =
146 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
147 Annotations.size()),
148 Annotations);
149 llvm::GlobalValue *gv =
150 new llvm::GlobalVariable(Array->getType(), false,
151 llvm::GlobalValue::AppendingLinkage, Array,
152 "llvm.global.annotations", &TheModule);
153 gv->setSection("llvm.metadata");
154}
155
Chris Lattner0e4755d2007-12-02 06:27:33 +0000156/// ReplaceMapValuesWith - This is a really slow and bad function that
157/// searches for any entries in GlobalDeclMap that point to OldVal, changing
158/// them to point to NewVal. This is badbadbad, FIXME!
159void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
160 llvm::Constant *NewVal) {
161 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
162 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
163 if (I->second == OldVal) I->second = NewVal;
164}
165
166
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000167llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
168 bool isDefinition) {
169 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000170 llvm::Constant *&Entry = GlobalDeclMap[D];
Eli Friedman725d2be2008-05-20 09:21:07 +0000171#if 0
172 // FIXME: The cache is currently broken!
Chris Lattner4b009652007-07-25 00:24:17 +0000173 if (Entry) return Entry;
Eli Friedman725d2be2008-05-20 09:21:07 +0000174#endif
175
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000176 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
177
178 // Check to see if the function already exists.
179 llvm::Function *F = getModule().getFunction(D->getName());
180 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
181
182 // If it doesn't already exist, just create and return an entry.
183 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000184 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000185 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
186 D->getName(), &getModule());
Nate Begemandc6262e2008-03-09 03:09:36 +0000187
188 // Set the appropriate calling convention for the Function.
189 if (D->getAttr<FastCallAttr>())
190 F->setCallingConv(llvm::CallingConv::Fast);
191 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000192 }
193
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000194 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000195 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000196 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000197
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000198 // If this isn't a definition, just return it casted to the right type.
199 if (!isDefinition)
200 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
201
202 // Otherwise, we have a definition after a prototype with the wrong type.
203 // F is the Function* for the one with the wrong type, we must make a new
204 // Function* and update everything that used F (a declaration) with the new
205 // Function* (which will be a definition).
206 //
207 // This happens if there is a prototype for a function (e.g. "int f()") and
208 // then a definition of a different type (e.g. "int f(int x)"). Start by
209 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000210 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000211 llvm::Function::ExternalLinkage,
212 "", &getModule());
213 NewFn->takeName(F);
214
215 // Replace uses of F with the Function we will endow with a body.
216 llvm::Constant *NewPtrForOldDecl =
217 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
218 F->replaceAllUsesWith(NewPtrForOldDecl);
219
220 // FIXME: Update the globaldeclmap for the previous decl of this name. We
221 // really want a way to walk all of these, but we don't have it yet. This
222 // is incredibly slow!
223 ReplaceMapValuesWith(F, NewPtrForOldDecl);
224
225 // Ok, delete the old function now, which is dead.
226 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
227 F->eraseFromParent();
228
229 // Return the new function which has the right type.
230 return Entry = NewFn;
231}
232
Chris Lattner0db06992008-02-05 06:37:34 +0000233static bool IsZeroElementArray(const llvm::Type *Ty) {
234 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
235 return ATy->getNumElements() == 0;
236 return false;
237}
238
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000239llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
240 bool isDefinition) {
241 assert(D->hasGlobalStorage() && "Not a global variable");
242
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000243 // See if it is already in the map.
244 llvm::Constant *&Entry = GlobalDeclMap[D];
245 if (Entry) return Entry;
246
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000247 QualType ASTTy = D->getType();
248 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000249
250 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000251 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000252
253 // If it doesn't already exist, just create and return an entry.
254 if (GV == 0) {
255 return Entry = new llvm::GlobalVariable(Ty, false,
256 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000257 0, D->getName(), &getModule(), 0,
258 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000259 }
260
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000261 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000262 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000263 if (PTy == GV->getType()) return Entry = GV;
264
265 // If this isn't a definition, just return it casted to the right type.
266 if (!isDefinition)
267 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
268
269
270 // Otherwise, we have a definition after a prototype with the wrong type.
271 // GV is the GlobalVariable* for the one with the wrong type, we must make a
272 /// new GlobalVariable* and update everything that used GV (a declaration)
273 // with the new GlobalVariable* (which will be a definition).
274 //
275 // This happens if there is a prototype for a global (e.g. "extern int x[];")
276 // and then a definition of a different type (e.g. "int x[10];"). Start by
277 // making a new global of the correct type, RAUW, then steal the name.
278 llvm::GlobalVariable *NewGV =
279 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000280 0, D->getName(), &getModule(), 0,
281 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000282 NewGV->takeName(GV);
283
284 // Replace uses of GV with the globalvalue we will endow with a body.
285 llvm::Constant *NewPtrForOldDecl =
286 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
287 GV->replaceAllUsesWith(NewPtrForOldDecl);
288
289 // FIXME: Update the globaldeclmap for the previous decl of this name. We
290 // really want a way to walk all of these, but we don't have it yet. This
291 // is incredibly slow!
292 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
293
Chris Lattner0db06992008-02-05 06:37:34 +0000294 // Verify that GV was a declaration or something like x[] which turns into
295 // [0 x type].
296 assert((GV->isDeclaration() ||
297 IsZeroElementArray(GV->getType()->getElementType())) &&
298 "Shouldn't replace non-declaration");
299
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000300 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000301 GV->eraseFromParent();
302
303 // Return the new global which has the right type.
304 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000305}
306
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000307
Chris Lattnerb326b172008-03-30 23:03:07 +0000308void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
309 // If this is not a prototype, emit the body.
310 if (OMD->getBody())
311 CodeGenFunction(*this).GenerateObjCMethod(OMD);
312}
313
Chris Lattner4b009652007-07-25 00:24:17 +0000314void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
315 // If this is not a prototype, emit the body.
Chris Lattner74bf5552008-05-04 02:29:49 +0000316 if (!FD->isThisDeclarationADefinition())
317 return;
318
319 // If the function is a static, defer code generation until later so we can
320 // easily omit unused statics.
321 if (FD->getStorageClass() != FunctionDecl::Static) {
Chris Lattner4b009652007-07-25 00:24:17 +0000322 CodeGenFunction(*this).GenerateCode(FD);
Chris Lattner74bf5552008-05-04 02:29:49 +0000323 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000324 }
Chris Lattner74bf5552008-05-04 02:29:49 +0000325
326 // We need to check the Module here to see if GetAddrOfFunctionDecl() has
327 // already added this function to the Module because the address of the
328 // function's prototype was taken. If this is the case, call
329 // GetAddrOfFunctionDecl to insert the static FunctionDecl into the used
330 // GlobalDeclsMap, so that EmitStatics will generate code for it later.
331 //
332 // Example:
333 // static int foo();
334 // int bar() { return foo(); }
335 // static int foo() { return 5; }
336 if (getModule().getFunction(FD->getName()))
337 GetAddrOfFunctionDecl(FD, true);
338
339 StaticDecls.push_back(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000340}
341
342void CodeGenModule::EmitStatics() {
343 // Emit code for each used static decl encountered. Since a previously unused
344 // static decl may become used during the generation of code for a static
345 // function, iterate until no changes are made.
346 bool Changed;
347 do {
348 Changed = false;
349 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
350 // Check the map of used decls for our static. If not found, continue.
351 const Decl *D = StaticDecls[i];
Nate Begeman91f52012008-04-20 20:38:08 +0000352 if (!GlobalDeclMap.count(D))
Nate Begemanad320b62008-04-20 06:29:50 +0000353 continue;
354
355 // If this is a function decl, generate code for the static function if it
356 // has a body. Otherwise, we must have a var decl for a static global
357 // variable.
358 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
359 if (FD->getBody())
360 CodeGenFunction(*this).GenerateCode(FD);
361 } else {
Nate Begeman91f52012008-04-20 20:38:08 +0000362 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begemanad320b62008-04-20 06:29:50 +0000363 }
364 // Erase the used decl from the list.
365 StaticDecls[i] = StaticDecls.back();
366 StaticDecls.pop_back();
367 --i;
368 --e;
369
370 // Remember that we made a change.
371 Changed = true;
372 }
373 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000374}
375
Anders Carlssond76cead2008-01-26 01:36:00 +0000376llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
377 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000378}
379
Nate Begeman8a704172008-04-19 04:17:09 +0000380/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
381/// annotation information for a given GlobalValue. The annotation struct is
382/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
383/// GlobalValue being annotated. The second filed is thee constant string
384/// created from the AnnotateAttr's annotation. The third field is a constant
385/// string containing the name of the translation unit. The fourth field is
386/// the line number in the file of the annotated value declaration.
387///
388/// FIXME: this does not unique the annotation string constants, as llvm-gcc
389/// appears to.
390///
391llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
392 const AnnotateAttr *AA,
393 unsigned LineNo) {
394 llvm::Module *M = &getModule();
395
396 // get [N x i8] constants for the annotation string, and the filename string
397 // which are the 2nd and 3rd elements of the global annotation structure.
398 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
399 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
400 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
401 true);
402
403 // Get the two global values corresponding to the ConstantArrays we just
404 // created to hold the bytes of the strings.
405 llvm::GlobalValue *annoGV =
406 new llvm::GlobalVariable(anno->getType(), false,
407 llvm::GlobalValue::InternalLinkage, anno,
408 GV->getName() + ".str", M);
409 // translation unit name string, emitted into the llvm.metadata section.
410 llvm::GlobalValue *unitGV =
411 new llvm::GlobalVariable(unit->getType(), false,
412 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
413
414 // Create the ConstantStruct that is the global annotion.
415 llvm::Constant *Fields[4] = {
416 llvm::ConstantExpr::getBitCast(GV, SBP),
417 llvm::ConstantExpr::getBitCast(annoGV, SBP),
418 llvm::ConstantExpr::getBitCast(unitGV, SBP),
419 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
420 };
421 return llvm::ConstantStruct::get(Fields, 4, false);
422}
423
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000424void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000425 // If the VarDecl is a static, defer code generation until later so we can
426 // easily omit unused statics.
427 if (D->getStorageClass() == VarDecl::Static) {
428 StaticDecls.push_back(D);
429 return;
430 }
431
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000432 // If this is just a forward declaration of the variable, don't emit it now,
433 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000434 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
435 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000436
Nate Begemanad320b62008-04-20 06:29:50 +0000437 EmitGlobalVarInit(D);
438}
439
440void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000441 // Get the global, forcing it to be a direct reference.
442 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000443 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000444
445 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000446 llvm::Constant *Init = 0;
447 if (D->getInit() == 0) {
448 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
449 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000450 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000451 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000452 if (D->getInit()->isIntegerConstantExpr(Value, Context))
453 Init = llvm::ConstantInt::get(Value);
454 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000455
Devang Patel08a10cc2007-10-30 21:27:20 +0000456 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000457 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000458
Nate Begeman8a704172008-04-19 04:17:09 +0000459 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
460 SourceManager &SM = Context.getSourceManager();
461 AddAnnotation(EmitAnnotateAttr(GV, AA,
462 SM.getLogicalLineNumber(D->getLocation())));
463 }
464
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000465 assert(GV->getType()->getElementType() == Init->getType() &&
466 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000467 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000468
469 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
470 GV->setVisibility(attr->getVisibility());
471 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000472
473 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000474 if (D->getStorageClass() == VarDecl::Static)
475 GV->setLinkage(llvm::Function::InternalLinkage);
476 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000477 GV->setLinkage(llvm::Function::DLLImportLinkage);
478 else if (D->getAttr<DLLExportAttr>())
479 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000480 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000481 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000482 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000483 // FIXME: This isn't right. This should handle common linkage and other
484 // stuff.
485 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000486 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000487 case VarDecl::Auto:
488 case VarDecl::Register:
489 assert(0 && "Can't have auto or register globals");
490 case VarDecl::None:
491 if (!D->getInit())
492 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
493 break;
494 case VarDecl::Extern:
495 case VarDecl::PrivateExtern:
496 // todo: common
497 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000498 }
Chris Lattner4b009652007-07-25 00:24:17 +0000499 }
500}
501
502/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
503/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000504void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
505 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
506 if (D->isFileVarDecl())
507 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000508}
509
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000510void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
511 // Make sure that this type is translated.
512 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000513}
514
515
Chris Lattnerab862cc2007-08-31 04:31:45 +0000516/// getBuiltinLibFunction
517llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000518 if (BuiltinID > BuiltinFunctions.size())
519 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000520
Chris Lattner9f2d6892007-12-13 00:38:03 +0000521 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
522 // a slot for it.
523 assert(BuiltinID && "Invalid Builtin ID");
524 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000525 if (FunctionSlot)
526 return FunctionSlot;
527
528 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
529
530 // Get the name, skip over the __builtin_ prefix.
531 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
532
533 // Get the type for the builtin.
534 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
535 const llvm::FunctionType *Ty =
536 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
537
538 // FIXME: This has a serious problem with code like this:
539 // void abs() {}
540 // ... __builtin_abs(x);
541 // The two versions of abs will collide. The fix is for the builtin to win,
542 // and for the existing one to be turned into a constantexpr cast of the
543 // builtin. In the case where the existing one is a static function, it
544 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000545 if (llvm::Function *Existing = getModule().getFunction(Name)) {
546 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
547 return FunctionSlot = Existing;
548 assert(Existing == 0 && "FIXME: Name collision");
549 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000550
551 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000552 return FunctionSlot =
553 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
554 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000555}
556
Chris Lattner4b23f942007-12-18 00:25:38 +0000557llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
558 unsigned NumTys) {
559 return llvm::Intrinsic::getDeclaration(&getModule(),
560 (llvm::Intrinsic::ID)IID, Tys, NumTys);
561}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000562
Chris Lattner4b009652007-07-25 00:24:17 +0000563llvm::Function *CodeGenModule::getMemCpyFn() {
564 if (MemCpyFn) return MemCpyFn;
565 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000566 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000567 default: assert(0 && "Unknown ptr width");
568 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
569 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
570 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000571 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000572}
Anders Carlsson36a04872007-08-21 00:21:21 +0000573
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000574llvm::Function *CodeGenModule::getMemSetFn() {
575 if (MemSetFn) return MemSetFn;
576 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000577 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000578 default: assert(0 && "Unknown ptr width");
579 case 32: IID = llvm::Intrinsic::memset_i32; break;
580 case 64: IID = llvm::Intrinsic::memset_i64; break;
581 }
582 return MemSetFn = getIntrinsic(IID);
583}
Chris Lattner4b23f942007-12-18 00:25:38 +0000584
Chris Lattnerab862cc2007-08-31 04:31:45 +0000585llvm::Constant *CodeGenModule::
586GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000587 llvm::StringMapEntry<llvm::Constant *> &Entry =
588 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
589
590 if (Entry.getValue())
591 return Entry.getValue();
592
593 std::vector<llvm::Constant*> Fields;
594
595 if (!CFConstantStringClassRef) {
596 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
597 Ty = llvm::ArrayType::get(Ty, 0);
598
599 CFConstantStringClassRef =
600 new llvm::GlobalVariable(Ty, false,
601 llvm::GlobalVariable::ExternalLinkage, 0,
602 "__CFConstantStringClassReference",
603 &getModule());
604 }
605
606 // Class pointer.
607 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
608 llvm::Constant *Zeros[] = { Zero, Zero };
609 llvm::Constant *C =
610 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
611 Fields.push_back(C);
612
613 // Flags.
614 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
615 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
616
617 // String pointer.
618 C = llvm::ConstantArray::get(str);
619 C = new llvm::GlobalVariable(C->getType(), true,
620 llvm::GlobalValue::InternalLinkage,
621 C, ".str", &getModule());
622
623 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
624 Fields.push_back(C);
625
626 // String length.
627 Ty = getTypes().ConvertType(getContext().LongTy);
628 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
629
630 // The struct.
631 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
632 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000633 llvm::GlobalVariable *GV =
634 new llvm::GlobalVariable(C->getType(), true,
635 llvm::GlobalVariable::InternalLinkage,
636 C, "", &getModule());
637 GV->setSection("__DATA,__cfstring");
638 Entry.setValue(GV);
639 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000640}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000641
Chris Lattnera6dcce32008-02-11 00:02:17 +0000642/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000643static llvm::Constant *GenerateStringLiteral(const std::string &str,
644 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000645 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000646 // Create Constant for this string literal
647 llvm::Constant *C=llvm::ConstantArray::get(str);
648
649 // Create a global variable for this string
650 C = new llvm::GlobalVariable(C->getType(), constant,
651 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000652 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000653 return C;
654}
655
Chris Lattnera6dcce32008-02-11 00:02:17 +0000656/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
657/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000658llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
659 // Don't share any string literals if writable-strings is turned on.
660 if (Features.WritableStrings)
661 return GenerateStringLiteral(str, false, *this);
662
663 llvm::StringMapEntry<llvm::Constant *> &Entry =
664 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
665
666 if (Entry.getValue())
667 return Entry.getValue();
668
669 // Create a global variable for this.
670 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
671 Entry.setValue(C);
672 return C;
673}