blob: da38698ab61382c92d59e8a0f10bc62003fc3f0a [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Chris Lattnercf9c9d02007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattnerdb6be562007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Nate Begeman8a704172008-04-19 04:17:09 +000020#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000022#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000025#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000026#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000027#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattnerdb6be562007-11-28 05:34:05 +000032CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000033 llvm::Module &M, const llvm::TargetData &TD,
34 Diagnostic &diags)
35 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattnercbfb5512008-03-01 08:45:05 +000036 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
37 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000038 Runtime = CreateObjCRuntime(M,
39 getTypes().ConvertType(getContext().IntTy),
40 getTypes().ConvertType(getContext().LongTy));
Chris Lattnercbfb5512008-03-01 08:45:05 +000041}
42
43CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000044 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000045 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000046 AddGlobalCtor(ObjCInitFunction);
Chris Lattner753d2592008-03-14 17:18:18 +000047 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000048 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000049 delete Runtime;
50}
Chris Lattner4b009652007-07-25 00:24:17 +000051
Chris Lattnercf9c9d02007-12-02 07:19:18 +000052/// WarnUnsupported - Print out a warning that codegen doesn't support the
53/// specified stmt yet.
54void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
55 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
56 "cannot codegen this %0 yet");
57 SourceRange Range = S->getSourceRange();
58 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000059 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000060 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000061}
Chris Lattner0e4755d2007-12-02 06:27:33 +000062
Chris Lattner806a5f52008-01-12 07:05:38 +000063/// WarnUnsupported - Print out a warning that codegen doesn't support the
64/// specified decl yet.
65void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
66 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
67 "cannot codegen this %0 yet");
68 std::string Msg = Type;
69 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
70 &Msg, 1);
71}
72
Chris Lattner753d2592008-03-14 17:18:18 +000073/// AddGlobalCtor - Add a function to the list that will be called before
74/// main() runs.
75void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
76 // TODO: Type coercion of void()* types.
77 GlobalCtors.push_back(Ctor);
78}
79
Chris Lattnerb326b172008-03-30 23:03:07 +000080/// EmitGlobalCtors - Generates the array of contsturctor functions to be
81/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +000082void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +000083 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000084
Chris Lattner753d2592008-03-14 17:18:18 +000085 // Get the type of @llvm.global_ctors
86 std::vector<const llvm::Type*> CtorFields;
87 CtorFields.push_back(llvm::IntegerType::get(32));
88 // Constructor function type
89 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000090 llvm::FunctionType* CtorFuncTy =
91 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
92
Chris Lattner753d2592008-03-14 17:18:18 +000093 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +000094 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
95 llvm::StructType* CtorStructTy =
96 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +000097 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +000098 llvm::ArrayType* GlobalCtorsTy =
99 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000100
Chris Lattner753d2592008-03-14 17:18:18 +0000101 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000102 llvm::GlobalVariable *GlobalCtorsVal =
103 new llvm::GlobalVariable(GlobalCtorsTy, false,
104 llvm::GlobalValue::AppendingLinkage,
105 (llvm::Constant*)0, "llvm.global_ctors",
106 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000107
108 // Populate the array
109 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000110 llvm::Constant *MagicNumber =
111 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
112 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000113 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000114 E = GlobalCtors.end(); I != E; ++I) {
115 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000116 StructValues.push_back(MagicNumber);
117 StructValues.push_back(*I);
118
Chris Lattnera18c12e2008-03-19 05:24:56 +0000119 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000120 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000121
122 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
123 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000124}
125
Chris Lattnerb326b172008-03-30 23:03:07 +0000126
127
Nate Begeman52da5c72008-04-18 23:43:57 +0000128void CodeGenModule::EmitAnnotations() {
129 if (Annotations.empty())
130 return;
131
132 // Create a new global variable for the ConstantStruct in the Module.
133 llvm::Constant *Array =
134 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
135 Annotations.size()),
136 Annotations);
137 llvm::GlobalValue *gv =
138 new llvm::GlobalVariable(Array->getType(), false,
139 llvm::GlobalValue::AppendingLinkage, Array,
140 "llvm.global.annotations", &TheModule);
141 gv->setSection("llvm.metadata");
142}
143
Chris Lattner0e4755d2007-12-02 06:27:33 +0000144/// ReplaceMapValuesWith - This is a really slow and bad function that
145/// searches for any entries in GlobalDeclMap that point to OldVal, changing
146/// them to point to NewVal. This is badbadbad, FIXME!
147void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
148 llvm::Constant *NewVal) {
149 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
150 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
151 if (I->second == OldVal) I->second = NewVal;
152}
153
154
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000155llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
156 bool isDefinition) {
157 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000158 llvm::Constant *&Entry = GlobalDeclMap[D];
159 if (Entry) return Entry;
160
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000161 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
162
163 // Check to see if the function already exists.
164 llvm::Function *F = getModule().getFunction(D->getName());
165 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
166
167 // If it doesn't already exist, just create and return an entry.
168 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000169 // FIXME: param attributes for sext/zext etc.
Gabor Greif815e2c12008-04-06 20:42:52 +0000170 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, D->getName(),
Nate Begemandc6262e2008-03-09 03:09:36 +0000171 &getModule());
172
173 // Set the appropriate calling convention for the Function.
174 if (D->getAttr<FastCallAttr>())
175 F->setCallingConv(llvm::CallingConv::Fast);
176 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000177 }
178
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000179 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000180 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000181 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000182
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000183 // If this isn't a definition, just return it casted to the right type.
184 if (!isDefinition)
185 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
186
187 // Otherwise, we have a definition after a prototype with the wrong type.
188 // F is the Function* for the one with the wrong type, we must make a new
189 // Function* and update everything that used F (a declaration) with the new
190 // Function* (which will be a definition).
191 //
192 // This happens if there is a prototype for a function (e.g. "int f()") and
193 // then a definition of a different type (e.g. "int f(int x)"). Start by
194 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000195 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000196 llvm::Function::ExternalLinkage,
197 "", &getModule());
198 NewFn->takeName(F);
199
200 // Replace uses of F with the Function we will endow with a body.
201 llvm::Constant *NewPtrForOldDecl =
202 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
203 F->replaceAllUsesWith(NewPtrForOldDecl);
204
205 // FIXME: Update the globaldeclmap for the previous decl of this name. We
206 // really want a way to walk all of these, but we don't have it yet. This
207 // is incredibly slow!
208 ReplaceMapValuesWith(F, NewPtrForOldDecl);
209
210 // Ok, delete the old function now, which is dead.
211 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
212 F->eraseFromParent();
213
214 // Return the new function which has the right type.
215 return Entry = NewFn;
216}
217
Chris Lattner0db06992008-02-05 06:37:34 +0000218static bool IsZeroElementArray(const llvm::Type *Ty) {
219 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
220 return ATy->getNumElements() == 0;
221 return false;
222}
223
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000224llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
225 bool isDefinition) {
226 assert(D->hasGlobalStorage() && "Not a global variable");
227
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000228 // See if it is already in the map.
229 llvm::Constant *&Entry = GlobalDeclMap[D];
230 if (Entry) return Entry;
231
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000232 QualType ASTTy = D->getType();
233 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000234
235 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000236 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000237
238 // If it doesn't already exist, just create and return an entry.
239 if (GV == 0) {
240 return Entry = new llvm::GlobalVariable(Ty, false,
241 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000242 0, D->getName(), &getModule(), 0,
243 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000244 }
245
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000246 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000247 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000248 if (PTy == GV->getType()) return Entry = GV;
249
250 // If this isn't a definition, just return it casted to the right type.
251 if (!isDefinition)
252 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
253
254
255 // Otherwise, we have a definition after a prototype with the wrong type.
256 // GV is the GlobalVariable* for the one with the wrong type, we must make a
257 /// new GlobalVariable* and update everything that used GV (a declaration)
258 // with the new GlobalVariable* (which will be a definition).
259 //
260 // This happens if there is a prototype for a global (e.g. "extern int x[];")
261 // and then a definition of a different type (e.g. "int x[10];"). Start by
262 // making a new global of the correct type, RAUW, then steal the name.
263 llvm::GlobalVariable *NewGV =
264 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000265 0, D->getName(), &getModule(), 0,
266 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000267 NewGV->takeName(GV);
268
269 // Replace uses of GV with the globalvalue we will endow with a body.
270 llvm::Constant *NewPtrForOldDecl =
271 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
272 GV->replaceAllUsesWith(NewPtrForOldDecl);
273
274 // FIXME: Update the globaldeclmap for the previous decl of this name. We
275 // really want a way to walk all of these, but we don't have it yet. This
276 // is incredibly slow!
277 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
278
Chris Lattner0db06992008-02-05 06:37:34 +0000279 // Verify that GV was a declaration or something like x[] which turns into
280 // [0 x type].
281 assert((GV->isDeclaration() ||
282 IsZeroElementArray(GV->getType()->getElementType())) &&
283 "Shouldn't replace non-declaration");
284
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000285 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000286 GV->eraseFromParent();
287
288 // Return the new global which has the right type.
289 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000290}
291
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000292
Chris Lattnerb326b172008-03-30 23:03:07 +0000293void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
294 // If this is not a prototype, emit the body.
295 if (OMD->getBody())
296 CodeGenFunction(*this).GenerateObjCMethod(OMD);
297}
298
Chris Lattner4b009652007-07-25 00:24:17 +0000299void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
300 // If this is not a prototype, emit the body.
301 if (FD->getBody())
302 CodeGenFunction(*this).GenerateCode(FD);
303}
304
Anders Carlssond76cead2008-01-26 01:36:00 +0000305llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
306 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000307}
308
Nate Begeman8a704172008-04-19 04:17:09 +0000309/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
310/// annotation information for a given GlobalValue. The annotation struct is
311/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
312/// GlobalValue being annotated. The second filed is thee constant string
313/// created from the AnnotateAttr's annotation. The third field is a constant
314/// string containing the name of the translation unit. The fourth field is
315/// the line number in the file of the annotated value declaration.
316///
317/// FIXME: this does not unique the annotation string constants, as llvm-gcc
318/// appears to.
319///
320llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
321 const AnnotateAttr *AA,
322 unsigned LineNo) {
323 llvm::Module *M = &getModule();
324
325 // get [N x i8] constants for the annotation string, and the filename string
326 // which are the 2nd and 3rd elements of the global annotation structure.
327 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
328 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
329 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
330 true);
331
332 // Get the two global values corresponding to the ConstantArrays we just
333 // created to hold the bytes of the strings.
334 llvm::GlobalValue *annoGV =
335 new llvm::GlobalVariable(anno->getType(), false,
336 llvm::GlobalValue::InternalLinkage, anno,
337 GV->getName() + ".str", M);
338 // translation unit name string, emitted into the llvm.metadata section.
339 llvm::GlobalValue *unitGV =
340 new llvm::GlobalVariable(unit->getType(), false,
341 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
342
343 // Create the ConstantStruct that is the global annotion.
344 llvm::Constant *Fields[4] = {
345 llvm::ConstantExpr::getBitCast(GV, SBP),
346 llvm::ConstantExpr::getBitCast(annoGV, SBP),
347 llvm::ConstantExpr::getBitCast(unitGV, SBP),
348 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
349 };
350 return llvm::ConstantStruct::get(Fields, 4, false);
351}
352
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000353void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000354 // If this is just a forward declaration of the variable, don't emit it now,
355 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000356 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
357 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000358
359 // Get the global, forcing it to be a direct reference.
360 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000361 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000362
363 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000364 llvm::Constant *Init = 0;
365 if (D->getInit() == 0) {
366 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
367 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000368 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000369 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000370 if (D->getInit()->isIntegerConstantExpr(Value, Context))
371 Init = llvm::ConstantInt::get(Value);
372 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000373
Devang Patel08a10cc2007-10-30 21:27:20 +0000374 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000375 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000376
Nate Begeman8a704172008-04-19 04:17:09 +0000377 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
378 SourceManager &SM = Context.getSourceManager();
379 AddAnnotation(EmitAnnotateAttr(GV, AA,
380 SM.getLogicalLineNumber(D->getLocation())));
381 }
382
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000383 assert(GV->getType()->getElementType() == Init->getType() &&
384 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000385 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000386
387 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
388 GV->setVisibility(attr->getVisibility());
389 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000390
391 // Set the llvm linkage type as appropriate.
Chris Lattner402b3372008-03-03 03:28:21 +0000392 if (D->getAttr<DLLImportAttr>())
393 GV->setLinkage(llvm::Function::DLLImportLinkage);
394 else if (D->getAttr<DLLExportAttr>())
395 GV->setLinkage(llvm::Function::DLLExportLinkage);
396 else if (D->getAttr<WeakAttr>()) {
397 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
398
399 } else {
400 // FIXME: This isn't right. This should handle common linkage and other
401 // stuff.
402 switch (D->getStorageClass()) {
403 case VarDecl::Auto:
404 case VarDecl::Register:
405 assert(0 && "Can't have auto or register globals");
406 case VarDecl::None:
407 if (!D->getInit())
408 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
409 break;
410 case VarDecl::Extern:
411 case VarDecl::PrivateExtern:
412 // todo: common
413 break;
414 case VarDecl::Static:
415 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
416 break;
417 }
Chris Lattner4b009652007-07-25 00:24:17 +0000418 }
419}
420
421/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
422/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000423void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
424 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
425 if (D->isFileVarDecl())
426 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000427}
428
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000429void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
430 // Make sure that this type is translated.
431 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000432}
433
434
Chris Lattnerab862cc2007-08-31 04:31:45 +0000435/// getBuiltinLibFunction
436llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000437 if (BuiltinID > BuiltinFunctions.size())
438 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000439
Chris Lattner9f2d6892007-12-13 00:38:03 +0000440 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
441 // a slot for it.
442 assert(BuiltinID && "Invalid Builtin ID");
443 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000444 if (FunctionSlot)
445 return FunctionSlot;
446
447 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
448
449 // Get the name, skip over the __builtin_ prefix.
450 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
451
452 // Get the type for the builtin.
453 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
454 const llvm::FunctionType *Ty =
455 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
456
457 // FIXME: This has a serious problem with code like this:
458 // void abs() {}
459 // ... __builtin_abs(x);
460 // The two versions of abs will collide. The fix is for the builtin to win,
461 // and for the existing one to be turned into a constantexpr cast of the
462 // builtin. In the case where the existing one is a static function, it
463 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000464 if (llvm::Function *Existing = getModule().getFunction(Name)) {
465 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
466 return FunctionSlot = Existing;
467 assert(Existing == 0 && "FIXME: Name collision");
468 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000469
470 // FIXME: param attributes for sext/zext etc.
Gabor Greif815e2c12008-04-06 20:42:52 +0000471 return FunctionSlot = llvm::Function::Create(Ty, llvm::Function::ExternalLinkage,
Chris Lattnerab862cc2007-08-31 04:31:45 +0000472 Name, &getModule());
473}
474
Chris Lattner4b23f942007-12-18 00:25:38 +0000475llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
476 unsigned NumTys) {
477 return llvm::Intrinsic::getDeclaration(&getModule(),
478 (llvm::Intrinsic::ID)IID, Tys, NumTys);
479}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000480
Chris Lattner4b009652007-07-25 00:24:17 +0000481llvm::Function *CodeGenModule::getMemCpyFn() {
482 if (MemCpyFn) return MemCpyFn;
483 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000484 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000485 default: assert(0 && "Unknown ptr width");
486 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
487 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
488 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000489 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000490}
Anders Carlsson36a04872007-08-21 00:21:21 +0000491
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000492llvm::Function *CodeGenModule::getMemSetFn() {
493 if (MemSetFn) return MemSetFn;
494 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000495 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000496 default: assert(0 && "Unknown ptr width");
497 case 32: IID = llvm::Intrinsic::memset_i32; break;
498 case 64: IID = llvm::Intrinsic::memset_i64; break;
499 }
500 return MemSetFn = getIntrinsic(IID);
501}
Chris Lattner4b23f942007-12-18 00:25:38 +0000502
Chris Lattnerab862cc2007-08-31 04:31:45 +0000503llvm::Constant *CodeGenModule::
504GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000505 llvm::StringMapEntry<llvm::Constant *> &Entry =
506 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
507
508 if (Entry.getValue())
509 return Entry.getValue();
510
511 std::vector<llvm::Constant*> Fields;
512
513 if (!CFConstantStringClassRef) {
514 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
515 Ty = llvm::ArrayType::get(Ty, 0);
516
517 CFConstantStringClassRef =
518 new llvm::GlobalVariable(Ty, false,
519 llvm::GlobalVariable::ExternalLinkage, 0,
520 "__CFConstantStringClassReference",
521 &getModule());
522 }
523
524 // Class pointer.
525 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
526 llvm::Constant *Zeros[] = { Zero, Zero };
527 llvm::Constant *C =
528 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
529 Fields.push_back(C);
530
531 // Flags.
532 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
533 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
534
535 // String pointer.
536 C = llvm::ConstantArray::get(str);
537 C = new llvm::GlobalVariable(C->getType(), true,
538 llvm::GlobalValue::InternalLinkage,
539 C, ".str", &getModule());
540
541 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
542 Fields.push_back(C);
543
544 // String length.
545 Ty = getTypes().ConvertType(getContext().LongTy);
546 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
547
548 // The struct.
549 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
550 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000551 llvm::GlobalVariable *GV =
552 new llvm::GlobalVariable(C->getType(), true,
553 llvm::GlobalVariable::InternalLinkage,
554 C, "", &getModule());
555 GV->setSection("__DATA,__cfstring");
556 Entry.setValue(GV);
557 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000558}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000559
Chris Lattnera6dcce32008-02-11 00:02:17 +0000560/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000561static llvm::Constant *GenerateStringLiteral(const std::string &str,
562 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000563 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000564 // Create Constant for this string literal
565 llvm::Constant *C=llvm::ConstantArray::get(str);
566
567 // Create a global variable for this string
568 C = new llvm::GlobalVariable(C->getType(), constant,
569 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000570 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000571 return C;
572}
573
Chris Lattnera6dcce32008-02-11 00:02:17 +0000574/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
575/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000576llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
577 // Don't share any string literals if writable-strings is turned on.
578 if (Features.WritableStrings)
579 return GenerateStringLiteral(str, false, *this);
580
581 llvm::StringMapEntry<llvm::Constant *> &Entry =
582 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
583
584 if (Entry.getValue())
585 return Entry.getValue();
586
587 // Create a global variable for this.
588 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
589 Entry.setValue(C);
590 return C;
591}