blob: 6082226b89d655295bfc243b14f8998999553dda [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"
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerb033c4a2008-04-30 16:05:42 +000029#include "llvm/Analysis/Verifier.h"
Christopher Lamb6db92f32007-12-02 08:49:54 +000030#include <algorithm>
Chris Lattner4b009652007-07-25 00:24:17 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattnerdb6be562007-11-28 05:34:05 +000035CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattner22595b82007-12-02 01:40:18 +000036 llvm::Module &M, const llvm::TargetData &TD,
Sanjiv Gupta40e56a12008-05-08 08:54:20 +000037 Diagnostic &diags, bool GenerateDebugInfo)
Chris Lattner22595b82007-12-02 01:40:18 +000038 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
Eli Friedman8f08a252008-05-26 12:59:39 +000039 Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
40 CFConstantStringClassRef(0) {
Chris Lattnercbfb5512008-03-01 08:45:05 +000041 //TODO: Make this selectable at runtime
Chris Lattner547907c2008-06-26 04:19:03 +000042 Runtime = CreateObjCRuntime(*this);
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() {
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +000052 EmitStatics();
Chris Lattnerb326b172008-03-30 23:03:07 +000053 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
Chris Lattnerc61e9f82008-03-30 23:25:33 +000054 if (ObjCInitFunction)
Chris Lattnerb326b172008-03-30 23:03:07 +000055 AddGlobalCtor(ObjCInitFunction);
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
Dan Gohman4751a3a2008-05-22 00:50:06 +000085/// setVisibility - Set the visibility for the given LLVM GlobalValue
86/// according to the given clang AST visibility value.
87void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
88 VisibilityAttr::VisibilityTypes Vis) {
89 switch (Vis) {
90 default: assert(0 && "Unknown visibility!");
91 case VisibilityAttr::DefaultVisibility:
92 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
93 break;
94 case VisibilityAttr::HiddenVisibility:
95 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
96 break;
97 case VisibilityAttr::ProtectedVisibility:
98 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
99 break;
100 }
101}
102
Chris Lattner753d2592008-03-14 17:18:18 +0000103/// AddGlobalCtor - Add a function to the list that will be called before
104/// main() runs.
105void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
106 // TODO: Type coercion of void()* types.
107 GlobalCtors.push_back(Ctor);
108}
109
Chris Lattnerb326b172008-03-30 23:03:07 +0000110/// EmitGlobalCtors - Generates the array of contsturctor functions to be
111/// called on module load, if any have been registered with AddGlobalCtor.
Chris Lattner753d2592008-03-14 17:18:18 +0000112void CodeGenModule::EmitGlobalCtors() {
Chris Lattnerb326b172008-03-30 23:03:07 +0000113 if (GlobalCtors.empty()) return;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000114
Chris Lattner753d2592008-03-14 17:18:18 +0000115 // Get the type of @llvm.global_ctors
116 std::vector<const llvm::Type*> CtorFields;
117 CtorFields.push_back(llvm::IntegerType::get(32));
118 // Constructor function type
119 std::vector<const llvm::Type*> VoidArgs;
Chris Lattnerc61e9f82008-03-30 23:25:33 +0000120 llvm::FunctionType* CtorFuncTy =
121 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
122
Chris Lattner753d2592008-03-14 17:18:18 +0000123 // i32, function type pair
Chris Lattnera18c12e2008-03-19 05:24:56 +0000124 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
125 llvm::StructType* CtorStructTy =
126 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner753d2592008-03-14 17:18:18 +0000127 // Array of fields
Chris Lattnera18c12e2008-03-19 05:24:56 +0000128 llvm::ArrayType* GlobalCtorsTy =
129 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner753d2592008-03-14 17:18:18 +0000130
Chris Lattner753d2592008-03-14 17:18:18 +0000131 // Define the global variable
Chris Lattnera18c12e2008-03-19 05:24:56 +0000132 llvm::GlobalVariable *GlobalCtorsVal =
133 new llvm::GlobalVariable(GlobalCtorsTy, false,
134 llvm::GlobalValue::AppendingLinkage,
135 (llvm::Constant*)0, "llvm.global_ctors",
136 &TheModule);
Chris Lattner753d2592008-03-14 17:18:18 +0000137
138 // Populate the array
139 std::vector<llvm::Constant*> CtorValues;
Chris Lattnera18c12e2008-03-19 05:24:56 +0000140 llvm::Constant *MagicNumber =
141 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
142 std::vector<llvm::Constant*> StructValues;
Chris Lattner753d2592008-03-14 17:18:18 +0000143 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattnera18c12e2008-03-19 05:24:56 +0000144 E = GlobalCtors.end(); I != E; ++I) {
145 StructValues.clear();
Chris Lattner753d2592008-03-14 17:18:18 +0000146 StructValues.push_back(MagicNumber);
147 StructValues.push_back(*I);
148
Chris Lattnera18c12e2008-03-19 05:24:56 +0000149 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000150 }
Chris Lattnera18c12e2008-03-19 05:24:56 +0000151
152 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
153 CtorValues));
Chris Lattner753d2592008-03-14 17:18:18 +0000154}
155
Chris Lattnerb326b172008-03-30 23:03:07 +0000156
157
Nate Begeman52da5c72008-04-18 23:43:57 +0000158void CodeGenModule::EmitAnnotations() {
159 if (Annotations.empty())
160 return;
161
162 // Create a new global variable for the ConstantStruct in the Module.
163 llvm::Constant *Array =
164 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
165 Annotations.size()),
166 Annotations);
167 llvm::GlobalValue *gv =
168 new llvm::GlobalVariable(Array->getType(), false,
169 llvm::GlobalValue::AppendingLinkage, Array,
170 "llvm.global.annotations", &TheModule);
171 gv->setSection("llvm.metadata");
172}
173
Chris Lattner0e4755d2007-12-02 06:27:33 +0000174/// ReplaceMapValuesWith - This is a really slow and bad function that
175/// searches for any entries in GlobalDeclMap that point to OldVal, changing
176/// them to point to NewVal. This is badbadbad, FIXME!
177void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
178 llvm::Constant *NewVal) {
179 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
180 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
181 if (I->second == OldVal) I->second = NewVal;
182}
183
Eli Friedman9be42212008-06-01 15:54:49 +0000184bool hasAggregateLLVMType(QualType T) {
185 return !T->isRealType() && !T->isPointerLikeType() &&
186 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
187}
188
Nuno Lopes78534382008-06-08 15:45:52 +0000189void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
190 llvm::GlobalValue *GV) {
191 // TODO: Set up linkage and many other things. Note, this is a simple
192 // approximation of what we really want.
193 if (FD->getStorageClass() == FunctionDecl::Static)
194 GV->setLinkage(llvm::Function::InternalLinkage);
195 else if (FD->getAttr<DLLImportAttr>())
196 GV->setLinkage(llvm::Function::DLLImportLinkage);
197 else if (FD->getAttr<DLLExportAttr>())
198 GV->setLinkage(llvm::Function::DLLExportLinkage);
199 else if (FD->getAttr<WeakAttr>() || FD->isInline())
200 GV->setLinkage(llvm::Function::WeakLinkage);
201
202 if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
203 CodeGenModule::setVisibility(GV, attr->getVisibility());
204 // FIXME: else handle -fvisibility
205}
206
Eli Friedman9be42212008-06-01 15:54:49 +0000207void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
208 llvm::Function *F,
209 const llvm::FunctionType *FTy) {
210 unsigned FuncAttrs = 0;
211 if (FD->getAttr<NoThrowAttr>())
212 FuncAttrs |= llvm::ParamAttr::NoUnwind;
213 if (FD->getAttr<NoReturnAttr>())
214 FuncAttrs |= llvm::ParamAttr::NoReturn;
215
216 llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
217 if (FuncAttrs)
218 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
219 // Note that there is parallel code in CodeGenFunction::EmitCallExpr
220 bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
221 if (AggregateReturn)
222 ParamAttrList.push_back(
223 llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
224 unsigned increment = AggregateReturn ? 2 : 1;
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000225 const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
226 if (FTP) {
227 for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
228 QualType ParamType = FTP->getArgType(i);
229 unsigned ParamAttrs = 0;
230 if (ParamType->isRecordType())
231 ParamAttrs |= llvm::ParamAttr::ByVal;
232 if (ParamType->isSignedIntegerType() && ParamType->isPromotableIntegerType())
233 ParamAttrs |= llvm::ParamAttr::SExt;
234 if (ParamType->isUnsignedIntegerType() && ParamType->isPromotableIntegerType())
235 ParamAttrs |= llvm::ParamAttr::ZExt;
236 if (ParamAttrs)
237 ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
238 ParamAttrs));
239 }
Eli Friedman9be42212008-06-01 15:54:49 +0000240 }
Eli Friedmanfa94dff2008-06-04 19:41:28 +0000241
Eli Friedman9be42212008-06-01 15:54:49 +0000242 F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
243 ParamAttrList.size()));
244
245 // Set the appropriate calling convention for the Function.
246 if (FD->getAttr<FastCallAttr>())
247 F->setCallingConv(llvm::CallingConv::Fast);
248
Nuno Lopes78534382008-06-08 15:45:52 +0000249 SetGlobalValueAttributes(FD, F);
Eli Friedman9be42212008-06-01 15:54:49 +0000250}
251
252
Chris Lattner0e4755d2007-12-02 06:27:33 +0000253
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000254llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
255 bool isDefinition) {
256 // See if it is already in the map. If so, just return it.
Chris Lattner4b009652007-07-25 00:24:17 +0000257 llvm::Constant *&Entry = GlobalDeclMap[D];
Eli Friedman5dcae522008-05-30 11:13:18 +0000258 if (!isDefinition && Entry) return Entry;
Eli Friedman725d2be2008-05-20 09:21:07 +0000259
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000260 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
261
262 // Check to see if the function already exists.
263 llvm::Function *F = getModule().getFunction(D->getName());
264 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
265
266 // If it doesn't already exist, just create and return an entry.
267 if (F == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000268 // FIXME: param attributes for sext/zext etc.
Nuno Lopes78534382008-06-08 15:45:52 +0000269 if (D->getBody() || !D->getAttr<AliasAttr>())
270 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
271 D->getName(), &getModule());
272 else {
273 const std::string& aliaseeName = D->getAttr<AliasAttr>()->getAliasee();
274 llvm::Function *aliasee = getModule().getFunction(aliaseeName);
275 llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
276 llvm::Function::ExternalLinkage,
277 D->getName(),
278 aliasee,
279 &getModule());
280 SetGlobalValueAttributes(D, alias);
281 return Entry = alias;
282 }
Nate Begemandc6262e2008-03-09 03:09:36 +0000283
Eli Friedman9be42212008-06-01 15:54:49 +0000284 SetFunctionAttributes(D, F, FTy);
Nate Begemandc6262e2008-03-09 03:09:36 +0000285 return Entry = F;
Chris Lattner4b009652007-07-25 00:24:17 +0000286 }
287
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000288 // If the pointer type matches, just return it.
Christopher Lamb4fe5e702007-12-17 01:11:20 +0000289 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000290 if (PFTy == F->getType()) return Entry = F;
Chris Lattner77ce67c2007-12-02 06:30:46 +0000291
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000292 // If this isn't a definition, just return it casted to the right type.
293 if (!isDefinition)
294 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
295
296 // Otherwise, we have a definition after a prototype with the wrong type.
297 // F is the Function* for the one with the wrong type, we must make a new
298 // Function* and update everything that used F (a declaration) with the new
299 // Function* (which will be a definition).
300 //
301 // This happens if there is a prototype for a function (e.g. "int f()") and
302 // then a definition of a different type (e.g. "int f(int x)"). Start by
303 // making a new function of the correct type, RAUW, then steal the name.
Gabor Greif815e2c12008-04-06 20:42:52 +0000304 llvm::Function *NewFn = llvm::Function::Create(FTy,
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000305 llvm::Function::ExternalLinkage,
306 "", &getModule());
307 NewFn->takeName(F);
308
309 // Replace uses of F with the Function we will endow with a body.
310 llvm::Constant *NewPtrForOldDecl =
311 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
312 F->replaceAllUsesWith(NewPtrForOldDecl);
313
314 // FIXME: Update the globaldeclmap for the previous decl of this name. We
315 // really want a way to walk all of these, but we don't have it yet. This
316 // is incredibly slow!
317 ReplaceMapValuesWith(F, NewPtrForOldDecl);
318
319 // Ok, delete the old function now, which is dead.
320 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
321 F->eraseFromParent();
322
Eli Friedman9be42212008-06-01 15:54:49 +0000323 SetFunctionAttributes(D, NewFn, FTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000324 // Return the new function which has the right type.
325 return Entry = NewFn;
326}
327
Chris Lattnerd2df2b52007-12-18 08:16:44 +0000328llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
329 bool isDefinition) {
330 assert(D->hasGlobalStorage() && "Not a global variable");
Eli Friedman43a0ce82008-05-30 19:50:47 +0000331 assert(!isDefinition && "This shouldn't be called for definitions!");
332
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000333 // See if it is already in the map.
334 llvm::Constant *&Entry = GlobalDeclMap[D];
335 if (Entry) return Entry;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000336
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000337 QualType ASTTy = D->getType();
338 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000339
340 // Check to see if the global already exists.
Chris Lattnered430e92008-02-02 04:43:11 +0000341 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000342
343 // If it doesn't already exist, just create and return an entry.
344 if (GV == 0) {
345 return Entry = new llvm::GlobalVariable(Ty, false,
346 llvm::GlobalValue::ExternalLinkage,
Christopher Lamb2a72bb32008-02-04 02:31:56 +0000347 0, D->getName(), &getModule(), 0,
348 ASTTy.getAddressSpace());
Chris Lattner77ce67c2007-12-02 06:30:46 +0000349 }
Chris Lattner4b009652007-07-25 00:24:17 +0000350
Eli Friedman43a0ce82008-05-30 19:50:47 +0000351 // Otherwise, it already exists; return the existing version
352 llvm::PointerType *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
353 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
354}
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000355
Chris Lattnerb326b172008-03-30 23:03:07 +0000356void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
357 // If this is not a prototype, emit the body.
358 if (OMD->getBody())
359 CodeGenFunction(*this).GenerateObjCMethod(OMD);
360}
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000361void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
362 llvm::SmallVector<std::string, 16> Protocols;
363 for (unsigned i = 0, e = PD->getNumReferencedProtocols() ; i < e ; i++)
364 Protocols.push_back(PD->getReferencedProtocols()[i]->getName());
365 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
366 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
367 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
368 endIter = PD->instmeth_end() ; iter != endIter ; iter++) {
369 std::string TypeStr;
370 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
371 InstanceMethodNames.push_back(
372 GetAddrOfConstantString((*iter)->getSelector().getName()));
373 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
374 }
375 // Collect information about class methods:
376 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
377 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
378 for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
379 endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
380 std::string TypeStr;
381 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
382 ClassMethodNames.push_back(
383 GetAddrOfConstantString((*iter)->getSelector().getName()));
384 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
385 }
386 Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
387 InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
388}
389
390void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
391
392 // Collect information about instance methods
393 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
394 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
395 for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
396 endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
397 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000398 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000399 InstanceMethodNames.push_back(
400 GetAddrOfConstantString((*iter)->getSelector().getName()));
401 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
402 }
403
404 // Collect information about class methods
405 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
406 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
407 for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
408 endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
409 std::string TypeStr;
Chris Lattnerbcb3e862008-06-26 04:52:29 +0000410 Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000411 ClassMethodNames.push_back(
412 GetAddrOfConstantString((*iter)->getSelector().getName()));
413 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
414 }
415
416 // Collect the names of referenced protocols
417 llvm::SmallVector<std::string, 16> Protocols;
418 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OCD->getClassInterface();
419 for (unsigned i=0 ; i<ClassDecl->getNumIntfRefProtocols() ; i++)
420 Protocols.push_back(ClassDecl->getReferencedProtocols()[i]->getName());
421
422 // Generate the category
423 Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
424 OCD->getName(), InstanceMethodNames, InstanceMethodTypes,
425 ClassMethodNames, ClassMethodTypes, Protocols);
426}
427
428void CodeGenModule::EmitObjCClassImplementation(
429 const ObjCImplementationDecl *OID) {
430 // Get the superclass name.
431 const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
432 const char * SCName = NULL;
433 if (SCDecl) {
434 SCName = SCDecl->getName();
435 }
436
437 // Get the class name
438 ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
439 const char * ClassName = ClassDecl->getName();
440
441 // Get the size of instances. For runtimes that support late-bound instances
442 // this should probably be something different (size just of instance
443 // varaibles in this class, not superclasses?).
444 int instanceSize = 0;
445 const llvm::Type *ObjTy;
446 if (!Runtime->LateBoundIVars()) {
447 ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
448 instanceSize = TheTargetData.getABITypeSize(ObjTy);
449 }
450
451 // Collect information about instance variables.
452 llvm::SmallVector<llvm::Constant*, 16> IvarNames;
453 llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
454 llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
455 const llvm::StructLayout *Layout =
456 TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
457 ObjTy = llvm::PointerType::getUnqual(ObjTy);
458 for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
459 endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
460 // Store the name
461 IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
462 // Get the type encoding for this ivar
463 std::string TypeStr;
464 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
465 Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
466 EncodingRecordTypes);
467 IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
468 // Get the offset
469 int offset =
470 (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
471 IvarOffsets.push_back(
472 llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
473 }
474
475 // Collect information about instance methods
476 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
477 llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
478 for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
479 endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
480 std::string TypeStr;
481 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
482 InstanceMethodNames.push_back(
483 GetAddrOfConstantString((*iter)->getSelector().getName()));
484 InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
485 }
486
487 // Collect information about class methods
488 llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
489 llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
490 for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
491 endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
492 std::string TypeStr;
493 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
494 ClassMethodNames.push_back(
495 GetAddrOfConstantString((*iter)->getSelector().getName()));
496 ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
497 }
498 // Collect the names of referenced protocols
499 llvm::SmallVector<std::string, 16> Protocols;
500 for (unsigned i = 0, e = ClassDecl->getNumIntfRefProtocols() ; i < e ; i++)
501 Protocols.push_back(ClassDecl->getReferencedProtocols()[i]->getName());
502
503 // Generate the category
504 Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
505 IvarOffsets, InstanceMethodNames, InstanceMethodTypes, ClassMethodNames,
506 ClassMethodTypes, Protocols);
507}
508
Chris Lattnerb326b172008-03-30 23:03:07 +0000509
Chris Lattner4b009652007-07-25 00:24:17 +0000510void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
511 // If this is not a prototype, emit the body.
Nuno Lopes78534382008-06-08 15:45:52 +0000512 if (!FD->isThisDeclarationADefinition()) {
513 if (FD->getAttr<AliasAttr>())
514 GetAddrOfFunctionDecl(FD, true);
Chris Lattner74bf5552008-05-04 02:29:49 +0000515 return;
Nuno Lopes78534382008-06-08 15:45:52 +0000516 }
Chris Lattner74bf5552008-05-04 02:29:49 +0000517
518 // If the function is a static, defer code generation until later so we can
519 // easily omit unused statics.
520 if (FD->getStorageClass() != FunctionDecl::Static) {
Chris Lattner4b009652007-07-25 00:24:17 +0000521 CodeGenFunction(*this).GenerateCode(FD);
Chris Lattner74bf5552008-05-04 02:29:49 +0000522 return;
Nate Begemanad320b62008-04-20 06:29:50 +0000523 }
Chris Lattner74bf5552008-05-04 02:29:49 +0000524
525 StaticDecls.push_back(FD);
Nate Begemanad320b62008-04-20 06:29:50 +0000526}
527
528void CodeGenModule::EmitStatics() {
529 // Emit code for each used static decl encountered. Since a previously unused
530 // static decl may become used during the generation of code for a static
531 // function, iterate until no changes are made.
532 bool Changed;
533 do {
534 Changed = false;
535 for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
Nate Begemanad320b62008-04-20 06:29:50 +0000536 const Decl *D = StaticDecls[i];
Eli Friedmana4d4e2f2008-05-27 04:58:01 +0000537
538 // Check if we have used a decl with the same name
539 // FIXME: The AST should have some sort of aggregate decls or
540 // global symbol map.
541 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
542 if (!getModule().getFunction(FD->getName()))
543 continue;
544 } else {
545 if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
546 continue;
547 }
548
Nate Begemanad320b62008-04-20 06:29:50 +0000549 // If this is a function decl, generate code for the static function if it
550 // has a body. Otherwise, we must have a var decl for a static global
551 // variable.
552 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
553 if (FD->getBody())
554 CodeGenFunction(*this).GenerateCode(FD);
Nuno Lopes78534382008-06-08 15:45:52 +0000555 else if (FD->getAttr<AliasAttr>())
556 GetAddrOfFunctionDecl(FD, true);
Nate Begemanad320b62008-04-20 06:29:50 +0000557 } else {
Nate Begeman91f52012008-04-20 20:38:08 +0000558 EmitGlobalVarInit(cast<VarDecl>(D));
Nate Begemanad320b62008-04-20 06:29:50 +0000559 }
560 // Erase the used decl from the list.
561 StaticDecls[i] = StaticDecls.back();
562 StaticDecls.pop_back();
563 --i;
564 --e;
565
566 // Remember that we made a change.
567 Changed = true;
568 }
569 } while (Changed);
Chris Lattner4b009652007-07-25 00:24:17 +0000570}
571
Anders Carlssond76cead2008-01-26 01:36:00 +0000572llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
573 return EmitConstantExpr(Expr);
Devang Patel08a10cc2007-10-30 21:27:20 +0000574}
575
Nate Begeman8a704172008-04-19 04:17:09 +0000576/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
577/// annotation information for a given GlobalValue. The annotation struct is
578/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
579/// GlobalValue being annotated. The second filed is thee constant string
580/// created from the AnnotateAttr's annotation. The third field is a constant
581/// string containing the name of the translation unit. The fourth field is
582/// the line number in the file of the annotated value declaration.
583///
584/// FIXME: this does not unique the annotation string constants, as llvm-gcc
585/// appears to.
586///
587llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
588 const AnnotateAttr *AA,
589 unsigned LineNo) {
590 llvm::Module *M = &getModule();
591
592 // get [N x i8] constants for the annotation string, and the filename string
593 // which are the 2nd and 3rd elements of the global annotation structure.
594 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
595 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
596 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
597 true);
598
599 // Get the two global values corresponding to the ConstantArrays we just
600 // created to hold the bytes of the strings.
601 llvm::GlobalValue *annoGV =
602 new llvm::GlobalVariable(anno->getType(), false,
603 llvm::GlobalValue::InternalLinkage, anno,
604 GV->getName() + ".str", M);
605 // translation unit name string, emitted into the llvm.metadata section.
606 llvm::GlobalValue *unitGV =
607 new llvm::GlobalVariable(unit->getType(), false,
608 llvm::GlobalValue::InternalLinkage, unit, ".str", M);
609
610 // Create the ConstantStruct that is the global annotion.
611 llvm::Constant *Fields[4] = {
612 llvm::ConstantExpr::getBitCast(GV, SBP),
613 llvm::ConstantExpr::getBitCast(annoGV, SBP),
614 llvm::ConstantExpr::getBitCast(unitGV, SBP),
615 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
616 };
617 return llvm::ConstantStruct::get(Fields, 4, false);
618}
619
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000620void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
Nate Begemanad320b62008-04-20 06:29:50 +0000621 // If the VarDecl is a static, defer code generation until later so we can
622 // easily omit unused statics.
623 if (D->getStorageClass() == VarDecl::Static) {
624 StaticDecls.push_back(D);
625 return;
626 }
627
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000628 // If this is just a forward declaration of the variable, don't emit it now,
629 // allow it to be emitted lazily on its first use.
Chris Lattner4b009652007-07-25 00:24:17 +0000630 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
631 return;
Chris Lattner1a3c1e22007-12-02 07:09:19 +0000632
Nate Begemanad320b62008-04-20 06:29:50 +0000633 EmitGlobalVarInit(D);
634}
635
636void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
Eli Friedman43a0ce82008-05-30 19:50:47 +0000637 assert(D->hasGlobalStorage() && "Not a global variable");
638
Chris Lattner4b009652007-07-25 00:24:17 +0000639 llvm::Constant *Init = 0;
Eli Friedman43a0ce82008-05-30 19:50:47 +0000640 QualType ASTTy = D->getType();
641 const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
642 const llvm::Type *VarPtrTy =
643 llvm::PointerType::get(VarTy, ASTTy.getAddressSpace());
644
Chris Lattner4b009652007-07-25 00:24:17 +0000645 if (D->getInit() == 0) {
Eli Friedman7008e9a2008-05-30 20:39:54 +0000646 // This is a tentative definition; tentative definitions are
647 // implicitly initialized with { 0 }
648 const llvm::Type* InitTy;
649 if (ASTTy->isIncompleteArrayType()) {
650 // An incomplete array is normally [ TYPE x 0 ], but we need
651 // to fix it to [ TYPE x 1 ].
652 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
653 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
654 } else {
655 InitTy = VarTy;
656 }
657 Init = llvm::Constant::getNullValue(InitTy);
Eli Friedman43a0ce82008-05-30 19:50:47 +0000658 } else {
659 Init = EmitGlobalInit(D->getInit());
660 }
661 const llvm::Type* InitType = Init->getType();
662
663 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
664
665 if (!GV) {
666 GV = new llvm::GlobalVariable(InitType, false,
667 llvm::GlobalValue::ExternalLinkage,
668 0, D->getName(), &getModule(), 0,
669 ASTTy.getAddressSpace());
670 } else if (GV->getType()->getElementType() != InitType ||
671 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
672 // We have a definition after a prototype with the wrong type.
673 // We must make a new GlobalVariable* and update everything that used OldGV
674 // (a declaration or tentative definition) with the new GlobalVariable*
675 // (which will be a definition).
676 //
677 // This happens if there is a prototype for a global (e.g. "extern int x[];")
678 // and then a definition of a different type (e.g. "int x[10];"). This also
679 // happens when an initializer has a different type from the type of the
680 // global (this happens with unions).
Eli Friedman7008e9a2008-05-30 20:39:54 +0000681 //
682 // FIXME: This also ends up happening if there's a definition followed by
683 // a tentative definition! (Although Sema rejects that construct
684 // at the moment.)
Eli Friedman43a0ce82008-05-30 19:50:47 +0000685
686 // Save the old global
687 llvm::GlobalVariable *OldGV = GV;
688
689 // Make a new global with the correct type
690 GV = new llvm::GlobalVariable(InitType, false,
691 llvm::GlobalValue::ExternalLinkage,
692 0, D->getName(), &getModule(), 0,
693 ASTTy.getAddressSpace());
694 // Steal the name of the old global
695 GV->takeName(OldGV);
696
697 // Replace all uses of the old global with the new global
698 llvm::Constant *NewPtrForOldDecl =
699 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
700 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
701 // Make sure we don't keep around any stale references to globals
702 // FIXME: This is really slow; we need a better way to walk all
703 // the decls with the same name
704 ReplaceMapValuesWith(OldGV, NewPtrForOldDecl);
705
706 // Erase the old global, since it is no longer used.
707 OldGV->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000708 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000709
Eli Friedman43a0ce82008-05-30 19:50:47 +0000710 GlobalDeclMap[D] = llvm::ConstantExpr::getBitCast(GV, VarPtrTy);
Devang Patel8b5f5302007-10-26 16:31:40 +0000711
Nate Begeman8a704172008-04-19 04:17:09 +0000712 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
713 SourceManager &SM = Context.getSourceManager();
714 AddAnnotation(EmitAnnotateAttr(GV, AA,
715 SM.getLogicalLineNumber(D->getLocation())));
716 }
717
Chris Lattner4b009652007-07-25 00:24:17 +0000718 GV->setInitializer(Init);
Chris Lattner402b3372008-03-03 03:28:21 +0000719
Eli Friedman7008e9a2008-05-30 20:39:54 +0000720 // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
721 unsigned Align;
722 if (const IncompleteArrayType* IAT = D->getType()->getAsIncompleteArrayType())
723 Align = Context.getTypeAlign(IAT->getElementType());
724 else
725 Align = Context.getTypeAlign(D->getType());
Eli Friedmanb232e992008-05-29 11:10:27 +0000726 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
727 Align = std::max(Align, AA->getAlignment());
728 }
729 GV->setAlignment(Align / 8);
730
Chris Lattner402b3372008-03-03 03:28:21 +0000731 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
Dan Gohman4751a3a2008-05-22 00:50:06 +0000732 setVisibility(GV, attr->getVisibility());
Chris Lattner402b3372008-03-03 03:28:21 +0000733 // FIXME: else handle -fvisibility
Chris Lattner4b009652007-07-25 00:24:17 +0000734
735 // Set the llvm linkage type as appropriate.
Chris Lattner25094a42008-05-04 01:44:26 +0000736 if (D->getStorageClass() == VarDecl::Static)
737 GV->setLinkage(llvm::Function::InternalLinkage);
738 else if (D->getAttr<DLLImportAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000739 GV->setLinkage(llvm::Function::DLLImportLinkage);
740 else if (D->getAttr<DLLExportAttr>())
741 GV->setLinkage(llvm::Function::DLLExportLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000742 else if (D->getAttr<WeakAttr>())
Chris Lattner402b3372008-03-03 03:28:21 +0000743 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
Chris Lattner25094a42008-05-04 01:44:26 +0000744 else {
Chris Lattner402b3372008-03-03 03:28:21 +0000745 // FIXME: This isn't right. This should handle common linkage and other
746 // stuff.
747 switch (D->getStorageClass()) {
Chris Lattner25094a42008-05-04 01:44:26 +0000748 case VarDecl::Static: assert(0 && "This case handled above");
Chris Lattner402b3372008-03-03 03:28:21 +0000749 case VarDecl::Auto:
750 case VarDecl::Register:
751 assert(0 && "Can't have auto or register globals");
752 case VarDecl::None:
753 if (!D->getInit())
Eli Friedmana7f46332008-05-29 11:03:17 +0000754 GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
Chris Lattner402b3372008-03-03 03:28:21 +0000755 break;
756 case VarDecl::Extern:
757 case VarDecl::PrivateExtern:
758 // todo: common
759 break;
Chris Lattner402b3372008-03-03 03:28:21 +0000760 }
Chris Lattner4b009652007-07-25 00:24:17 +0000761 }
Sanjiv Gupta54d97542008-06-05 08:59:10 +0000762
763 // Emit global variable debug information.
764 CGDebugInfo *DI = getDebugInfo();
765 if(DI) {
766 if(D->getLocation().isValid())
767 DI->setLocation(D->getLocation());
768 DI->EmitGlobalVariable(GV, D);
769 }
Chris Lattner4b009652007-07-25 00:24:17 +0000770}
771
772/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
773/// declarator chain.
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000774void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
775 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
776 if (D->isFileVarDecl())
777 EmitGlobalVar(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000778}
779
Chris Lattner9ec3ca22008-02-06 05:08:19 +0000780void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
781 // Make sure that this type is translated.
782 Types.UpdateCompletedType(TD);
Chris Lattner1b22f8b2008-02-05 08:06:13 +0000783}
784
785
Chris Lattnerab862cc2007-08-31 04:31:45 +0000786/// getBuiltinLibFunction
787llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner9f2d6892007-12-13 00:38:03 +0000788 if (BuiltinID > BuiltinFunctions.size())
789 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerab862cc2007-08-31 04:31:45 +0000790
Chris Lattner9f2d6892007-12-13 00:38:03 +0000791 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
792 // a slot for it.
793 assert(BuiltinID && "Invalid Builtin ID");
794 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerab862cc2007-08-31 04:31:45 +0000795 if (FunctionSlot)
796 return FunctionSlot;
797
798 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
799
800 // Get the name, skip over the __builtin_ prefix.
801 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
802
803 // Get the type for the builtin.
804 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
805 const llvm::FunctionType *Ty =
806 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
807
808 // FIXME: This has a serious problem with code like this:
809 // void abs() {}
810 // ... __builtin_abs(x);
811 // The two versions of abs will collide. The fix is for the builtin to win,
812 // and for the existing one to be turned into a constantexpr cast of the
813 // builtin. In the case where the existing one is a static function, it
814 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000815 if (llvm::Function *Existing = getModule().getFunction(Name)) {
816 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
817 return FunctionSlot = Existing;
818 assert(Existing == 0 && "FIXME: Name collision");
819 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000820
821 // FIXME: param attributes for sext/zext etc.
Nate Begemanad320b62008-04-20 06:29:50 +0000822 return FunctionSlot =
823 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
824 &getModule());
Chris Lattnerab862cc2007-08-31 04:31:45 +0000825}
826
Chris Lattner4b23f942007-12-18 00:25:38 +0000827llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
828 unsigned NumTys) {
829 return llvm::Intrinsic::getDeclaration(&getModule(),
830 (llvm::Intrinsic::ID)IID, Tys, NumTys);
831}
Chris Lattnerab862cc2007-08-31 04:31:45 +0000832
Chris Lattner4b009652007-07-25 00:24:17 +0000833llvm::Function *CodeGenModule::getMemCpyFn() {
834 if (MemCpyFn) return MemCpyFn;
835 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000836 switch (Context.Target.getPointerWidth(0)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000837 default: assert(0 && "Unknown ptr width");
838 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
839 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
840 }
Chris Lattner4b23f942007-12-18 00:25:38 +0000841 return MemCpyFn = getIntrinsic(IID);
Chris Lattner4b009652007-07-25 00:24:17 +0000842}
Anders Carlsson36a04872007-08-21 00:21:21 +0000843
Eli Friedman8f08a252008-05-26 12:59:39 +0000844llvm::Function *CodeGenModule::getMemMoveFn() {
845 if (MemMoveFn) return MemMoveFn;
846 llvm::Intrinsic::ID IID;
847 switch (Context.Target.getPointerWidth(0)) {
848 default: assert(0 && "Unknown ptr width");
849 case 32: IID = llvm::Intrinsic::memmove_i32; break;
850 case 64: IID = llvm::Intrinsic::memmove_i64; break;
851 }
852 return MemMoveFn = getIntrinsic(IID);
853}
854
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000855llvm::Function *CodeGenModule::getMemSetFn() {
856 if (MemSetFn) return MemSetFn;
857 llvm::Intrinsic::ID IID;
Chris Lattner461a6c52008-03-08 08:34:58 +0000858 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancioe5bef732008-02-19 22:01:01 +0000859 default: assert(0 && "Unknown ptr width");
860 case 32: IID = llvm::Intrinsic::memset_i32; break;
861 case 64: IID = llvm::Intrinsic::memset_i64; break;
862 }
863 return MemSetFn = getIntrinsic(IID);
864}
Chris Lattner4b23f942007-12-18 00:25:38 +0000865
Anton Korobeynikovcd5d08d2008-06-01 14:13:53 +0000866// FIXME: This needs moving into an Apple Objective-C runtime class
Chris Lattnerab862cc2007-08-31 04:31:45 +0000867llvm::Constant *CodeGenModule::
868GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000869 llvm::StringMapEntry<llvm::Constant *> &Entry =
870 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
871
872 if (Entry.getValue())
873 return Entry.getValue();
874
875 std::vector<llvm::Constant*> Fields;
876
877 if (!CFConstantStringClassRef) {
878 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
879 Ty = llvm::ArrayType::get(Ty, 0);
880
881 CFConstantStringClassRef =
882 new llvm::GlobalVariable(Ty, false,
883 llvm::GlobalVariable::ExternalLinkage, 0,
884 "__CFConstantStringClassReference",
885 &getModule());
886 }
887
888 // Class pointer.
889 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
890 llvm::Constant *Zeros[] = { Zero, Zero };
891 llvm::Constant *C =
892 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
893 Fields.push_back(C);
894
895 // Flags.
896 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
897 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
898
899 // String pointer.
900 C = llvm::ConstantArray::get(str);
901 C = new llvm::GlobalVariable(C->getType(), true,
902 llvm::GlobalValue::InternalLinkage,
903 C, ".str", &getModule());
904
905 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
906 Fields.push_back(C);
907
908 // String length.
909 Ty = getTypes().ConvertType(getContext().LongTy);
910 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
911
912 // The struct.
913 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
914 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson9be009e2007-11-01 00:41:52 +0000915 llvm::GlobalVariable *GV =
916 new llvm::GlobalVariable(C->getType(), true,
917 llvm::GlobalVariable::InternalLinkage,
918 C, "", &getModule());
919 GV->setSection("__DATA,__cfstring");
920 Entry.setValue(GV);
921 return GV;
Anders Carlsson36a04872007-08-21 00:21:21 +0000922}
Chris Lattnerdb6be562007-11-28 05:34:05 +0000923
Chris Lattnera6dcce32008-02-11 00:02:17 +0000924/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000925static llvm::Constant *GenerateStringLiteral(const std::string &str,
926 bool constant,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000927 CodeGenModule &CGM) {
Chris Lattnerdb6be562007-11-28 05:34:05 +0000928 // Create Constant for this string literal
929 llvm::Constant *C=llvm::ConstantArray::get(str);
930
931 // Create a global variable for this string
932 C = new llvm::GlobalVariable(C->getType(), constant,
933 llvm::GlobalValue::InternalLinkage,
Chris Lattnercf9c9d02007-12-02 07:19:18 +0000934 C, ".str", &CGM.getModule());
Chris Lattnerdb6be562007-11-28 05:34:05 +0000935 return C;
936}
937
Chris Lattnera6dcce32008-02-11 00:02:17 +0000938/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
939/// array containing the literal. The result is pointer to array type.
Chris Lattnerdb6be562007-11-28 05:34:05 +0000940llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
941 // Don't share any string literals if writable-strings is turned on.
942 if (Features.WritableStrings)
943 return GenerateStringLiteral(str, false, *this);
944
945 llvm::StringMapEntry<llvm::Constant *> &Entry =
946 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
947
948 if (Entry.getValue())
949 return Entry.getValue();
950
951 // Create a global variable for this.
952 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
953 Entry.setValue(C);
954 return C;
955}