CodeGenModule.cpp revision be14c5c6e29af948f6f809c499f83d844e755af9
1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/LangOptions.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "llvm/CallingConv.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Module.h"
27#include "llvm/Intrinsics.h"
28#include "llvm/Analysis/Verifier.h"
29#include <algorithm>
30using namespace clang;
31using namespace CodeGen;
32
33
34CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35                             llvm::Module &M, const llvm::TargetData &TD,
36                             Diagnostic &diags, bool GenerateDebugInfo)
37  : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
38    Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
39  //TODO: Make this selectable at runtime
40  Runtime = CreateObjCRuntime(M,
41      getTypes().ConvertType(getContext().IntTy),
42      getTypes().ConvertType(getContext().LongTy));
43
44  // If debug info generation is enabled, create the CGDebugInfo object.
45  if (GenerateDebugInfo)
46    DebugInfo = new CGDebugInfo(this);
47  else
48    DebugInfo = NULL;
49}
50
51CodeGenModule::~CodeGenModule() {
52  llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
53  if (ObjCInitFunction)
54    AddGlobalCtor(ObjCInitFunction);
55  EmitStatics();
56  EmitGlobalCtors();
57  EmitAnnotations();
58  delete Runtime;
59  delete DebugInfo;
60  // Run the verifier to check that the generated code is consistent.
61  assert(!verifyModule(TheModule));
62}
63
64/// 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;
71  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
72                    &Msg, 1, &Range, 1);
73}
74
75/// 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
85/// AddGlobalCtor - Add a function to the list that will be called before
86/// main() runs.
87void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
88  // TODO: Type coercion of void()* types.
89  GlobalCtors.push_back(Ctor);
90}
91
92/// EmitGlobalCtors - Generates the array of contsturctor functions to be
93/// called on module load, if any have been registered with AddGlobalCtor.
94void CodeGenModule::EmitGlobalCtors() {
95  if (GlobalCtors.empty()) return;
96
97  // Get the type of @llvm.global_ctors
98  std::vector<const llvm::Type*> CtorFields;
99  CtorFields.push_back(llvm::IntegerType::get(32));
100  // Constructor function type
101  std::vector<const llvm::Type*> VoidArgs;
102  llvm::FunctionType* CtorFuncTy =
103    llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
104
105  // i32, function type pair
106  const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
107  llvm::StructType* CtorStructTy =
108  llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
109  // Array of fields
110  llvm::ArrayType* GlobalCtorsTy =
111    llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
112
113  // Define the global variable
114  llvm::GlobalVariable *GlobalCtorsVal =
115    new llvm::GlobalVariable(GlobalCtorsTy, false,
116                             llvm::GlobalValue::AppendingLinkage,
117                             (llvm::Constant*)0, "llvm.global_ctors",
118                             &TheModule);
119
120  // Populate the array
121  std::vector<llvm::Constant*> CtorValues;
122  llvm::Constant *MagicNumber =
123    llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
124  std::vector<llvm::Constant*> StructValues;
125  for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
126       E = GlobalCtors.end(); I != E; ++I) {
127    StructValues.clear();
128    StructValues.push_back(MagicNumber);
129    StructValues.push_back(*I);
130
131    CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
132  }
133
134  GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
135                                                          CtorValues));
136}
137
138
139
140void CodeGenModule::EmitAnnotations() {
141  if (Annotations.empty())
142    return;
143
144  // Create a new global variable for the ConstantStruct in the Module.
145  llvm::Constant *Array =
146  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
147                                                Annotations.size()),
148                           Annotations);
149  llvm::GlobalValue *gv =
150  new llvm::GlobalVariable(Array->getType(), false,
151                           llvm::GlobalValue::AppendingLinkage, Array,
152                           "llvm.global.annotations", &TheModule);
153  gv->setSection("llvm.metadata");
154}
155
156/// ReplaceMapValuesWith - This is a really slow and bad function that
157/// searches for any entries in GlobalDeclMap that point to OldVal, changing
158/// them to point to NewVal.  This is badbadbad, FIXME!
159void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
160                                         llvm::Constant *NewVal) {
161  for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
162       I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
163    if (I->second == OldVal) I->second = NewVal;
164}
165
166
167llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
168                                                     bool isDefinition) {
169  // See if it is already in the map.  If so, just return it.
170  llvm::Constant *&Entry = GlobalDeclMap[D];
171#if 0
172  // FIXME: The cache is currently broken!
173  if (Entry) return Entry;
174#endif
175
176  const llvm::Type *Ty = getTypes().ConvertType(D->getType());
177
178  // Check to see if the function already exists.
179  llvm::Function *F = getModule().getFunction(D->getName());
180  const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
181
182  // If it doesn't already exist, just create and return an entry.
183  if (F == 0) {
184    // FIXME: param attributes for sext/zext etc.
185    F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
186                               D->getName(), &getModule());
187
188    // Set the appropriate calling convention for the Function.
189    if (D->getAttr<FastCallAttr>())
190      F->setCallingConv(llvm::CallingConv::Fast);
191    return Entry = F;
192  }
193
194  // If the pointer type matches, just return it.
195  llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
196  if (PFTy == F->getType()) return Entry = F;
197
198  // If this isn't a definition, just return it casted to the right type.
199  if (!isDefinition)
200    return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
201
202  // Otherwise, we have a definition after a prototype with the wrong type.
203  // F is the Function* for the one with the wrong type, we must make a new
204  // Function* and update everything that used F (a declaration) with the new
205  // Function* (which will be a definition).
206  //
207  // This happens if there is a prototype for a function (e.g. "int f()") and
208  // then a definition of a different type (e.g. "int f(int x)").  Start by
209  // making a new function of the correct type, RAUW, then steal the name.
210  llvm::Function *NewFn = llvm::Function::Create(FTy,
211                                             llvm::Function::ExternalLinkage,
212                                             "", &getModule());
213  NewFn->takeName(F);
214
215  // Replace uses of F with the Function we will endow with a body.
216  llvm::Constant *NewPtrForOldDecl =
217    llvm::ConstantExpr::getBitCast(NewFn, F->getType());
218  F->replaceAllUsesWith(NewPtrForOldDecl);
219
220  // FIXME: Update the globaldeclmap for the previous decl of this name.  We
221  // really want a way to walk all of these, but we don't have it yet.  This
222  // is incredibly slow!
223  ReplaceMapValuesWith(F, NewPtrForOldDecl);
224
225  // Ok, delete the old function now, which is dead.
226  assert(F->isDeclaration() && "Shouldn't replace non-declaration");
227  F->eraseFromParent();
228
229  // Return the new function which has the right type.
230  return Entry = NewFn;
231}
232
233static bool IsZeroElementArray(const llvm::Type *Ty) {
234  if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
235    return ATy->getNumElements() == 0;
236  return false;
237}
238
239llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
240                                                  bool isDefinition) {
241  assert(D->hasGlobalStorage() && "Not a global variable");
242
243  // See if it is already in the map.
244  llvm::Constant *&Entry = GlobalDeclMap[D];
245  if (Entry) return Entry;
246
247  QualType ASTTy = D->getType();
248  const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
249
250  // Check to see if the global already exists.
251  llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
252
253  // If it doesn't already exist, just create and return an entry.
254  if (GV == 0) {
255    return Entry = new llvm::GlobalVariable(Ty, false,
256                                            llvm::GlobalValue::ExternalLinkage,
257                                            0, D->getName(), &getModule(), 0,
258                                            ASTTy.getAddressSpace());
259  }
260
261  // If the pointer type matches, just return it.
262  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
263  if (PTy == GV->getType()) return Entry = GV;
264
265  // If this isn't a definition, just return it casted to the right type.
266  if (!isDefinition)
267    return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
268
269
270  // Otherwise, we have a definition after a prototype with the wrong type.
271  // GV is the GlobalVariable* for the one with the wrong type, we must make a
272  /// new GlobalVariable* and update everything that used GV (a declaration)
273  // with the new GlobalVariable* (which will be a definition).
274  //
275  // This happens if there is a prototype for a global (e.g. "extern int x[];")
276  // and then a definition of a different type (e.g. "int x[10];").  Start by
277  // making a new global of the correct type, RAUW, then steal the name.
278  llvm::GlobalVariable *NewGV =
279    new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
280                             0, D->getName(), &getModule(), 0,
281                             ASTTy.getAddressSpace());
282  NewGV->takeName(GV);
283
284  // Replace uses of GV with the globalvalue we will endow with a body.
285  llvm::Constant *NewPtrForOldDecl =
286    llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
287  GV->replaceAllUsesWith(NewPtrForOldDecl);
288
289  // FIXME: Update the globaldeclmap for the previous decl of this name.  We
290  // really want a way to walk all of these, but we don't have it yet.  This
291  // is incredibly slow!
292  ReplaceMapValuesWith(GV, NewPtrForOldDecl);
293
294  // Verify that GV was a declaration or something like x[] which turns into
295  // [0 x type].
296  assert((GV->isDeclaration() ||
297          IsZeroElementArray(GV->getType()->getElementType())) &&
298         "Shouldn't replace non-declaration");
299
300  // Ok, delete the old global now, which is dead.
301  GV->eraseFromParent();
302
303  // Return the new global which has the right type.
304  return Entry = NewGV;
305}
306
307
308void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
309  // If this is not a prototype, emit the body.
310  if (OMD->getBody())
311    CodeGenFunction(*this).GenerateObjCMethod(OMD);
312}
313
314void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
315  // If this is not a prototype, emit the body.
316  if (!FD->isThisDeclarationADefinition())
317    return;
318
319  // If the function is a static, defer code generation until later so we can
320  // easily omit unused statics.
321  if (FD->getStorageClass() != FunctionDecl::Static) {
322    CodeGenFunction(*this).GenerateCode(FD);
323    return;
324  }
325
326  // We need to check the Module here to see if GetAddrOfFunctionDecl() has
327  // already added this function to the Module because the address of the
328  // function's prototype was taken.  If this is the case, call
329  // GetAddrOfFunctionDecl to insert the static FunctionDecl into the used
330  // GlobalDeclsMap, so that EmitStatics will generate code for it later.
331  //
332  // Example:
333  // static int foo();
334  // int bar() { return foo(); }
335  // static int foo() { return 5; }
336  if (getModule().getFunction(FD->getName()))
337    GetAddrOfFunctionDecl(FD, true);
338
339  StaticDecls.push_back(FD);
340}
341
342void CodeGenModule::EmitStatics() {
343  // Emit code for each used static decl encountered.  Since a previously unused
344  // static decl may become used during the generation of code for a static
345  // function, iterate until no changes are made.
346  bool Changed;
347  do {
348    Changed = false;
349    for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
350      // Check the map of used decls for our static. If not found, continue.
351      const Decl *D = StaticDecls[i];
352      if (!GlobalDeclMap.count(D))
353        continue;
354
355      // If this is a function decl, generate code for the static function if it
356      // has a body.  Otherwise, we must have a var decl for a static global
357      // variable.
358      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
359        if (FD->getBody())
360          CodeGenFunction(*this).GenerateCode(FD);
361      } else {
362        EmitGlobalVarInit(cast<VarDecl>(D));
363      }
364      // Erase the used decl from the list.
365      StaticDecls[i] = StaticDecls.back();
366      StaticDecls.pop_back();
367      --i;
368      --e;
369
370      // Remember that we made a change.
371      Changed = true;
372    }
373  } while (Changed);
374}
375
376llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
377  return EmitConstantExpr(Expr);
378}
379
380/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
381/// annotation information for a given GlobalValue.  The annotation struct is
382/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
383/// GlobalValue being annotated.  The second filed is thee constant string
384/// created from the AnnotateAttr's annotation.  The third field is a constant
385/// string containing the name of the translation unit.  The fourth field is
386/// the line number in the file of the annotated value declaration.
387///
388/// FIXME: this does not unique the annotation string constants, as llvm-gcc
389///        appears to.
390///
391llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
392                                                const AnnotateAttr *AA,
393                                                unsigned LineNo) {
394  llvm::Module *M = &getModule();
395
396  // get [N x i8] constants for the annotation string, and the filename string
397  // which are the 2nd and 3rd elements of the global annotation structure.
398  const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
399  llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
400  llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
401                                                  true);
402
403  // Get the two global values corresponding to the ConstantArrays we just
404  // created to hold the bytes of the strings.
405  llvm::GlobalValue *annoGV =
406  new llvm::GlobalVariable(anno->getType(), false,
407                           llvm::GlobalValue::InternalLinkage, anno,
408                           GV->getName() + ".str", M);
409  // translation unit name string, emitted into the llvm.metadata section.
410  llvm::GlobalValue *unitGV =
411  new llvm::GlobalVariable(unit->getType(), false,
412                           llvm::GlobalValue::InternalLinkage, unit, ".str", M);
413
414  // Create the ConstantStruct that is the global annotion.
415  llvm::Constant *Fields[4] = {
416    llvm::ConstantExpr::getBitCast(GV, SBP),
417    llvm::ConstantExpr::getBitCast(annoGV, SBP),
418    llvm::ConstantExpr::getBitCast(unitGV, SBP),
419    llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
420  };
421  return llvm::ConstantStruct::get(Fields, 4, false);
422}
423
424void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
425  // If the VarDecl is a static, defer code generation until later so we can
426  // easily omit unused statics.
427  if (D->getStorageClass() == VarDecl::Static) {
428    StaticDecls.push_back(D);
429    return;
430  }
431
432  // If this is just a forward declaration of the variable, don't emit it now,
433  // allow it to be emitted lazily on its first use.
434  if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
435    return;
436
437  EmitGlobalVarInit(D);
438}
439
440void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
441  // Get the global, forcing it to be a direct reference.
442  llvm::GlobalVariable *GV =
443    cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
444
445  // Convert the initializer, or use zero if appropriate.
446  llvm::Constant *Init = 0;
447  if (D->getInit() == 0) {
448    Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
449  } else if (D->getType()->isIntegerType()) {
450    llvm::APSInt Value(static_cast<uint32_t>(
451      getContext().getTypeSize(D->getInit()->getType())));
452    if (D->getInit()->isIntegerConstantExpr(Value, Context))
453      Init = llvm::ConstantInt::get(Value);
454  }
455
456  if (!Init)
457    Init = EmitGlobalInit(D->getInit());
458
459  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
460    SourceManager &SM = Context.getSourceManager();
461    AddAnnotation(EmitAnnotateAttr(GV, AA,
462                                   SM.getLogicalLineNumber(D->getLocation())));
463  }
464
465  assert(GV->getType()->getElementType() == Init->getType() &&
466         "Initializer codegen type mismatch!");
467  GV->setInitializer(Init);
468
469  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
470    GV->setVisibility(attr->getVisibility());
471  // FIXME: else handle -fvisibility
472
473  // Set the llvm linkage type as appropriate.
474  if (D->getStorageClass() == VarDecl::Static)
475    GV->setLinkage(llvm::Function::InternalLinkage);
476  else if (D->getAttr<DLLImportAttr>())
477    GV->setLinkage(llvm::Function::DLLImportLinkage);
478  else if (D->getAttr<DLLExportAttr>())
479    GV->setLinkage(llvm::Function::DLLExportLinkage);
480  else if (D->getAttr<WeakAttr>())
481    GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
482  else {
483    // FIXME: This isn't right.  This should handle common linkage and other
484    // stuff.
485    switch (D->getStorageClass()) {
486    case VarDecl::Static: assert(0 && "This case handled above");
487    case VarDecl::Auto:
488    case VarDecl::Register:
489      assert(0 && "Can't have auto or register globals");
490    case VarDecl::None:
491      if (!D->getInit())
492        GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
493      break;
494    case VarDecl::Extern:
495    case VarDecl::PrivateExtern:
496      // todo: common
497      break;
498    }
499  }
500}
501
502/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
503/// declarator chain.
504void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
505  for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
506    if (D->isFileVarDecl())
507      EmitGlobalVar(D);
508}
509
510void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
511  // Make sure that this type is translated.
512  Types.UpdateCompletedType(TD);
513}
514
515
516/// getBuiltinLibFunction
517llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
518  if (BuiltinID > BuiltinFunctions.size())
519    BuiltinFunctions.resize(BuiltinID);
520
521  // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
522  // a slot for it.
523  assert(BuiltinID && "Invalid Builtin ID");
524  llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
525  if (FunctionSlot)
526    return FunctionSlot;
527
528  assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
529
530  // Get the name, skip over the __builtin_ prefix.
531  const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
532
533  // Get the type for the builtin.
534  QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
535  const llvm::FunctionType *Ty =
536    cast<llvm::FunctionType>(getTypes().ConvertType(Type));
537
538  // FIXME: This has a serious problem with code like this:
539  //  void abs() {}
540  //    ... __builtin_abs(x);
541  // The two versions of abs will collide.  The fix is for the builtin to win,
542  // and for the existing one to be turned into a constantexpr cast of the
543  // builtin.  In the case where the existing one is a static function, it
544  // should just be renamed.
545  if (llvm::Function *Existing = getModule().getFunction(Name)) {
546    if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
547      return FunctionSlot = Existing;
548    assert(Existing == 0 && "FIXME: Name collision");
549  }
550
551  // FIXME: param attributes for sext/zext etc.
552  return FunctionSlot =
553    llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
554                           &getModule());
555}
556
557llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
558                                            unsigned NumTys) {
559  return llvm::Intrinsic::getDeclaration(&getModule(),
560                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
561}
562
563llvm::Function *CodeGenModule::getMemCpyFn() {
564  if (MemCpyFn) return MemCpyFn;
565  llvm::Intrinsic::ID IID;
566  switch (Context.Target.getPointerWidth(0)) {
567  default: assert(0 && "Unknown ptr width");
568  case 32: IID = llvm::Intrinsic::memcpy_i32; break;
569  case 64: IID = llvm::Intrinsic::memcpy_i64; break;
570  }
571  return MemCpyFn = getIntrinsic(IID);
572}
573
574llvm::Function *CodeGenModule::getMemSetFn() {
575  if (MemSetFn) return MemSetFn;
576  llvm::Intrinsic::ID IID;
577  switch (Context.Target.getPointerWidth(0)) {
578  default: assert(0 && "Unknown ptr width");
579  case 32: IID = llvm::Intrinsic::memset_i32; break;
580  case 64: IID = llvm::Intrinsic::memset_i64; break;
581  }
582  return MemSetFn = getIntrinsic(IID);
583}
584
585llvm::Constant *CodeGenModule::
586GetAddrOfConstantCFString(const std::string &str) {
587  llvm::StringMapEntry<llvm::Constant *> &Entry =
588    CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
589
590  if (Entry.getValue())
591    return Entry.getValue();
592
593  std::vector<llvm::Constant*> Fields;
594
595  if (!CFConstantStringClassRef) {
596    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
597    Ty = llvm::ArrayType::get(Ty, 0);
598
599    CFConstantStringClassRef =
600      new llvm::GlobalVariable(Ty, false,
601                               llvm::GlobalVariable::ExternalLinkage, 0,
602                               "__CFConstantStringClassReference",
603                               &getModule());
604  }
605
606  // Class pointer.
607  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
608  llvm::Constant *Zeros[] = { Zero, Zero };
609  llvm::Constant *C =
610    llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
611  Fields.push_back(C);
612
613  // Flags.
614  const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
615  Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
616
617  // String pointer.
618  C = llvm::ConstantArray::get(str);
619  C = new llvm::GlobalVariable(C->getType(), true,
620                               llvm::GlobalValue::InternalLinkage,
621                               C, ".str", &getModule());
622
623  C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
624  Fields.push_back(C);
625
626  // String length.
627  Ty = getTypes().ConvertType(getContext().LongTy);
628  Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
629
630  // The struct.
631  Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
632  C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
633  llvm::GlobalVariable *GV =
634    new llvm::GlobalVariable(C->getType(), true,
635                             llvm::GlobalVariable::InternalLinkage,
636                             C, "", &getModule());
637  GV->setSection("__DATA,__cfstring");
638  Entry.setValue(GV);
639  return GV;
640}
641
642/// GenerateWritableString -- Creates storage for a string literal.
643static llvm::Constant *GenerateStringLiteral(const std::string &str,
644                                             bool constant,
645                                             CodeGenModule &CGM) {
646  // Create Constant for this string literal
647  llvm::Constant *C=llvm::ConstantArray::get(str);
648
649  // Create a global variable for this string
650  C = new llvm::GlobalVariable(C->getType(), constant,
651                               llvm::GlobalValue::InternalLinkage,
652                               C, ".str", &CGM.getModule());
653  return C;
654}
655
656/// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
657/// array containing the literal.  The result is pointer to array type.
658llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
659  // Don't share any string literals if writable-strings is turned on.
660  if (Features.WritableStrings)
661    return GenerateStringLiteral(str, false, *this);
662
663  llvm::StringMapEntry<llvm::Constant *> &Entry =
664  ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
665
666  if (Entry.getValue())
667      return Entry.getValue();
668
669  // Create a global variable for this.
670  llvm::Constant *C = GenerateStringLiteral(str, true, *this);
671  Entry.setValue(C);
672  return C;
673}
674