blob: a5a51b19c7961ce6bb529e8157a677e02b2ae750 [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"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Basic/TargetInfo.h"
Nate Begemandc6262e2008-03-09 03:09:36 +000021#include "llvm/CallingConv.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000025#include "llvm/Intrinsics.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000026#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28using namespace CodeGen;
29
30
Chris Lattnerdb6be562007-11-28 05:34:05 +000031CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000032 llvm::Module &M, const llvm::TargetData &TD,
33 Diagnostic &diags)
34 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Chris Lattnercbfb5512008-03-01 08:45:05 +000035 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
36 //TODO: Make this selectable at runtime
Chris Lattnerb326b172008-03-30 23:03:07 +000037 Runtime = CreateObjCRuntime(M,
38 getTypes().ConvertType(getContext().IntTy),
39 getTypes().ConvertType(getContext().LongTy));
Chris Lattnercbfb5512008-03-01 08:45:05 +000040}
41
42CodeGenModule::~CodeGenModule() {
Chris Lattnerb326b172008-03-30 23:03:07 +000043 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000044 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000045 AddGlobalCtor(ObjCInitFunction);
Chris Lattner753d2592008-03-14 17:18:18 +000046 EmitGlobalCtors();
Nate Begeman52da5c72008-04-18 23:43:57 +000047 EmitAnnotations();
Chris Lattnercbfb5512008-03-01 08:45:05 +000048 delete Runtime;
49}
Chris Lattner4b009652007-07-25 00:24:17 +000050
Chris Lattnercf9c9d02007-12-02 07:19:18 +000051/// WarnUnsupported - Print out a warning that codegen doesn't support the
52/// specified stmt yet.
53void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
54 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
55 "cannot codegen this %0 yet");
56 SourceRange Range = S->getSourceRange();
57 std::string Msg = Type;
Ted Kremenekd7f64cd2007-12-12 22:39:36 +000058 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenekb3ee1932007-12-11 21:27:55 +000059 &Msg, 1, &Range, 1);
Chris Lattnercf9c9d02007-12-02 07:19:18 +000060}
Chris Lattner0e4755d2007-12-02 06:27:33 +000061
Chris Lattner806a5f52008-01-12 07:05:38 +000062/// WarnUnsupported - Print out a warning that codegen doesn't support the
63/// specified decl yet.
64void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
65 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
66 "cannot codegen this %0 yet");
67 std::string Msg = Type;
68 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
69 &Msg, 1);
70}
71
Chris Lattner753d2592008-03-14 17:18:18 +000072/// AddGlobalCtor - Add a function to the list that will be called before
73/// main() runs.
74void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
75 // TODO: Type coercion of void()* types.
76 GlobalCtors.push_back(Ctor);
77}
78
Chris Lattnerb326b172008-03-30 23:03:07 +000079/// EmitGlobalCtors - Generates the array of contsturctor functions to be
80/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +000081void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +000082 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000083
Chris Lattner753d2592008-03-14 17:18:18 +000084 // Get the type of @llvm.global_ctors
85 std::vector<const llvm::Type*> CtorFields;
86 CtorFields.push_back(llvm::IntegerType::get(32));
87 // Constructor function type
88 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +000089 llvm::FunctionType* CtorFuncTy =
90 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
91
Chris Lattner753d2592008-03-14 17:18:18 +000092 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +000093 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
94 llvm::StructType* CtorStructTy =
95 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +000096 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +000097 llvm::ArrayType* GlobalCtorsTy =
98 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +000099
Chris Lattner753d2592008-03-14 17:18:18 +0000100 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000101 llvm::GlobalVariable *GlobalCtorsVal =
102 new llvm::GlobalVariable(GlobalCtorsTy, false,
103 llvm::GlobalValue::AppendingLinkage,
104 (llvm::Constant*)0, "llvm.global_ctors",
105 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000106
107 // Populate the array
108 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000109 llvm::Constant *MagicNumber =
110 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
111 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000112 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000113 E = GlobalCtors.end(); I != E; ++I) {
114 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000115 StructValues.push_back(MagicNumber);
116 StructValues.push_back(*I);
117
Chris Lattnera18c12e2008-03-19 05:24:56 +0000118 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000119 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000120
121 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
122 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000123}
124
Chris Lattnerb326b172008-03-30 23:03:07 +0000125
126
Nate Begeman52da5c72008-04-18 23:43:57 +0000127void CodeGenModule::EmitAnnotations() {
128 if (Annotations.empty())
129 return;
130
131 // Create a new global variable for the ConstantStruct in the Module.
132 llvm::Constant *Array =
133 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
134 Annotations.size()),
135 Annotations);
136 llvm::GlobalValue *gv =
137 new llvm::GlobalVariable(Array->getType(), false,
138 llvm::GlobalValue::AppendingLinkage, Array,
139 "llvm.global.annotations", &TheModule);
140 gv->setSection("llvm.metadata");
141}
142
Chris Lattner0e4755d2007-12-02 06:27:33 +0000143/// ReplaceMapValuesWith - This is a really slow and bad function that
144/// searches for any entries in GlobalDeclMap that point to OldVal, changing
145/// them to point to NewVal. This is badbadbad, FIXME!
146void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
147 llvm::Constant *NewVal) {
148 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
149 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
150 if (I->second == OldVal) I->second = NewVal;
151}
152
153
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000154llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
155 bool isDefinition) {
156 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000157 llvm::Constant *&Entry = GlobalDeclMap[D];
158 if (Entry) return Entry;
159
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000160 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
161
162 // Check to see if the function already exists.
163 llvm::Function *F = getModule().getFunction(D->getName());
164 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
165
166 // If it doesn't already exist, just create and return an entry.
167 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000168 // FIXME: param attributes for sext/zext etc.
Gabor Greif815e2c12008-04-06 20:42:52 +0000169 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, D->getName(),
Nate Begemandc6262e2008-03-09 03:09:36 +0000170 &getModule());
171
172 // Set the appropriate calling convention for the Function.
173 if (D->getAttr<FastCallAttr>())
174 F->setCallingConv(llvm::CallingConv::Fast);
175 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000176 }
177
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000178 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000179 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000180 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000181
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000182 // If this isn't a definition, just return it casted to the right type.
183 if (!isDefinition)
184 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
185
186 // Otherwise, we have a definition after a prototype with the wrong type.
187 // F is the Function* for the one with the wrong type, we must make a new
188 // Function* and update everything that used F (a declaration) with the new
189 // Function* (which will be a definition).
190 //
191 // This happens if there is a prototype for a function (e.g. "int f()") and
192 // then a definition of a different type (e.g. "int f(int x)"). Start by
193 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000194 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000195 llvm::Function::ExternalLinkage,
196 "", &getModule());
197 NewFn->takeName(F);
198
199 // Replace uses of F with the Function we will endow with a body.
200 llvm::Constant *NewPtrForOldDecl =
201 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
202 F->replaceAllUsesWith(NewPtrForOldDecl);
203
204 // FIXME: Update the globaldeclmap for the previous decl of this name. We
205 // really want a way to walk all of these, but we don't have it yet. This
206 // is incredibly slow!
207 ReplaceMapValuesWith(F, NewPtrForOldDecl);
208
209 // Ok, delete the old function now, which is dead.
210 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
211 F->eraseFromParent();
212
213 // Return the new function which has the right type.
214 return Entry = NewFn;
215}
216
Chris Lattner0db06992008-02-05 06:37:34 +0000217static bool IsZeroElementArray(const llvm::Type *Ty) {
218 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
219 return ATy->getNumElements() == 0;
220 return false;
221}
222
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000223llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
224 bool isDefinition) {
225 assert(D->hasGlobalStorage() && "Not a global variable");
226
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000227 // See if it is already in the map.
228 llvm::Constant *&Entry = GlobalDeclMap[D];
229 if (Entry) return Entry;
230
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000231 QualType ASTTy = D->getType();
232 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000233
234 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000235 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000236
237 // If it doesn't already exist, just create and return an entry.
238 if (GV == 0) {
239 return Entry = new llvm::GlobalVariable(Ty, false,
240 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000241 0, D->getName(), &getModule(), 0,
242 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000243 }
244
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000245 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000246 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000247 if (PTy == GV->getType()) return Entry = GV;
248
249 // If this isn't a definition, just return it casted to the right type.
250 if (!isDefinition)
251 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
252
253
254 // Otherwise, we have a definition after a prototype with the wrong type.
255 // GV is the GlobalVariable* for the one with the wrong type, we must make a
256 /// new GlobalVariable* and update everything that used GV (a declaration)
257 // with the new GlobalVariable* (which will be a definition).
258 //
259 // This happens if there is a prototype for a global (e.g. "extern int x[];")
260 // and then a definition of a different type (e.g. "int x[10];"). Start by
261 // making a new global of the correct type, RAUW, then steal the name.
262 llvm::GlobalVariable *NewGV =
263 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000264 0, D->getName(), &getModule(), 0,
265 ASTTy.getAddressSpace());
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000266 NewGV->takeName(GV);
267
268 // Replace uses of GV with the globalvalue we will endow with a body.
269 llvm::Constant *NewPtrForOldDecl =
270 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
271 GV->replaceAllUsesWith(NewPtrForOldDecl);
272
273 // FIXME: Update the globaldeclmap for the previous decl of this name. We
274 // really want a way to walk all of these, but we don't have it yet. This
275 // is incredibly slow!
276 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
277
Chris Lattner0db06992008-02-05 06:37:34 +0000278 // Verify that GV was a declaration or something like x[] which turns into
279 // [0 x type].
280 assert((GV->isDeclaration() ||
281 IsZeroElementArray(GV->getType()->getElementType())) &&
282 "Shouldn't replace non-declaration");
283
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000284 // Ok, delete the old global now, which is dead.
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000285 GV->eraseFromParent();
286
287 // Return the new global which has the right type.
288 return Entry = NewGV;
Chris Lattner4b009652007-07-25 00:24:17 +0000289}
290
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000291
Chris Lattnerb326b172008-03-30 23:03:07 +0000292void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
293 // If this is not a prototype, emit the body.
294 if (OMD->getBody())
295 CodeGenFunction(*this).GenerateObjCMethod(OMD);
296}
297
Chris Lattner4b009652007-07-25 00:24:17 +0000298void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
299 // If this is not a prototype, emit the body.
300 if (FD->getBody())
301 CodeGenFunction(*this).GenerateCode(FD);
302}
303
Anders Carlssond76cead2008-01-26 01:36:00 +0000304llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
305 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000306}
307
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000308void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000309 // If this is just a forward declaration of the variable, don't emit it now,
310 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000311 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
312 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000313
314 // Get the global, forcing it to be a direct reference.
315 llvm::GlobalVariable *GV =
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000316 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000317
318 // Convert the initializer, or use zero if appropriate.
Chris Lattner4b009652007-07-25 00:24:17 +0000319 llvm::Constant *Init = 0;
320 if (D->getInit() == 0) {
321 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
322 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000323 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner8cd0e932008-03-05 18:54:05 +0000324 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner4b009652007-07-25 00:24:17 +0000325 if (D->getInit()->isIntegerConstantExpr(Value, Context))
326 Init = llvm::ConstantInt::get(Value);
327 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000328
Devang Patel08a10cc2007-10-30 21:27:20 +0000329 if (!Init)
Oliver Hunt253e0a72007-12-02 00:11:25 +0000330 Init = EmitGlobalInit(D->getInit());
Devang Patel8b5f5302007-10-26 16:31:40 +0000331
Chris Lattnerc7e4f672007-12-10 00:05:55 +0000332 assert(GV->getType()->getElementType() == Init->getType() &&
333 "Initializer codegen type mismatch!");
Chris Lattner4b009652007-07-25 00:24:17 +0000334 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000335
336 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
337 GV->setVisibility(attr->getVisibility());
338 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000339
340 // Set the llvm linkage type as appropriate.
Chris Lattner402b3372008-03-03 03:28:21 +0000341 if (D->getAttr<DLLImportAttr>())
342 GV->setLinkage(llvm::Function::DLLImportLinkage);
343 else if (D->getAttr<DLLExportAttr>())
344 GV->setLinkage(llvm::Function::DLLExportLinkage);
345 else if (D->getAttr<WeakAttr>()) {
346 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
347
348 } else {
349 // FIXME: This isn't right. This should handle common linkage and other
350 // stuff.
351 switch (D->getStorageClass()) {
352 case VarDecl::Auto:
353 case VarDecl::Register:
354 assert(0 && "Can't have auto or register globals");
355 case VarDecl::None:
356 if (!D->getInit())
357 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
358 break;
359 case VarDecl::Extern:
360 case VarDecl::PrivateExtern:
361 // todo: common
362 break;
363 case VarDecl::Static:
364 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
365 break;
366 }
Chris Lattner4b009652007-07-25 00:24:17 +0000367 }
368}
369
370/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
371/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000372void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
373 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
374 if (D->isFileVarDecl())
375 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000376}
377
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000378void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
379 // Make sure that this type is translated.
380 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000381}
382
383
Chris Lattnerab862cc2007-08-31 04:31:45 +0000384/// getBuiltinLibFunction
385llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000386 if (BuiltinID > BuiltinFunctions.size())
387 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000388
Chris Lattner9f2d6892007-12-13 00:38:03 +0000389 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
390 // a slot for it.
391 assert(BuiltinID && "Invalid Builtin ID");
392 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000393 if (FunctionSlot)
394 return FunctionSlot;
395
396 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
397
398 // Get the name, skip over the __builtin_ prefix.
399 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
400
401 // Get the type for the builtin.
402 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
403 const llvm::FunctionType *Ty =
404 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
405
406 // FIXME: This has a serious problem with code like this:
407 // void abs() {}
408 // ... __builtin_abs(x);
409 // The two versions of abs will collide. The fix is for the builtin to win,
410 // and for the existing one to be turned into a constantexpr cast of the
411 // builtin. In the case where the existing one is a static function, it
412 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000413 if (llvm::Function *Existing = getModule().getFunction(Name)) {
414 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
415 return FunctionSlot = Existing;
416 assert(Existing == 0 && "FIXME: Name collision");
417 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000418
419 // FIXME: param attributes for sext/zext etc.
Gabor Greif815e2c12008-04-06 20:42:52 +0000420 return FunctionSlot = llvm::Function::Create(Ty, llvm::Function::ExternalLinkage,
Chris Lattnerab862cc2007-08-31 04:31:45 +0000421 Name, &getModule());
422}
423
Chris Lattner4b23f942007-12-18 00:25:38 +0000424llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
425 unsigned NumTys) {
426 return llvm::Intrinsic::getDeclaration(&getModule(),
427 (llvm::Intrinsic::ID)IID, Tys, NumTys);
428}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000429
Chris Lattner4b009652007-07-25 00:24:17 +0000430llvm::Function *CodeGenModule::getMemCpyFn() {
431 if (MemCpyFn) return MemCpyFn;
432 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000433 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000434 default: assert(0 && "Unknown ptr width");
435 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
436 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
437 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000438 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000439}
Anders Carlsson36a04872007-08-21 00:21:21 +0000440
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000441llvm::Function *CodeGenModule::getMemSetFn() {
442 if (MemSetFn) return MemSetFn;
443 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000444 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000445 default: assert(0 && "Unknown ptr width");
446 case 32: IID = llvm::Intrinsic::memset_i32; break;
447 case 64: IID = llvm::Intrinsic::memset_i64; break;
448 }
449 return MemSetFn = getIntrinsic(IID);
450}
Chris Lattner4b23f942007-12-18 00:25:38 +0000451
Chris Lattnerab862cc2007-08-31 04:31:45 +0000452llvm::Constant *CodeGenModule::
453GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000454 llvm::StringMapEntry<llvm::Constant *> &Entry =
455 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
456
457 if (Entry.getValue())
458 return Entry.getValue();
459
460 std::vector<llvm::Constant*> Fields;
461
462 if (!CFConstantStringClassRef) {
463 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
464 Ty = llvm::ArrayType::get(Ty, 0);
465
466 CFConstantStringClassRef =
467 new llvm::GlobalVariable(Ty, false,
468 llvm::GlobalVariable::ExternalLinkage, 0,
469 "__CFConstantStringClassReference",
470 &getModule());
471 }
472
473 // Class pointer.
474 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
475 llvm::Constant *Zeros[] = { Zero, Zero };
476 llvm::Constant *C =
477 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
478 Fields.push_back(C);
479
480 // Flags.
481 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
482 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
483
484 // String pointer.
485 C = llvm::ConstantArray::get(str);
486 C = new llvm::GlobalVariable(C->getType(), true,
487 llvm::GlobalValue::InternalLinkage,
488 C, ".str", &getModule());
489
490 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
491 Fields.push_back(C);
492
493 // String length.
494 Ty = getTypes().ConvertType(getContext().LongTy);
495 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
496
497 // The struct.
498 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
499 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000500 llvm::GlobalVariable *GV =
501 new llvm::GlobalVariable(C->getType(), true,
502 llvm::GlobalVariable::InternalLinkage,
503 C, "", &getModule());
504 GV->setSection("__DATA,__cfstring");
505 Entry.setValue(GV);
506 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000507}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000508
Chris Lattnera6dcce32008-02-11 00:02:17 +0000509/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000510static llvm::Constant *GenerateStringLiteral(const std::string &str,
511 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000512 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000513 // Create Constant for this string literal
514 llvm::Constant *C=llvm::ConstantArray::get(str);
515
516 // Create a global variable for this string
517 C = new llvm::GlobalVariable(C->getType(), constant,
518 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000519 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000520 return C;
521}
522
Chris Lattnera6dcce32008-02-11 00:02:17 +0000523/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
524/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000525llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
526 // Don't share any string literals if writable-strings is turned on.
527 if (Features.WritableStrings)
528 return GenerateStringLiteral(str, false, *this);
529
530 llvm::StringMapEntry<llvm::Constant *> &Entry =
531 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
532
533 if (Entry.getValue())
534 return Entry.getValue();
535
536 // Create a global variable for this.
537 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
538 Entry.setValue(C);
539 return C;
540}