blob: b234788a08f81f4015c693745e20a30979a9aac1 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000019#include "clang/Basic/Diagnostic.h"
Chris Lattner45e8cbd2007-11-28 05:34:05 +000020#include "clang/Basic/LangOptions.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000023#include "llvm/CallingConv.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000024#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000026#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Intrinsics.h"
Chris Lattnera1945fa2008-04-30 16:05:42 +000028#include "llvm/Analysis/Verifier.h"
Christopher Lambce39faa2007-12-02 08:49:54 +000029#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattner45e8cbd2007-11-28 05:34:05 +000034CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-12-02 01:40:18 +000035 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000036 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattnerfb97b032007-12-02 01:40:18 +000037 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattner2b94fe32008-03-01 08:45:05 +000038 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
39 //TODO: Make this selectable at runtime
Chris Lattner391d77a2008-03-30 23:03:07 +000040 Runtime = CreateObjCRuntime(M,
41 getTypes().ConvertType(getContext().IntTy),
42 getTypes().ConvertType(getContext().LongTy));
Sanjiv Guptae8b9f5b2008-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 Lattner2b94fe32008-03-01 08:45:05 +000049}
50
51CodeGenModule::~CodeGenModule() {
Chris Lattner391d77a2008-03-30 23:03:07 +000052 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerce5605e2008-03-30 23:25:33 +000053 if (ObjCInitFunction)
Chris Lattner391d77a2008-03-30 23:03:07 +000054 AddGlobalCtor(ObjCInitFunction);
Nate Begeman4c13b7a2008-04-20 06:29:50 +000055 EmitStatics();
Chris Lattner6d397602008-03-14 17:18:18 +000056 EmitGlobalCtors();
Nate Begeman532485c2008-04-18 23:43:57 +000057 EmitAnnotations();
Chris Lattner2b94fe32008-03-01 08:45:05 +000058 delete Runtime;
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +000059 delete DebugInfo;
Chris Lattnera1945fa2008-04-30 16:05:42 +000060 // Run the verifier to check that the generated code is consistent.
61 assert(!verifyModule(TheModule));
Chris Lattner2b94fe32008-03-01 08:45:05 +000062}
Reid Spencer5f016e22007-07-11 17:01:13 +000063
Chris Lattner2c8569d2007-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 Kremenek9c728dc2007-12-12 22:39:36 +000071 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000072 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000073}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000074
Chris Lattnerc6fdc342008-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 Lattner6d397602008-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 Lattner391d77a2008-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 Lattner6d397602008-03-14 17:18:18 +000094void CodeGenModule::EmitGlobalCtors() {
Chris Lattner391d77a2008-03-30 23:03:07 +000095 if (GlobalCtors.empty()) return;
Chris Lattnerce5605e2008-03-30 23:25:33 +000096
Chris Lattner6d397602008-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 Lattnerce5605e2008-03-30 23:25:33 +0000102 llvm::FunctionType* CtorFuncTy =
103 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
104
Chris Lattner6d397602008-03-14 17:18:18 +0000105 // i32, function type pair
Chris Lattner572cf092008-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 Lattner6d397602008-03-14 17:18:18 +0000109 // Array of fields
Chris Lattner572cf092008-03-19 05:24:56 +0000110 llvm::ArrayType* GlobalCtorsTy =
111 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner6d397602008-03-14 17:18:18 +0000112
Chris Lattner6d397602008-03-14 17:18:18 +0000113 // Define the global variable
Chris Lattner572cf092008-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 Lattner6d397602008-03-14 17:18:18 +0000119
120 // Populate the array
121 std::vector<llvm::Constant*> CtorValues;
Chris Lattner572cf092008-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 Lattner6d397602008-03-14 17:18:18 +0000125 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattner572cf092008-03-19 05:24:56 +0000126 E = GlobalCtors.end(); I != E; ++I) {
127 StructValues.clear();
Chris Lattner6d397602008-03-14 17:18:18 +0000128 StructValues.push_back(MagicNumber);
129 StructValues.push_back(*I);
130
Chris Lattner572cf092008-03-19 05:24:56 +0000131 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner6d397602008-03-14 17:18:18 +0000132 }
Chris Lattner572cf092008-03-19 05:24:56 +0000133
134 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
135 CtorValues));
Chris Lattner6d397602008-03-14 17:18:18 +0000136}
137
Chris Lattner391d77a2008-03-30 23:03:07 +0000138
139
Nate Begeman532485c2008-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 Lattner58c3f9e2007-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 Lattner9cd4fe42007-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.
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 llvm::Constant *&Entry = GlobalDeclMap[D];
171 if (Entry) return Entry;
172
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000173 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
174
175 // Check to see if the function already exists.
176 llvm::Function *F = getModule().getFunction(D->getName());
177 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
178
179 // If it doesn't already exist, just create and return an entry.
180 if (F == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000182 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
183 D->getName(), &getModule());
Nate Begemanec9426c2008-03-09 03:09:36 +0000184
185 // Set the appropriate calling convention for the Function.
186 if (D->getAttr<FastCallAttr>())
187 F->setCallingConv(llvm::CallingConv::Fast);
188 return Entry = F;
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 }
190
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000191 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000192 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000193 if (PFTy == F->getType()) return Entry = F;
Chris Lattnerfafad832007-12-02 06:30:46 +0000194
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000195 // If this isn't a definition, just return it casted to the right type.
196 if (!isDefinition)
197 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
198
199 // Otherwise, we have a definition after a prototype with the wrong type.
200 // F is the Function* for the one with the wrong type, we must make a new
201 // Function* and update everything that used F (a declaration) with the new
202 // Function* (which will be a definition).
203 //
204 // This happens if there is a prototype for a function (e.g. "int f()") and
205 // then a definition of a different type (e.g. "int f(int x)"). Start by
206 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif984d0b42008-04-06 20:42:52 +0000207 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000208 llvm::Function::ExternalLinkage,
209 "", &getModule());
210 NewFn->takeName(F);
211
212 // Replace uses of F with the Function we will endow with a body.
213 llvm::Constant *NewPtrForOldDecl =
214 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
215 F->replaceAllUsesWith(NewPtrForOldDecl);
216
217 // FIXME: Update the globaldeclmap for the previous decl of this name. We
218 // really want a way to walk all of these, but we don't have it yet. This
219 // is incredibly slow!
220 ReplaceMapValuesWith(F, NewPtrForOldDecl);
221
222 // Ok, delete the old function now, which is dead.
223 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
224 F->eraseFromParent();
225
226 // Return the new function which has the right type.
227 return Entry = NewFn;
228}
229
Chris Lattnerc4b23a52008-02-05 06:37:34 +0000230static bool IsZeroElementArray(const llvm::Type *Ty) {
231 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
232 return ATy->getNumElements() == 0;
233 return false;
234}
235
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000236llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
237 bool isDefinition) {
238 assert(D->hasGlobalStorage() && "Not a global variable");
239
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000240 // See if it is already in the map.
241 llvm::Constant *&Entry = GlobalDeclMap[D];
242 if (Entry) return Entry;
243
Christopher Lambebb97e92008-02-04 02:31:56 +0000244 QualType ASTTy = D->getType();
245 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000246
247 // Check to see if the global already exists.
Chris Lattner49573782008-02-02 04:43:11 +0000248 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000249
250 // If it doesn't already exist, just create and return an entry.
251 if (GV == 0) {
252 return Entry = new llvm::GlobalVariable(Ty, false,
253 llvm::GlobalValue::ExternalLinkage,
Christopher Lambebb97e92008-02-04 02:31:56 +0000254 0, D->getName(), &getModule(), 0,
255 ASTTy.getAddressSpace());
Chris Lattnerfafad832007-12-02 06:30:46 +0000256 }
257
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000258 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000259 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000260 if (PTy == GV->getType()) return Entry = GV;
261
262 // If this isn't a definition, just return it casted to the right type.
263 if (!isDefinition)
264 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
265
266
267 // Otherwise, we have a definition after a prototype with the wrong type.
268 // GV is the GlobalVariable* for the one with the wrong type, we must make a
269 /// new GlobalVariable* and update everything that used GV (a declaration)
270 // with the new GlobalVariable* (which will be a definition).
271 //
272 // This happens if there is a prototype for a global (e.g. "extern int x[];")
273 // and then a definition of a different type (e.g. "int x[10];"). Start by
274 // making a new global of the correct type, RAUW, then steal the name.
275 llvm::GlobalVariable *NewGV =
276 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lambebb97e92008-02-04 02:31:56 +0000277 0, D->getName(), &getModule(), 0,
278 ASTTy.getAddressSpace());
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000279 NewGV->takeName(GV);
280
281 // Replace uses of GV with the globalvalue we will endow with a body.
282 llvm::Constant *NewPtrForOldDecl =
283 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
284 GV->replaceAllUsesWith(NewPtrForOldDecl);
285
286 // FIXME: Update the globaldeclmap for the previous decl of this name. We
287 // really want a way to walk all of these, but we don't have it yet. This
288 // is incredibly slow!
289 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
290
Chris Lattnerc4b23a52008-02-05 06:37:34 +0000291 // Verify that GV was a declaration or something like x[] which turns into
292 // [0 x type].
293 assert((GV->isDeclaration() ||
294 IsZeroElementArray(GV->getType()->getElementType())) &&
295 "Shouldn't replace non-declaration");
296
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000297 // Ok, delete the old global now, which is dead.
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000298 GV->eraseFromParent();
299
300 // Return the new global which has the right type.
301 return Entry = NewGV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000302}
303
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000304
Chris Lattner391d77a2008-03-30 23:03:07 +0000305void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
306 // If this is not a prototype, emit the body.
307 if (OMD->getBody())
308 CodeGenFunction(*this).GenerateObjCMethod(OMD);
309}
310
Chris Lattner88a69ad2007-07-13 05:13:43 +0000311void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // If this is not a prototype, emit the body.
Chris Lattnera212c562008-05-04 02:29:49 +0000313 if (!FD->isThisDeclarationADefinition())
314 return;
315
316 // If the function is a static, defer code generation until later so we can
317 // easily omit unused statics.
318 if (FD->getStorageClass() != FunctionDecl::Static) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 CodeGenFunction(*this).GenerateCode(FD);
Chris Lattnera212c562008-05-04 02:29:49 +0000320 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000321 }
Chris Lattnera212c562008-05-04 02:29:49 +0000322
323 // We need to check the Module here to see if GetAddrOfFunctionDecl() has
324 // already added this function to the Module because the address of the
325 // function's prototype was taken. If this is the case, call
326 // GetAddrOfFunctionDecl to insert the static FunctionDecl into the used
327 // GlobalDeclsMap, so that EmitStatics will generate code for it later.
328 //
329 // Example:
330 // static int foo();
331 // int bar() { return foo(); }
332 // static int foo() { return 5; }
333 if (getModule().getFunction(FD->getName()))
334 GetAddrOfFunctionDecl(FD, true);
335
336 StaticDecls.push_back(FD);
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000337}
338
339void CodeGenModule::EmitStatics() {
340 // Emit code for each used static decl encountered. Since a previously unused
341 // static decl may become used during the generation of code for a static
342 // function, iterate until no changes are made.
343 bool Changed;
344 do {
345 Changed = false;
346 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
347 // Check the map of used decls for our static. If not found, continue.
348 const Decl *D = StaticDecls[i];
Nate Begeman1a1d92a2008-04-20 20:38:08 +0000349 if (!GlobalDeclMap.count(D))
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000350 continue;
351
352 // If this is a function decl, generate code for the static function if it
353 // has a body. Otherwise, we must have a var decl for a static global
354 // variable.
355 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
356 if (FD->getBody())
357 CodeGenFunction(*this).GenerateCode(FD);
358 } else {
Nate Begeman1a1d92a2008-04-20 20:38:08 +0000359 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000360 }
361 // Erase the used decl from the list.
362 StaticDecls[i] = StaticDecls.back();
363 StaticDecls.pop_back();
364 --i;
365 --e;
366
367 // Remember that we made a change.
368 Changed = true;
369 }
370 } while (Changed);
Reid Spencer5f016e22007-07-11 17:01:13 +0000371}
372
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000373llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
374 return EmitConstantExpr(Expr);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000375}
376
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000377/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
378/// annotation information for a given GlobalValue. The annotation struct is
379/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
380/// GlobalValue being annotated. The second filed is thee constant string
381/// created from the AnnotateAttr's annotation. The third field is a constant
382/// string containing the name of the translation unit. The fourth field is
383/// the line number in the file of the annotated value declaration.
384///
385/// FIXME: this does not unique the annotation string constants, as llvm-gcc
386/// appears to.
387///
388llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
389 const AnnotateAttr *AA,
390 unsigned LineNo) {
391 llvm::Module *M = &getModule();
392
393 // get [N x i8] constants for the annotation string, and the filename string
394 // which are the 2nd and 3rd elements of the global annotation structure.
395 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
396 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
397 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
398 true);
399
400 // Get the two global values corresponding to the ConstantArrays we just
401 // created to hold the bytes of the strings.
402 llvm::GlobalValue *annoGV =
403 new llvm::GlobalVariable(anno->getType(), false,
404 llvm::GlobalValue::InternalLinkage, anno,
405 GV->getName() + ".str", M);
406 // translation unit name string, emitted into the llvm.metadata section.
407 llvm::GlobalValue *unitGV =
408 new llvm::GlobalVariable(unit->getType(), false,
409 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
410
411 // Create the ConstantStruct that is the global annotion.
412 llvm::Constant *Fields[4] = {
413 llvm::ConstantExpr::getBitCast(GV, SBP),
414 llvm::ConstantExpr::getBitCast(annoGV, SBP),
415 llvm::ConstantExpr::getBitCast(unitGV, SBP),
416 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
417 };
418 return llvm::ConstantStruct::get(Fields, 4, false);
419}
420
Steve Naroff248a7532008-04-15 22:42:06 +0000421void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000422 // If the VarDecl is a static, defer code generation until later so we can
423 // easily omit unused statics.
424 if (D->getStorageClass() == VarDecl::Static) {
425 StaticDecls.push_back(D);
426 return;
427 }
428
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000429 // If this is just a forward declaration of the variable, don't emit it now,
430 // allow it to be emitted lazily on its first use.
Chris Lattner88a69ad2007-07-13 05:13:43 +0000431 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
432 return;
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000433
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000434 EmitGlobalVarInit(D);
435}
436
437void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000438 // Get the global, forcing it to be a direct reference.
439 llvm::GlobalVariable *GV =
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000440 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000441
442 // Convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000443 llvm::Constant *Init = 0;
444 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000445 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000446 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000447 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner98be4942008-03-05 18:54:05 +0000448 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner590b6642007-07-15 23:26:56 +0000449 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000450 Init = llvm::ConstantInt::get(Value);
451 }
Devang Patel8e53e722007-10-26 16:31:40 +0000452
Devang Patel9e32d4b2007-10-30 21:27:20 +0000453 if (!Init)
Oliver Hunt28247232007-12-02 00:11:25 +0000454 Init = EmitGlobalInit(D->getInit());
Devang Patel8e53e722007-10-26 16:31:40 +0000455
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000456 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
457 SourceManager &SM = Context.getSourceManager();
458 AddAnnotation(EmitAnnotateAttr(GV, AA,
459 SM.getLogicalLineNumber(D->getLocation())));
460 }
461
Chris Lattnerf89dfb22007-12-10 00:05:55 +0000462 assert(GV->getType()->getElementType() == Init->getType() &&
463 "Initializer codegen type mismatch!");
Chris Lattner88a69ad2007-07-13 05:13:43 +0000464 GV->setInitializer(Init);
Chris Lattnerddee4232008-03-03 03:28:21 +0000465
466 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
467 GV->setVisibility(attr->getVisibility());
468 // FIXME: else handle -fvisibility
Chris Lattner88a69ad2007-07-13 05:13:43 +0000469
470 // Set the llvm linkage type as appropriate.
Chris Lattner8fabd782008-05-04 01:44:26 +0000471 if (D->getStorageClass() == VarDecl::Static)
472 GV->setLinkage(llvm::Function::InternalLinkage);
473 else if (D->getAttr<DLLImportAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000474 GV->setLinkage(llvm::Function::DLLImportLinkage);
475 else if (D->getAttr<DLLExportAttr>())
476 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000477 else if (D->getAttr<WeakAttr>())
Chris Lattnerddee4232008-03-03 03:28:21 +0000478 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner8fabd782008-05-04 01:44:26 +0000479 else {
Chris Lattnerddee4232008-03-03 03:28:21 +0000480 // FIXME: This isn't right. This should handle common linkage and other
481 // stuff.
482 switch (D->getStorageClass()) {
Chris Lattner8fabd782008-05-04 01:44:26 +0000483 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattnerddee4232008-03-03 03:28:21 +0000484 case VarDecl::Auto:
485 case VarDecl::Register:
486 assert(0 && "Can't have auto or register globals");
487 case VarDecl::None:
488 if (!D->getInit())
489 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
490 break;
491 case VarDecl::Extern:
492 case VarDecl::PrivateExtern:
493 // todo: common
494 break;
Chris Lattnerddee4232008-03-03 03:28:21 +0000495 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000496 }
497}
Reid Spencer5f016e22007-07-11 17:01:13 +0000498
Chris Lattner32b266c2007-07-14 00:16:50 +0000499/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
500/// declarator chain.
Steve Naroff248a7532008-04-15 22:42:06 +0000501void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
502 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
503 if (D->isFileVarDecl())
504 EmitGlobalVar(D);
Chris Lattner32b266c2007-07-14 00:16:50 +0000505}
Reid Spencer5f016e22007-07-11 17:01:13 +0000506
Chris Lattnerc5b88062008-02-06 05:08:19 +0000507void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
508 // Make sure that this type is translated.
509 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000510}
511
512
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000513/// getBuiltinLibFunction
514llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000515 if (BuiltinID > BuiltinFunctions.size())
516 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000517
Chris Lattner1426fec2007-12-13 00:38:03 +0000518 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
519 // a slot for it.
520 assert(BuiltinID && "Invalid Builtin ID");
521 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000522 if (FunctionSlot)
523 return FunctionSlot;
524
525 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
526
527 // Get the name, skip over the __builtin_ prefix.
528 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
529
530 // Get the type for the builtin.
531 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
532 const llvm::FunctionType *Ty =
533 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
534
535 // FIXME: This has a serious problem with code like this:
536 // void abs() {}
537 // ... __builtin_abs(x);
538 // The two versions of abs will collide. The fix is for the builtin to win,
539 // and for the existing one to be turned into a constantexpr cast of the
540 // builtin. In the case where the existing one is a static function, it
541 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000542 if (llvm::Function *Existing = getModule().getFunction(Name)) {
543 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
544 return FunctionSlot = Existing;
545 assert(Existing == 0 && "FIXME: Name collision");
546 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000547
548 // FIXME: param attributes for sext/zext etc.
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000549 return FunctionSlot =
550 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
551 &getModule());
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000552}
553
Chris Lattner7acda7c2007-12-18 00:25:38 +0000554llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
555 unsigned NumTys) {
556 return llvm::Intrinsic::getDeclaration(&getModule(),
557 (llvm::Intrinsic::ID)IID, Tys, NumTys);
558}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000559
Reid Spencer5f016e22007-07-11 17:01:13 +0000560llvm::Function *CodeGenModule::getMemCpyFn() {
561 if (MemCpyFn) return MemCpyFn;
562 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000563 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 default: assert(0 && "Unknown ptr width");
565 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
566 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
567 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000568 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000569}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000570
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000571llvm::Function *CodeGenModule::getMemSetFn() {
572 if (MemSetFn) return MemSetFn;
573 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000574 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000575 default: assert(0 && "Unknown ptr width");
576 case 32: IID = llvm::Intrinsic::memset_i32; break;
577 case 64: IID = llvm::Intrinsic::memset_i64; break;
578 }
579 return MemSetFn = getIntrinsic(IID);
580}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000581
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000582llvm::Constant *CodeGenModule::
583GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000584 llvm::StringMapEntry<llvm::Constant *> &Entry =
585 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
586
587 if (Entry.getValue())
588 return Entry.getValue();
589
590 std::vector<llvm::Constant*> Fields;
591
592 if (!CFConstantStringClassRef) {
593 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
594 Ty = llvm::ArrayType::get(Ty, 0);
595
596 CFConstantStringClassRef =
597 new llvm::GlobalVariable(Ty, false,
598 llvm::GlobalVariable::ExternalLinkage, 0,
599 "__CFConstantStringClassReference",
600 &getModule());
601 }
602
603 // Class pointer.
604 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
605 llvm::Constant *Zeros[] = { Zero, Zero };
606 llvm::Constant *C =
607 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
608 Fields.push_back(C);
609
610 // Flags.
611 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
612 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
613
614 // String pointer.
615 C = llvm::ConstantArray::get(str);
616 C = new llvm::GlobalVariable(C->getType(), true,
617 llvm::GlobalValue::InternalLinkage,
618 C, ".str", &getModule());
619
620 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
621 Fields.push_back(C);
622
623 // String length.
624 Ty = getTypes().ConvertType(getContext().LongTy);
625 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
626
627 // The struct.
628 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
629 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000630 llvm::GlobalVariable *GV =
631 new llvm::GlobalVariable(C->getType(), true,
632 llvm::GlobalVariable::InternalLinkage,
633 C, "", &getModule());
634 GV->setSection("__DATA,__cfstring");
635 Entry.setValue(GV);
636 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000637}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000638
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000639/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000640static llvm::Constant *GenerateStringLiteral(const std::string &str,
641 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000642 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000643 // Create Constant for this string literal
644 llvm::Constant *C=llvm::ConstantArray::get(str);
645
646 // Create a global variable for this string
647 C = new llvm::GlobalVariable(C->getType(), constant,
648 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000649 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000650 return C;
651}
652
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000653/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
654/// array containing the literal. The result is pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000655llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
656 // Don't share any string literals if writable-strings is turned on.
657 if (Features.WritableStrings)
658 return GenerateStringLiteral(str, false, *this);
659
660 llvm::StringMapEntry<llvm::Constant *> &Entry =
661 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
662
663 if (Entry.getValue())
664 return Entry.getValue();
665
666 // Create a global variable for this.
667 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
668 Entry.setValue(C);
669 return C;
670}