blob: b5d9db98ef9e02eaa211aef3f4d97f7e39bfe2d8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000018#include "clang/Basic/Diagnostic.h"
Chris Lattner45e8cbd2007-11-28 05:34:05 +000019#include "clang/Basic/LangOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Basic/TargetInfo.h"
Nate Begemanec9426c2008-03-09 03:09:36 +000021#include "llvm/CallingConv.h"
Chris Lattner8f32f712007-07-14 00:23:28 +000022#include "llvm/Constants.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "llvm/DerivedTypes.h"
Chris Lattnerbef20ac2007-08-31 04:31:45 +000024#include "llvm/Module.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "llvm/Intrinsics.h"
Christopher Lambce39faa2007-12-02 08:49:54 +000026#include <algorithm>
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28using namespace CodeGen;
29
30
Chris Lattner45e8cbd2007-11-28 05:34:05 +000031CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
Chris Lattnerfb97b032007-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 Lattner2b94fe32008-03-01 08:45:05 +000035 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
36 //TODO: Make this selectable at runtime
37 Runtime = CreateObjCRuntime(M);
38}
39
40CodeGenModule::~CodeGenModule() {
Chris Lattner6d397602008-03-14 17:18:18 +000041 EmitGlobalCtors();
Chris Lattner2b94fe32008-03-01 08:45:05 +000042 delete Runtime;
43}
Reid Spencer5f016e22007-07-11 17:01:13 +000044
Chris Lattner2c8569d2007-12-02 07:19:18 +000045/// WarnUnsupported - Print out a warning that codegen doesn't support the
46/// specified stmt yet.
47void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
48 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
49 "cannot codegen this %0 yet");
50 SourceRange Range = S->getSourceRange();
51 std::string Msg = Type;
Ted Kremenek9c728dc2007-12-12 22:39:36 +000052 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000053 &Msg, 1, &Range, 1);
Chris Lattner2c8569d2007-12-02 07:19:18 +000054}
Chris Lattner58c3f9e2007-12-02 06:27:33 +000055
Chris Lattnerc6fdc342008-01-12 07:05:38 +000056/// WarnUnsupported - Print out a warning that codegen doesn't support the
57/// specified decl yet.
58void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
59 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
60 "cannot codegen this %0 yet");
61 std::string Msg = Type;
62 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
63 &Msg, 1);
64}
65
Chris Lattner6d397602008-03-14 17:18:18 +000066/// AddGlobalCtor - Add a function to the list that will be called before
67/// main() runs.
68void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
69 // TODO: Type coercion of void()* types.
70 GlobalCtors.push_back(Ctor);
71}
72
73void CodeGenModule::EmitGlobalCtors() {
74 // Get the type of @llvm.global_ctors
75 std::vector<const llvm::Type*> CtorFields;
76 CtorFields.push_back(llvm::IntegerType::get(32));
77 // Constructor function type
78 std::vector<const llvm::Type*> VoidArgs;
79 llvm::FunctionType* CtorFuncTy = llvm::FunctionType::get(
80 llvm::Type::VoidTy,
81 VoidArgs,
82 false);
83 // i32, function type pair
Chris Lattner572cf092008-03-19 05:24:56 +000084 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
85 llvm::StructType* CtorStructTy =
86 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
Chris Lattner6d397602008-03-14 17:18:18 +000087 // Array of fields
Chris Lattner572cf092008-03-19 05:24:56 +000088 llvm::ArrayType* GlobalCtorsTy =
89 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
Chris Lattner6d397602008-03-14 17:18:18 +000090
Chris Lattner6d397602008-03-14 17:18:18 +000091 // Define the global variable
Chris Lattner572cf092008-03-19 05:24:56 +000092 llvm::GlobalVariable *GlobalCtorsVal =
93 new llvm::GlobalVariable(GlobalCtorsTy, false,
94 llvm::GlobalValue::AppendingLinkage,
95 (llvm::Constant*)0, "llvm.global_ctors",
96 &TheModule);
Chris Lattner6d397602008-03-14 17:18:18 +000097
98 // Populate the array
99 std::vector<llvm::Constant*> CtorValues;
Chris Lattner572cf092008-03-19 05:24:56 +0000100 llvm::Constant *MagicNumber =
101 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
102 std::vector<llvm::Constant*> StructValues;
Chris Lattner6d397602008-03-14 17:18:18 +0000103 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
Chris Lattner572cf092008-03-19 05:24:56 +0000104 E = GlobalCtors.end(); I != E; ++I) {
105 StructValues.clear();
Chris Lattner6d397602008-03-14 17:18:18 +0000106 StructValues.push_back(MagicNumber);
107 StructValues.push_back(*I);
108
Chris Lattner572cf092008-03-19 05:24:56 +0000109 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
Chris Lattner6d397602008-03-14 17:18:18 +0000110 }
Chris Lattner572cf092008-03-19 05:24:56 +0000111
112 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
113 CtorValues));
Chris Lattner6d397602008-03-14 17:18:18 +0000114
115}
116
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000117/// ReplaceMapValuesWith - This is a really slow and bad function that
118/// searches for any entries in GlobalDeclMap that point to OldVal, changing
119/// them to point to NewVal. This is badbadbad, FIXME!
120void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
121 llvm::Constant *NewVal) {
122 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
123 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
124 if (I->second == OldVal) I->second = NewVal;
125}
126
127
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000128llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
129 bool isDefinition) {
130 // See if it is already in the map. If so, just return it.
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 llvm::Constant *&Entry = GlobalDeclMap[D];
132 if (Entry) return Entry;
133
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000134 const llvm::Type *Ty = getTypes().ConvertType(D->getType());
135
136 // Check to see if the function already exists.
137 llvm::Function *F = getModule().getFunction(D->getName());
138 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
139
140 // If it doesn't already exist, just create and return an entry.
141 if (F == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 // FIXME: param attributes for sext/zext etc.
Nate Begemanec9426c2008-03-09 03:09:36 +0000143 F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(),
144 &getModule());
145
146 // Set the appropriate calling convention for the Function.
147 if (D->getAttr<FastCallAttr>())
148 F->setCallingConv(llvm::CallingConv::Fast);
149 return Entry = F;
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 }
151
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000152 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000153 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000154 if (PFTy == F->getType()) return Entry = F;
Chris Lattnerfafad832007-12-02 06:30:46 +0000155
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000156 // If this isn't a definition, just return it casted to the right type.
157 if (!isDefinition)
158 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
159
160 // Otherwise, we have a definition after a prototype with the wrong type.
161 // F is the Function* for the one with the wrong type, we must make a new
162 // Function* and update everything that used F (a declaration) with the new
163 // Function* (which will be a definition).
164 //
165 // This happens if there is a prototype for a function (e.g. "int f()") and
166 // then a definition of a different type (e.g. "int f(int x)"). Start by
167 // making a new function of the correct type, RAUW, then steal the name.
168 llvm::Function *NewFn = new llvm::Function(FTy,
169 llvm::Function::ExternalLinkage,
170 "", &getModule());
171 NewFn->takeName(F);
172
173 // Replace uses of F with the Function we will endow with a body.
174 llvm::Constant *NewPtrForOldDecl =
175 llvm::ConstantExpr::getBitCast(NewFn, F->getType());
176 F->replaceAllUsesWith(NewPtrForOldDecl);
177
178 // FIXME: Update the globaldeclmap for the previous decl of this name. We
179 // really want a way to walk all of these, but we don't have it yet. This
180 // is incredibly slow!
181 ReplaceMapValuesWith(F, NewPtrForOldDecl);
182
183 // Ok, delete the old function now, which is dead.
184 assert(F->isDeclaration() && "Shouldn't replace non-declaration");
185 F->eraseFromParent();
186
187 // Return the new function which has the right type.
188 return Entry = NewFn;
189}
190
Chris Lattnerc4b23a52008-02-05 06:37:34 +0000191static bool IsZeroElementArray(const llvm::Type *Ty) {
192 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
193 return ATy->getNumElements() == 0;
194 return false;
195}
196
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000197llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
198 bool isDefinition) {
199 assert(D->hasGlobalStorage() && "Not a global variable");
200
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000201 // See if it is already in the map.
202 llvm::Constant *&Entry = GlobalDeclMap[D];
203 if (Entry) return Entry;
204
Christopher Lambebb97e92008-02-04 02:31:56 +0000205 QualType ASTTy = D->getType();
206 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000207
208 // Check to see if the global already exists.
Chris Lattner49573782008-02-02 04:43:11 +0000209 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000210
211 // If it doesn't already exist, just create and return an entry.
212 if (GV == 0) {
213 return Entry = new llvm::GlobalVariable(Ty, false,
214 llvm::GlobalValue::ExternalLinkage,
Christopher Lambebb97e92008-02-04 02:31:56 +0000215 0, D->getName(), &getModule(), 0,
216 ASTTy.getAddressSpace());
Chris Lattnerfafad832007-12-02 06:30:46 +0000217 }
218
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000219 // If the pointer type matches, just return it.
Christopher Lambddc23f32007-12-17 01:11:20 +0000220 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000221 if (PTy == GV->getType()) return Entry = GV;
222
223 // If this isn't a definition, just return it casted to the right type.
224 if (!isDefinition)
225 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
226
227
228 // Otherwise, we have a definition after a prototype with the wrong type.
229 // GV is the GlobalVariable* for the one with the wrong type, we must make a
230 /// new GlobalVariable* and update everything that used GV (a declaration)
231 // with the new GlobalVariable* (which will be a definition).
232 //
233 // This happens if there is a prototype for a global (e.g. "extern int x[];")
234 // and then a definition of a different type (e.g. "int x[10];"). Start by
235 // making a new global of the correct type, RAUW, then steal the name.
236 llvm::GlobalVariable *NewGV =
237 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
Christopher Lambebb97e92008-02-04 02:31:56 +0000238 0, D->getName(), &getModule(), 0,
239 ASTTy.getAddressSpace());
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000240 NewGV->takeName(GV);
241
242 // Replace uses of GV with the globalvalue we will endow with a body.
243 llvm::Constant *NewPtrForOldDecl =
244 llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
245 GV->replaceAllUsesWith(NewPtrForOldDecl);
246
247 // FIXME: Update the globaldeclmap for the previous decl of this name. We
248 // really want a way to walk all of these, but we don't have it yet. This
249 // is incredibly slow!
250 ReplaceMapValuesWith(GV, NewPtrForOldDecl);
251
Chris Lattnerc4b23a52008-02-05 06:37:34 +0000252 // Verify that GV was a declaration or something like x[] which turns into
253 // [0 x type].
254 assert((GV->isDeclaration() ||
255 IsZeroElementArray(GV->getType()->getElementType())) &&
256 "Shouldn't replace non-declaration");
257
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000258 // Ok, delete the old global now, which is dead.
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000259 GV->eraseFromParent();
260
261 // Return the new global which has the right type.
262 return Entry = NewGV;
Reid Spencer5f016e22007-07-11 17:01:13 +0000263}
264
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000265
Chris Lattner88a69ad2007-07-13 05:13:43 +0000266void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000267 // If this is not a prototype, emit the body.
268 if (FD->getBody())
269 CodeGenFunction(*this).GenerateCode(FD);
270}
271
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000272llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
273 return EmitConstantExpr(Expr);
Devang Patel9e32d4b2007-10-30 21:27:20 +0000274}
275
Chris Lattner88a69ad2007-07-13 05:13:43 +0000276void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000277 // If this is just a forward declaration of the variable, don't emit it now,
278 // allow it to be emitted lazily on its first use.
Chris Lattner88a69ad2007-07-13 05:13:43 +0000279 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
280 return;
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000281
282 // Get the global, forcing it to be a direct reference.
283 llvm::GlobalVariable *GV =
Chris Lattner2b9d2ca2007-12-18 08:16:44 +0000284 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
Chris Lattner9cd4fe42007-12-02 07:09:19 +0000285
286 // Convert the initializer, or use zero if appropriate.
Chris Lattner8f32f712007-07-14 00:23:28 +0000287 llvm::Constant *Init = 0;
288 if (D->getInit() == 0) {
Chris Lattner88a69ad2007-07-13 05:13:43 +0000289 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
Chris Lattner8f32f712007-07-14 00:23:28 +0000290 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiser7b660002007-10-17 15:00:17 +0000291 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattner98be4942008-03-05 18:54:05 +0000292 getContext().getTypeSize(D->getInit()->getType())));
Chris Lattner590b6642007-07-15 23:26:56 +0000293 if (D->getInit()->isIntegerConstantExpr(Value, Context))
Chris Lattner8f32f712007-07-14 00:23:28 +0000294 Init = llvm::ConstantInt::get(Value);
295 }
Devang Patel8e53e722007-10-26 16:31:40 +0000296
Devang Patel9e32d4b2007-10-30 21:27:20 +0000297 if (!Init)
Oliver Hunt28247232007-12-02 00:11:25 +0000298 Init = EmitGlobalInit(D->getInit());
Devang Patel8e53e722007-10-26 16:31:40 +0000299
Chris Lattnerf89dfb22007-12-10 00:05:55 +0000300 assert(GV->getType()->getElementType() == Init->getType() &&
301 "Initializer codegen type mismatch!");
Chris Lattner88a69ad2007-07-13 05:13:43 +0000302 GV->setInitializer(Init);
Chris Lattnerddee4232008-03-03 03:28:21 +0000303
304 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
305 GV->setVisibility(attr->getVisibility());
306 // FIXME: else handle -fvisibility
Chris Lattner88a69ad2007-07-13 05:13:43 +0000307
308 // Set the llvm linkage type as appropriate.
Chris Lattnerddee4232008-03-03 03:28:21 +0000309 if (D->getAttr<DLLImportAttr>())
310 GV->setLinkage(llvm::Function::DLLImportLinkage);
311 else if (D->getAttr<DLLExportAttr>())
312 GV->setLinkage(llvm::Function::DLLExportLinkage);
313 else if (D->getAttr<WeakAttr>()) {
314 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
315
316 } else {
317 // FIXME: This isn't right. This should handle common linkage and other
318 // stuff.
319 switch (D->getStorageClass()) {
320 case VarDecl::Auto:
321 case VarDecl::Register:
322 assert(0 && "Can't have auto or register globals");
323 case VarDecl::None:
324 if (!D->getInit())
325 GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
326 break;
327 case VarDecl::Extern:
328 case VarDecl::PrivateExtern:
329 // todo: common
330 break;
331 case VarDecl::Static:
332 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
333 break;
334 }
Chris Lattner88a69ad2007-07-13 05:13:43 +0000335 }
336}
Reid Spencer5f016e22007-07-11 17:01:13 +0000337
Chris Lattner32b266c2007-07-14 00:16:50 +0000338/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
339/// declarator chain.
340void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
341 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
342 EmitGlobalVar(D);
343}
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
Chris Lattnerc5b88062008-02-06 05:08:19 +0000345void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
346 // Make sure that this type is translated.
347 Types.UpdateCompletedType(TD);
Chris Lattnerd86e6bc2008-02-05 08:06:13 +0000348}
349
350
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000351/// getBuiltinLibFunction
352llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
Chris Lattner1426fec2007-12-13 00:38:03 +0000353 if (BuiltinID > BuiltinFunctions.size())
354 BuiltinFunctions.resize(BuiltinID);
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000355
Chris Lattner1426fec2007-12-13 00:38:03 +0000356 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve
357 // a slot for it.
358 assert(BuiltinID && "Invalid Builtin ID");
359 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000360 if (FunctionSlot)
361 return FunctionSlot;
362
363 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
364
365 // Get the name, skip over the __builtin_ prefix.
366 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
367
368 // Get the type for the builtin.
369 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
370 const llvm::FunctionType *Ty =
371 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
372
373 // FIXME: This has a serious problem with code like this:
374 // void abs() {}
375 // ... __builtin_abs(x);
376 // The two versions of abs will collide. The fix is for the builtin to win,
377 // and for the existing one to be turned into a constantexpr cast of the
378 // builtin. In the case where the existing one is a static function, it
379 // should just be renamed.
Chris Lattnerc5e940f2007-08-31 04:44:06 +0000380 if (llvm::Function *Existing = getModule().getFunction(Name)) {
381 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
382 return FunctionSlot = Existing;
383 assert(Existing == 0 && "FIXME: Name collision");
384 }
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000385
386 // FIXME: param attributes for sext/zext etc.
387 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
388 Name, &getModule());
389}
390
Chris Lattner7acda7c2007-12-18 00:25:38 +0000391llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
392 unsigned NumTys) {
393 return llvm::Intrinsic::getDeclaration(&getModule(),
394 (llvm::Intrinsic::ID)IID, Tys, NumTys);
395}
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000396
Reid Spencer5f016e22007-07-11 17:01:13 +0000397llvm::Function *CodeGenModule::getMemCpyFn() {
398 if (MemCpyFn) return MemCpyFn;
399 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000400 switch (Context.Target.getPointerWidth(0)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000401 default: assert(0 && "Unknown ptr width");
402 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
403 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
404 }
Chris Lattner7acda7c2007-12-18 00:25:38 +0000405 return MemCpyFn = getIntrinsic(IID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000406}
Anders Carlssonc9e20912007-08-21 00:21:21 +0000407
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000408llvm::Function *CodeGenModule::getMemSetFn() {
409 if (MemSetFn) return MemSetFn;
410 llvm::Intrinsic::ID IID;
Chris Lattnerf72a4432008-03-08 08:34:58 +0000411 switch (Context.Target.getPointerWidth(0)) {
Lauro Ramos Venancio41ef30e2008-02-19 22:01:01 +0000412 default: assert(0 && "Unknown ptr width");
413 case 32: IID = llvm::Intrinsic::memset_i32; break;
414 case 64: IID = llvm::Intrinsic::memset_i64; break;
415 }
416 return MemSetFn = getIntrinsic(IID);
417}
Chris Lattner7acda7c2007-12-18 00:25:38 +0000418
Chris Lattnerbef20ac2007-08-31 04:31:45 +0000419llvm::Constant *CodeGenModule::
420GetAddrOfConstantCFString(const std::string &str) {
Anders Carlssonc9e20912007-08-21 00:21:21 +0000421 llvm::StringMapEntry<llvm::Constant *> &Entry =
422 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
423
424 if (Entry.getValue())
425 return Entry.getValue();
426
427 std::vector<llvm::Constant*> Fields;
428
429 if (!CFConstantStringClassRef) {
430 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
431 Ty = llvm::ArrayType::get(Ty, 0);
432
433 CFConstantStringClassRef =
434 new llvm::GlobalVariable(Ty, false,
435 llvm::GlobalVariable::ExternalLinkage, 0,
436 "__CFConstantStringClassReference",
437 &getModule());
438 }
439
440 // Class pointer.
441 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
442 llvm::Constant *Zeros[] = { Zero, Zero };
443 llvm::Constant *C =
444 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
445 Fields.push_back(C);
446
447 // Flags.
448 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
449 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
450
451 // String pointer.
452 C = llvm::ConstantArray::get(str);
453 C = new llvm::GlobalVariable(C->getType(), true,
454 llvm::GlobalValue::InternalLinkage,
455 C, ".str", &getModule());
456
457 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
458 Fields.push_back(C);
459
460 // String length.
461 Ty = getTypes().ConvertType(getContext().LongTy);
462 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
463
464 // The struct.
465 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
466 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
Anders Carlsson0c678292007-11-01 00:41:52 +0000467 llvm::GlobalVariable *GV =
468 new llvm::GlobalVariable(C->getType(), true,
469 llvm::GlobalVariable::InternalLinkage,
470 C, "", &getModule());
471 GV->setSection("__DATA,__cfstring");
472 Entry.setValue(GV);
473 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +0000474}
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000475
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000476/// GenerateWritableString -- Creates storage for a string literal.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000477static llvm::Constant *GenerateStringLiteral(const std::string &str,
478 bool constant,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000479 CodeGenModule &CGM) {
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000480 // Create Constant for this string literal
481 llvm::Constant *C=llvm::ConstantArray::get(str);
482
483 // Create a global variable for this string
484 C = new llvm::GlobalVariable(C->getType(), constant,
485 llvm::GlobalValue::InternalLinkage,
Chris Lattner2c8569d2007-12-02 07:19:18 +0000486 C, ".str", &CGM.getModule());
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000487 return C;
488}
489
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000490/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
491/// array containing the literal. The result is pointer to array type.
Chris Lattner45e8cbd2007-11-28 05:34:05 +0000492llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
493 // Don't share any string literals if writable-strings is turned on.
494 if (Features.WritableStrings)
495 return GenerateStringLiteral(str, false, *this);
496
497 llvm::StringMapEntry<llvm::Constant *> &Entry =
498 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
499
500 if (Entry.getValue())
501 return Entry.getValue();
502
503 // Create a global variable for this.
504 llvm::Constant *C = GenerateStringLiteral(str, true, *this);
505 Entry.setValue(C);
506 return C;
507}