CodeGenModule.cpp revision 204962
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 "CodeGenModule.h"
15#include "CGDebugInfo.h"
16#include "CodeGenFunction.h"
17#include "CGCall.h"
18#include "CGObjCRuntime.h"
19#include "Mangle.h"
20#include "TargetInfo.h"
21#include "clang/CodeGen/CodeGenOptions.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/Diagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/ConvertUTF.h"
32#include "llvm/CallingConv.h"
33#include "llvm/Module.h"
34#include "llvm/Intrinsics.h"
35#include "llvm/LLVMContext.h"
36#include "llvm/ADT/Triple.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Support/ErrorHandling.h"
39using namespace clang;
40using namespace CodeGen;
41
42
43CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
44                             llvm::Module &M, const llvm::TargetData &TD,
45                             Diagnostic &diags)
46  : BlockModule(C, M, TD, Types, *this), Context(C),
47    Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
48    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
49    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
50    MangleCtx(C), VtableInfo(*this), Runtime(0),
51    MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0),
52    VMContext(M.getContext()) {
53
54  if (!Features.ObjC1)
55    Runtime = 0;
56  else if (!Features.NeXTRuntime)
57    Runtime = CreateGNUObjCRuntime(*this);
58  else if (Features.ObjCNonFragileABI)
59    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
60  else
61    Runtime = CreateMacObjCRuntime(*this);
62
63  // If debug info generation is enabled, create the CGDebugInfo object.
64  DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
65}
66
67CodeGenModule::~CodeGenModule() {
68  delete Runtime;
69  delete DebugInfo;
70}
71
72void CodeGenModule::createObjCRuntime() {
73  if (!Features.NeXTRuntime)
74    Runtime = CreateGNUObjCRuntime(*this);
75  else if (Features.ObjCNonFragileABI)
76    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
77  else
78    Runtime = CreateMacObjCRuntime(*this);
79}
80
81void CodeGenModule::Release() {
82  EmitDeferred();
83  EmitCXXGlobalInitFunc();
84  if (Runtime)
85    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
86      AddGlobalCtor(ObjCInitFunction);
87  EmitCtorList(GlobalCtors, "llvm.global_ctors");
88  EmitCtorList(GlobalDtors, "llvm.global_dtors");
89  EmitAnnotations();
90  EmitLLVMUsed();
91}
92
93bool CodeGenModule::isTargetDarwin() const {
94  return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
95}
96
97/// ErrorUnsupported - Print out an error that codegen doesn't support the
98/// specified stmt yet.
99void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
100                                     bool OmitOnError) {
101  if (OmitOnError && getDiags().hasErrorOccurred())
102    return;
103  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
104                                               "cannot compile this %0 yet");
105  std::string Msg = Type;
106  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
107    << Msg << S->getSourceRange();
108}
109
110/// ErrorUnsupported - Print out an error that codegen doesn't support the
111/// specified decl yet.
112void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
113                                     bool OmitOnError) {
114  if (OmitOnError && getDiags().hasErrorOccurred())
115    return;
116  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
117                                               "cannot compile this %0 yet");
118  std::string Msg = Type;
119  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
120}
121
122LangOptions::VisibilityMode
123CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
124  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
125    if (VD->getStorageClass() == VarDecl::PrivateExtern)
126      return LangOptions::Hidden;
127
128  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
129    switch (attr->getVisibility()) {
130    default: assert(0 && "Unknown visibility!");
131    case VisibilityAttr::DefaultVisibility:
132      return LangOptions::Default;
133    case VisibilityAttr::HiddenVisibility:
134      return LangOptions::Hidden;
135    case VisibilityAttr::ProtectedVisibility:
136      return LangOptions::Protected;
137    }
138  }
139
140  // This decl should have the same visibility as its parent.
141  if (const DeclContext *DC = D->getDeclContext())
142    return getDeclVisibilityMode(cast<Decl>(DC));
143
144  return getLangOptions().getVisibilityMode();
145}
146
147void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
148                                        const Decl *D) const {
149  // Internal definitions always have default visibility.
150  if (GV->hasLocalLinkage()) {
151    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
152    return;
153  }
154
155  switch (getDeclVisibilityMode(D)) {
156  default: assert(0 && "Unknown visibility!");
157  case LangOptions::Default:
158    return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
159  case LangOptions::Hidden:
160    return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
161  case LangOptions::Protected:
162    return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
163  }
164}
165
166const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
167  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
168
169  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
170    return getMangledCXXCtorName(D, GD.getCtorType());
171  if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
172    return getMangledCXXDtorName(D, GD.getDtorType());
173
174  return getMangledName(ND);
175}
176
177/// \brief Retrieves the mangled name for the given declaration.
178///
179/// If the given declaration requires a mangled name, returns an
180/// const char* containing the mangled name.  Otherwise, returns
181/// the unmangled name.
182///
183const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
184  if (!getMangleContext().shouldMangleDeclName(ND)) {
185    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
186    return ND->getNameAsCString();
187  }
188
189  llvm::SmallString<256> Name;
190  getMangleContext().mangleName(ND, Name);
191  Name += '\0';
192  return UniqueMangledName(Name.begin(), Name.end());
193}
194
195const char *CodeGenModule::UniqueMangledName(const char *NameStart,
196                                             const char *NameEnd) {
197  assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
198
199  return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
200}
201
202/// AddGlobalCtor - Add a function to the list that will be called before
203/// main() runs.
204void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
205  // FIXME: Type coercion of void()* types.
206  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
207}
208
209/// AddGlobalDtor - Add a function to the list that will be called
210/// when the module is unloaded.
211void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
212  // FIXME: Type coercion of void()* types.
213  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
214}
215
216void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
217  // Ctor function type is void()*.
218  llvm::FunctionType* CtorFTy =
219    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
220                            std::vector<const llvm::Type*>(),
221                            false);
222  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
223
224  // Get the type of a ctor entry, { i32, void ()* }.
225  llvm::StructType* CtorStructTy =
226    llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
227                          llvm::PointerType::getUnqual(CtorFTy), NULL);
228
229  // Construct the constructor and destructor arrays.
230  std::vector<llvm::Constant*> Ctors;
231  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
232    std::vector<llvm::Constant*> S;
233    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
234                I->second, false));
235    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
236    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
237  }
238
239  if (!Ctors.empty()) {
240    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
241    new llvm::GlobalVariable(TheModule, AT, false,
242                             llvm::GlobalValue::AppendingLinkage,
243                             llvm::ConstantArray::get(AT, Ctors),
244                             GlobalName);
245  }
246}
247
248void CodeGenModule::EmitAnnotations() {
249  if (Annotations.empty())
250    return;
251
252  // Create a new global variable for the ConstantStruct in the Module.
253  llvm::Constant *Array =
254  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
255                                                Annotations.size()),
256                           Annotations);
257  llvm::GlobalValue *gv =
258  new llvm::GlobalVariable(TheModule, Array->getType(), false,
259                           llvm::GlobalValue::AppendingLinkage, Array,
260                           "llvm.global.annotations");
261  gv->setSection("llvm.metadata");
262}
263
264static CodeGenModule::GVALinkage
265GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
266                      const LangOptions &Features) {
267  CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
268
269  Linkage L = FD->getLinkage();
270  if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
271      FD->getType()->getLinkage() == UniqueExternalLinkage)
272    L = UniqueExternalLinkage;
273
274  switch (L) {
275  case NoLinkage:
276  case InternalLinkage:
277  case UniqueExternalLinkage:
278    return CodeGenModule::GVA_Internal;
279
280  case ExternalLinkage:
281    switch (FD->getTemplateSpecializationKind()) {
282    case TSK_Undeclared:
283    case TSK_ExplicitSpecialization:
284      External = CodeGenModule::GVA_StrongExternal;
285      break;
286
287    case TSK_ExplicitInstantiationDefinition:
288      // FIXME: explicit instantiation definitions should use weak linkage
289      return CodeGenModule::GVA_StrongExternal;
290
291    case TSK_ExplicitInstantiationDeclaration:
292    case TSK_ImplicitInstantiation:
293      External = CodeGenModule::GVA_TemplateInstantiation;
294      break;
295    }
296  }
297
298  if (!FD->isInlined())
299    return External;
300
301  if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
302    // GNU or C99 inline semantics. Determine whether this symbol should be
303    // externally visible.
304    if (FD->isInlineDefinitionExternallyVisible())
305      return External;
306
307    // C99 inline semantics, where the symbol is not externally visible.
308    return CodeGenModule::GVA_C99Inline;
309  }
310
311  // C++0x [temp.explicit]p9:
312  //   [ Note: The intent is that an inline function that is the subject of
313  //   an explicit instantiation declaration will still be implicitly
314  //   instantiated when used so that the body can be considered for
315  //   inlining, but that no out-of-line copy of the inline function would be
316  //   generated in the translation unit. -- end note ]
317  if (FD->getTemplateSpecializationKind()
318                                       == TSK_ExplicitInstantiationDeclaration)
319    return CodeGenModule::GVA_C99Inline;
320
321  return CodeGenModule::GVA_CXXInline;
322}
323
324llvm::GlobalValue::LinkageTypes
325CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
326  GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
327
328  if (Linkage == GVA_Internal) {
329    return llvm::Function::InternalLinkage;
330  } else if (D->hasAttr<DLLExportAttr>()) {
331    return llvm::Function::DLLExportLinkage;
332  } else if (D->hasAttr<WeakAttr>()) {
333    return llvm::Function::WeakAnyLinkage;
334  } else if (Linkage == GVA_C99Inline) {
335    // In C99 mode, 'inline' functions are guaranteed to have a strong
336    // definition somewhere else, so we can use available_externally linkage.
337    return llvm::Function::AvailableExternallyLinkage;
338  } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
339    // In C++, the compiler has to emit a definition in every translation unit
340    // that references the function.  We should use linkonce_odr because
341    // a) if all references in this translation unit are optimized away, we
342    // don't need to codegen it.  b) if the function persists, it needs to be
343    // merged with other definitions. c) C++ has the ODR, so we know the
344    // definition is dependable.
345    return llvm::Function::LinkOnceODRLinkage;
346  } else {
347    assert(Linkage == GVA_StrongExternal);
348    // Otherwise, we have strong external linkage.
349    return llvm::Function::ExternalLinkage;
350  }
351}
352
353
354/// SetFunctionDefinitionAttributes - Set attributes for a global.
355///
356/// FIXME: This is currently only done for aliases and functions, but not for
357/// variables (these details are set in EmitGlobalVarDefinition for variables).
358void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
359                                                    llvm::GlobalValue *GV) {
360  GV->setLinkage(getFunctionLinkage(D));
361  SetCommonAttributes(D, GV);
362}
363
364void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
365                                              const CGFunctionInfo &Info,
366                                              llvm::Function *F) {
367  unsigned CallingConv;
368  AttributeListType AttributeList;
369  ConstructAttributeList(Info, D, AttributeList, CallingConv);
370  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
371                                          AttributeList.size()));
372  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
373}
374
375void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
376                                                           llvm::Function *F) {
377  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
378    F->addFnAttr(llvm::Attribute::NoUnwind);
379
380  if (D->hasAttr<AlwaysInlineAttr>())
381    F->addFnAttr(llvm::Attribute::AlwaysInline);
382
383  if (D->hasAttr<NoInlineAttr>())
384    F->addFnAttr(llvm::Attribute::NoInline);
385
386  if (Features.getStackProtectorMode() == LangOptions::SSPOn)
387    F->addFnAttr(llvm::Attribute::StackProtect);
388  else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
389    F->addFnAttr(llvm::Attribute::StackProtectReq);
390
391  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
392    unsigned width = Context.Target.getCharWidth();
393    F->setAlignment(AA->getAlignment() / width);
394    while ((AA = AA->getNext<AlignedAttr>()))
395      F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
396  }
397  // C++ ABI requires 2-byte alignment for member functions.
398  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
399    F->setAlignment(2);
400}
401
402void CodeGenModule::SetCommonAttributes(const Decl *D,
403                                        llvm::GlobalValue *GV) {
404  setGlobalVisibility(GV, D);
405
406  if (D->hasAttr<UsedAttr>())
407    AddUsedGlobal(GV);
408
409  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
410    GV->setSection(SA->getName());
411
412  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
413}
414
415void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
416                                                  llvm::Function *F,
417                                                  const CGFunctionInfo &FI) {
418  SetLLVMFunctionAttributes(D, FI, F);
419  SetLLVMFunctionAttributesForDefinition(D, F);
420
421  F->setLinkage(llvm::Function::InternalLinkage);
422
423  SetCommonAttributes(D, F);
424}
425
426void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
427                                          llvm::Function *F,
428                                          bool IsIncompleteFunction) {
429  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
430
431  if (!IsIncompleteFunction)
432    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
433
434  // Only a few attributes are set on declarations; these may later be
435  // overridden by a definition.
436
437  if (FD->hasAttr<DLLImportAttr>()) {
438    F->setLinkage(llvm::Function::DLLImportLinkage);
439  } else if (FD->hasAttr<WeakAttr>() ||
440             FD->hasAttr<WeakImportAttr>()) {
441    // "extern_weak" is overloaded in LLVM; we probably should have
442    // separate linkage types for this.
443    F->setLinkage(llvm::Function::ExternalWeakLinkage);
444  } else {
445    F->setLinkage(llvm::Function::ExternalLinkage);
446  }
447
448  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
449    F->setSection(SA->getName());
450}
451
452void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
453  assert(!GV->isDeclaration() &&
454         "Only globals with definition can force usage.");
455  LLVMUsed.push_back(GV);
456}
457
458void CodeGenModule::EmitLLVMUsed() {
459  // Don't create llvm.used if there is no need.
460  if (LLVMUsed.empty())
461    return;
462
463  const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
464
465  // Convert LLVMUsed to what ConstantArray needs.
466  std::vector<llvm::Constant*> UsedArray;
467  UsedArray.resize(LLVMUsed.size());
468  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
469    UsedArray[i] =
470     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
471                                      i8PTy);
472  }
473
474  if (UsedArray.empty())
475    return;
476  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
477
478  llvm::GlobalVariable *GV =
479    new llvm::GlobalVariable(getModule(), ATy, false,
480                             llvm::GlobalValue::AppendingLinkage,
481                             llvm::ConstantArray::get(ATy, UsedArray),
482                             "llvm.used");
483
484  GV->setSection("llvm.metadata");
485}
486
487void CodeGenModule::EmitDeferred() {
488  // Emit code for any potentially referenced deferred decls.  Since a
489  // previously unused static decl may become used during the generation of code
490  // for a static function, iterate until no  changes are made.
491
492  while (!DeferredDeclsToEmit.empty() || !DeferredVtables.empty()) {
493    if (!DeferredVtables.empty()) {
494      const CXXRecordDecl *RD = DeferredVtables.back();
495      DeferredVtables.pop_back();
496      getVtableInfo().GenerateClassData(getVtableLinkage(RD), RD);
497      continue;
498    }
499
500    GlobalDecl D = DeferredDeclsToEmit.back();
501    DeferredDeclsToEmit.pop_back();
502
503    // The mangled name for the decl must have been emitted in GlobalDeclMap.
504    // Look it up to see if it was defined with a stronger definition (e.g. an
505    // extern inline function with a strong function redefinition).  If so,
506    // just ignore the deferred decl.
507    llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
508    assert(CGRef && "Deferred decl wasn't referenced?");
509
510    if (!CGRef->isDeclaration())
511      continue;
512
513    // Otherwise, emit the definition and move on to the next one.
514    EmitGlobalDefinition(D);
515  }
516}
517
518/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
519/// annotation information for a given GlobalValue.  The annotation struct is
520/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
521/// GlobalValue being annotated.  The second field is the constant string
522/// created from the AnnotateAttr's annotation.  The third field is a constant
523/// string containing the name of the translation unit.  The fourth field is
524/// the line number in the file of the annotated value declaration.
525///
526/// FIXME: this does not unique the annotation string constants, as llvm-gcc
527///        appears to.
528///
529llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
530                                                const AnnotateAttr *AA,
531                                                unsigned LineNo) {
532  llvm::Module *M = &getModule();
533
534  // get [N x i8] constants for the annotation string, and the filename string
535  // which are the 2nd and 3rd elements of the global annotation structure.
536  const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
537  llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
538                                                  AA->getAnnotation(), true);
539  llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
540                                                  M->getModuleIdentifier(),
541                                                  true);
542
543  // Get the two global values corresponding to the ConstantArrays we just
544  // created to hold the bytes of the strings.
545  llvm::GlobalValue *annoGV =
546    new llvm::GlobalVariable(*M, anno->getType(), false,
547                             llvm::GlobalValue::PrivateLinkage, anno,
548                             GV->getName());
549  // translation unit name string, emitted into the llvm.metadata section.
550  llvm::GlobalValue *unitGV =
551    new llvm::GlobalVariable(*M, unit->getType(), false,
552                             llvm::GlobalValue::PrivateLinkage, unit,
553                             ".str");
554
555  // Create the ConstantStruct for the global annotation.
556  llvm::Constant *Fields[4] = {
557    llvm::ConstantExpr::getBitCast(GV, SBP),
558    llvm::ConstantExpr::getBitCast(annoGV, SBP),
559    llvm::ConstantExpr::getBitCast(unitGV, SBP),
560    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
561  };
562  return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
563}
564
565bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
566  // Never defer when EmitAllDecls is specified or the decl has
567  // attribute used.
568  if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
569    return false;
570
571  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
572    // Constructors and destructors should never be deferred.
573    if (FD->hasAttr<ConstructorAttr>() ||
574        FD->hasAttr<DestructorAttr>())
575      return false;
576
577    // The key function for a class must never be deferred.
578    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
579      const CXXRecordDecl *RD = MD->getParent();
580      if (MD->isOutOfLine() && RD->isDynamicClass()) {
581        const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
582        if (KeyFunction &&
583            KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
584          return false;
585      }
586    }
587
588    GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
589
590    // static, static inline, always_inline, and extern inline functions can
591    // always be deferred.  Normal inline functions can be deferred in C99/C++.
592    if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
593        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
594      return true;
595    return false;
596  }
597
598  const VarDecl *VD = cast<VarDecl>(Global);
599  assert(VD->isFileVarDecl() && "Invalid decl");
600
601  // We never want to defer structs that have non-trivial constructors or
602  // destructors.
603
604  // FIXME: Handle references.
605  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
606    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
607      if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
608        return false;
609    }
610  }
611
612  // Static data may be deferred, but out-of-line static data members
613  // cannot be.
614  Linkage L = VD->getLinkage();
615  if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus &&
616      VD->getType()->getLinkage() == UniqueExternalLinkage)
617    L = UniqueExternalLinkage;
618
619  switch (L) {
620  case NoLinkage:
621  case InternalLinkage:
622  case UniqueExternalLinkage:
623    // Initializer has side effects?
624    if (VD->getInit() && VD->getInit()->HasSideEffects(Context))
625      return false;
626    return !(VD->isStaticDataMember() && VD->isOutOfLine());
627
628  case ExternalLinkage:
629    break;
630  }
631
632  return false;
633}
634
635llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
636  const AliasAttr *AA = VD->getAttr<AliasAttr>();
637  assert(AA && "No alias?");
638
639  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
640
641  // Unique the name through the identifier table.
642  const char *AliaseeName =
643    getContext().Idents.get(AA->getAliasee()).getNameStart();
644
645  // See if there is already something with the target's name in the module.
646  llvm::GlobalValue *Entry = GlobalDeclMap[AliaseeName];
647
648  llvm::Constant *Aliasee;
649  if (isa<llvm::FunctionType>(DeclTy))
650    Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
651  else
652    Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
653                                    llvm::PointerType::getUnqual(DeclTy), 0);
654  if (!Entry) {
655    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
656    F->setLinkage(llvm::Function::ExternalWeakLinkage);
657    WeakRefReferences.insert(F);
658  }
659
660  return Aliasee;
661}
662
663void CodeGenModule::EmitGlobal(GlobalDecl GD) {
664  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
665
666  // Weak references don't produce any output by themselves.
667  if (Global->hasAttr<WeakRefAttr>())
668    return;
669
670  // If this is an alias definition (which otherwise looks like a declaration)
671  // emit it now.
672  if (Global->hasAttr<AliasAttr>())
673    return EmitAliasDefinition(Global);
674
675  // Ignore declarations, they will be emitted on their first use.
676  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
677    // Forward declarations are emitted lazily on first use.
678    if (!FD->isThisDeclarationADefinition())
679      return;
680  } else {
681    const VarDecl *VD = cast<VarDecl>(Global);
682    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
683
684    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
685      return;
686  }
687
688  // Defer code generation when possible if this is a static definition, inline
689  // function etc.  These we only want to emit if they are used.
690  if (MayDeferGeneration(Global)) {
691    // If the value has already been used, add it directly to the
692    // DeferredDeclsToEmit list.
693    const char *MangledName = getMangledName(GD);
694    if (GlobalDeclMap.count(MangledName))
695      DeferredDeclsToEmit.push_back(GD);
696    else {
697      // Otherwise, remember that we saw a deferred decl with this name.  The
698      // first use of the mangled name will cause it to move into
699      // DeferredDeclsToEmit.
700      DeferredDecls[MangledName] = GD;
701    }
702    return;
703  }
704
705  // Otherwise emit the definition.
706  EmitGlobalDefinition(GD);
707}
708
709void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
710  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
711
712  PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(),
713                                 Context.getSourceManager(),
714                                 "Generating code for declaration");
715
716  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
717    getVtableInfo().MaybeEmitVtable(GD);
718    if (MD->isVirtual() && MD->isOutOfLine() &&
719        (!isa<CXXDestructorDecl>(D) || GD.getDtorType() != Dtor_Base)) {
720      if (isa<CXXDestructorDecl>(D)) {
721        GlobalDecl CanonGD(cast<CXXDestructorDecl>(D->getCanonicalDecl()),
722                           GD.getDtorType());
723        BuildThunksForVirtual(CanonGD);
724      } else {
725        BuildThunksForVirtual(MD->getCanonicalDecl());
726      }
727    }
728  }
729
730  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
731    EmitCXXConstructor(CD, GD.getCtorType());
732  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
733    EmitCXXDestructor(DD, GD.getDtorType());
734  else if (isa<FunctionDecl>(D))
735    EmitGlobalFunctionDefinition(GD);
736  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
737    EmitGlobalVarDefinition(VD);
738  else {
739    assert(0 && "Invalid argument to EmitGlobalDefinition()");
740  }
741}
742
743/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
744/// module, create and return an llvm Function with the specified type. If there
745/// is something in the module with the specified name, return it potentially
746/// bitcasted to the right type.
747///
748/// If D is non-null, it specifies a decl that correspond to this.  This is used
749/// to set the attributes on the function when it is first created.
750llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
751                                                       const llvm::Type *Ty,
752                                                       GlobalDecl D) {
753  // Lookup the entry, lazily creating it if necessary.
754  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
755  if (Entry) {
756    if (WeakRefReferences.count(Entry)) {
757      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
758      if (FD && !FD->hasAttr<WeakAttr>())
759	Entry->setLinkage(llvm::Function::ExternalLinkage);
760
761      WeakRefReferences.erase(Entry);
762    }
763
764    if (Entry->getType()->getElementType() == Ty)
765      return Entry;
766
767    // Make sure the result is of the correct type.
768    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
769    return llvm::ConstantExpr::getBitCast(Entry, PTy);
770  }
771
772  // This function doesn't have a complete type (for example, the return
773  // type is an incomplete struct). Use a fake type instead, and make
774  // sure not to try to set attributes.
775  bool IsIncompleteFunction = false;
776  if (!isa<llvm::FunctionType>(Ty)) {
777    Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
778                                 std::vector<const llvm::Type*>(), false);
779    IsIncompleteFunction = true;
780  }
781  llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
782                                             llvm::Function::ExternalLinkage,
783                                             "", &getModule());
784  F->setName(MangledName);
785  if (D.getDecl())
786    SetFunctionAttributes(D, F, IsIncompleteFunction);
787  Entry = F;
788
789  // This is the first use or definition of a mangled name.  If there is a
790  // deferred decl with this name, remember that we need to emit it at the end
791  // of the file.
792  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
793    DeferredDecls.find(MangledName);
794  if (DDI != DeferredDecls.end()) {
795    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
796    // list, and remove it from DeferredDecls (since we don't need it anymore).
797    DeferredDeclsToEmit.push_back(DDI->second);
798    DeferredDecls.erase(DDI);
799  } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
800    // If this the first reference to a C++ inline function in a class, queue up
801    // the deferred function body for emission.  These are not seen as
802    // top-level declarations.
803    if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
804      DeferredDeclsToEmit.push_back(D);
805    // A called constructor which has no definition or declaration need be
806    // synthesized.
807    else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
808      if (CD->isImplicit()) {
809        assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
810        DeferredDeclsToEmit.push_back(D);
811      }
812    } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
813      if (DD->isImplicit()) {
814        assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
815        DeferredDeclsToEmit.push_back(D);
816      }
817    } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
818      if (MD->isCopyAssignment() && MD->isImplicit()) {
819        assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
820        DeferredDeclsToEmit.push_back(D);
821      }
822    }
823  }
824
825  return F;
826}
827
828/// GetAddrOfFunction - Return the address of the given function.  If Ty is
829/// non-null, then this function will use the specified type if it has to
830/// create it (this occurs when we see a definition of the function).
831llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
832                                                 const llvm::Type *Ty) {
833  // If there was no specific requested type, just convert it now.
834  if (!Ty)
835    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
836  return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD);
837}
838
839/// CreateRuntimeFunction - Create a new runtime function with the specified
840/// type and name.
841llvm::Constant *
842CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
843                                     const char *Name) {
844  // Convert Name to be a uniqued string from the IdentifierInfo table.
845  Name = getContext().Idents.get(Name).getNameStart();
846  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
847}
848
849static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
850  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
851    return false;
852  if (Context.getLangOptions().CPlusPlus &&
853      Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
854    // FIXME: We should do something fancier here!
855    return false;
856  }
857  return true;
858}
859
860/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
861/// create and return an llvm GlobalVariable with the specified type.  If there
862/// is something in the module with the specified name, return it potentially
863/// bitcasted to the right type.
864///
865/// If D is non-null, it specifies a decl that correspond to this.  This is used
866/// to set the attributes on the global when it is first created.
867llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
868                                                     const llvm::PointerType*Ty,
869                                                     const VarDecl *D) {
870  // Lookup the entry, lazily creating it if necessary.
871  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
872  if (Entry) {
873    if (WeakRefReferences.count(Entry)) {
874      if (D && !D->hasAttr<WeakAttr>())
875	Entry->setLinkage(llvm::Function::ExternalLinkage);
876
877      WeakRefReferences.erase(Entry);
878    }
879
880    if (Entry->getType() == Ty)
881      return Entry;
882
883    // Make sure the result is of the correct type.
884    return llvm::ConstantExpr::getBitCast(Entry, Ty);
885  }
886
887  // This is the first use or definition of a mangled name.  If there is a
888  // deferred decl with this name, remember that we need to emit it at the end
889  // of the file.
890  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
891    DeferredDecls.find(MangledName);
892  if (DDI != DeferredDecls.end()) {
893    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
894    // list, and remove it from DeferredDecls (since we don't need it anymore).
895    DeferredDeclsToEmit.push_back(DDI->second);
896    DeferredDecls.erase(DDI);
897  }
898
899  llvm::GlobalVariable *GV =
900    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
901                             llvm::GlobalValue::ExternalLinkage,
902                             0, "", 0,
903                             false, Ty->getAddressSpace());
904  GV->setName(MangledName);
905
906  // Handle things which are present even on external declarations.
907  if (D) {
908    // FIXME: This code is overly simple and should be merged with other global
909    // handling.
910    GV->setConstant(DeclIsConstantGlobal(Context, D));
911
912    // FIXME: Merge with other attribute handling code.
913    if (D->getStorageClass() == VarDecl::PrivateExtern)
914      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
915
916    if (D->hasAttr<WeakAttr>() ||
917        D->hasAttr<WeakImportAttr>())
918      GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
919
920    GV->setThreadLocal(D->isThreadSpecified());
921  }
922
923  return Entry = GV;
924}
925
926
927/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
928/// given global variable.  If Ty is non-null and if the global doesn't exist,
929/// then it will be greated with the specified type instead of whatever the
930/// normal requested type would be.
931llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
932                                                  const llvm::Type *Ty) {
933  assert(D->hasGlobalStorage() && "Not a global variable");
934  QualType ASTTy = D->getType();
935  if (Ty == 0)
936    Ty = getTypes().ConvertTypeForMem(ASTTy);
937
938  const llvm::PointerType *PTy =
939    llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
940  return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
941}
942
943/// CreateRuntimeVariable - Create a new runtime global variable with the
944/// specified type and name.
945llvm::Constant *
946CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
947                                     const char *Name) {
948  // Convert Name to be a uniqued string from the IdentifierInfo table.
949  Name = getContext().Idents.get(Name).getNameStart();
950  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
951}
952
953void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
954  assert(!D->getInit() && "Cannot emit definite definitions here!");
955
956  if (MayDeferGeneration(D)) {
957    // If we have not seen a reference to this variable yet, place it
958    // into the deferred declarations table to be emitted if needed
959    // later.
960    const char *MangledName = getMangledName(D);
961    if (GlobalDeclMap.count(MangledName) == 0) {
962      DeferredDecls[MangledName] = D;
963      return;
964    }
965  }
966
967  // The tentative definition is the only definition.
968  EmitGlobalVarDefinition(D);
969}
970
971llvm::GlobalVariable::LinkageTypes
972CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) {
973  if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
974    return llvm::GlobalVariable::InternalLinkage;
975
976  if (const CXXMethodDecl *KeyFunction
977                                    = RD->getASTContext().getKeyFunction(RD)) {
978    // If this class has a key function, use that to determine the linkage of
979    // the vtable.
980    const FunctionDecl *Def = 0;
981    if (KeyFunction->getBody(Def))
982      KeyFunction = cast<CXXMethodDecl>(Def);
983
984    switch (KeyFunction->getTemplateSpecializationKind()) {
985      case TSK_Undeclared:
986      case TSK_ExplicitSpecialization:
987        if (KeyFunction->isInlined())
988          return llvm::GlobalVariable::WeakODRLinkage;
989
990        return llvm::GlobalVariable::ExternalLinkage;
991
992      case TSK_ImplicitInstantiation:
993      case TSK_ExplicitInstantiationDefinition:
994        return llvm::GlobalVariable::WeakODRLinkage;
995
996      case TSK_ExplicitInstantiationDeclaration:
997        // FIXME: Use available_externally linkage. However, this currently
998        // breaks LLVM's build due to undefined symbols.
999        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1000        return llvm::GlobalVariable::WeakODRLinkage;
1001    }
1002  }
1003
1004  switch (RD->getTemplateSpecializationKind()) {
1005  case TSK_Undeclared:
1006  case TSK_ExplicitSpecialization:
1007  case TSK_ImplicitInstantiation:
1008  case TSK_ExplicitInstantiationDefinition:
1009    return llvm::GlobalVariable::WeakODRLinkage;
1010
1011  case TSK_ExplicitInstantiationDeclaration:
1012    // FIXME: Use available_externally linkage. However, this currently
1013    // breaks LLVM's build due to undefined symbols.
1014    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1015    return llvm::GlobalVariable::WeakODRLinkage;
1016  }
1017
1018  // Silence GCC warning.
1019  return llvm::GlobalVariable::WeakODRLinkage;
1020}
1021
1022static CodeGenModule::GVALinkage
1023GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
1024  // If this is a static data member, compute the kind of template
1025  // specialization. Otherwise, this variable is not part of a
1026  // template.
1027  TemplateSpecializationKind TSK = TSK_Undeclared;
1028  if (VD->isStaticDataMember())
1029    TSK = VD->getTemplateSpecializationKind();
1030
1031  Linkage L = VD->getLinkage();
1032  if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
1033      VD->getType()->getLinkage() == UniqueExternalLinkage)
1034    L = UniqueExternalLinkage;
1035
1036  switch (L) {
1037  case NoLinkage:
1038  case InternalLinkage:
1039  case UniqueExternalLinkage:
1040    return CodeGenModule::GVA_Internal;
1041
1042  case ExternalLinkage:
1043    switch (TSK) {
1044    case TSK_Undeclared:
1045    case TSK_ExplicitSpecialization:
1046
1047      // FIXME: ExplicitInstantiationDefinition should be weak!
1048    case TSK_ExplicitInstantiationDefinition:
1049      return CodeGenModule::GVA_StrongExternal;
1050
1051    case TSK_ExplicitInstantiationDeclaration:
1052      llvm_unreachable("Variable should not be instantiated");
1053      // Fall through to treat this like any other instantiation.
1054
1055    case TSK_ImplicitInstantiation:
1056      return CodeGenModule::GVA_TemplateInstantiation;
1057    }
1058  }
1059
1060  return CodeGenModule::GVA_StrongExternal;
1061}
1062
1063CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1064    return CharUnits::fromQuantity(
1065      TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1066}
1067
1068void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1069  llvm::Constant *Init = 0;
1070  QualType ASTTy = D->getType();
1071  bool NonConstInit = false;
1072
1073  const Expr *InitExpr = D->getAnyInitializer();
1074
1075  if (!InitExpr) {
1076    // This is a tentative definition; tentative definitions are
1077    // implicitly initialized with { 0 }.
1078    //
1079    // Note that tentative definitions are only emitted at the end of
1080    // a translation unit, so they should never have incomplete
1081    // type. In addition, EmitTentativeDefinition makes sure that we
1082    // never attempt to emit a tentative definition if a real one
1083    // exists. A use may still exists, however, so we still may need
1084    // to do a RAUW.
1085    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1086    Init = EmitNullConstant(D->getType());
1087  } else {
1088    Init = EmitConstantExpr(InitExpr, D->getType());
1089
1090    if (!Init) {
1091      QualType T = InitExpr->getType();
1092      if (getLangOptions().CPlusPlus) {
1093        EmitCXXGlobalVarDeclInitFunc(D);
1094        Init = EmitNullConstant(T);
1095        NonConstInit = true;
1096      } else {
1097        ErrorUnsupported(D, "static initializer");
1098        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1099      }
1100    }
1101  }
1102
1103  const llvm::Type* InitType = Init->getType();
1104  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1105
1106  // Strip off a bitcast if we got one back.
1107  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1108    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1109           // all zero index gep.
1110           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1111    Entry = CE->getOperand(0);
1112  }
1113
1114  // Entry is now either a Function or GlobalVariable.
1115  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1116
1117  // We have a definition after a declaration with the wrong type.
1118  // We must make a new GlobalVariable* and update everything that used OldGV
1119  // (a declaration or tentative definition) with the new GlobalVariable*
1120  // (which will be a definition).
1121  //
1122  // This happens if there is a prototype for a global (e.g.
1123  // "extern int x[];") and then a definition of a different type (e.g.
1124  // "int x[10];"). This also happens when an initializer has a different type
1125  // from the type of the global (this happens with unions).
1126  if (GV == 0 ||
1127      GV->getType()->getElementType() != InitType ||
1128      GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1129
1130    // Remove the old entry from GlobalDeclMap so that we'll create a new one.
1131    GlobalDeclMap.erase(getMangledName(D));
1132
1133    // Make a new global with the correct type, this is now guaranteed to work.
1134    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1135    GV->takeName(cast<llvm::GlobalValue>(Entry));
1136
1137    // Replace all uses of the old global with the new global
1138    llvm::Constant *NewPtrForOldDecl =
1139        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1140    Entry->replaceAllUsesWith(NewPtrForOldDecl);
1141
1142    // Erase the old global, since it is no longer used.
1143    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1144  }
1145
1146  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1147    SourceManager &SM = Context.getSourceManager();
1148    AddAnnotation(EmitAnnotateAttr(GV, AA,
1149                              SM.getInstantiationLineNumber(D->getLocation())));
1150  }
1151
1152  GV->setInitializer(Init);
1153
1154  // If it is safe to mark the global 'constant', do so now.
1155  GV->setConstant(false);
1156  if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1157    GV->setConstant(true);
1158
1159  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1160
1161  // Set the llvm linkage type as appropriate.
1162  GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1163  if (Linkage == GVA_Internal)
1164    GV->setLinkage(llvm::Function::InternalLinkage);
1165  else if (D->hasAttr<DLLImportAttr>())
1166    GV->setLinkage(llvm::Function::DLLImportLinkage);
1167  else if (D->hasAttr<DLLExportAttr>())
1168    GV->setLinkage(llvm::Function::DLLExportLinkage);
1169  else if (D->hasAttr<WeakAttr>()) {
1170    if (GV->isConstant())
1171      GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1172    else
1173      GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1174  } else if (Linkage == GVA_TemplateInstantiation)
1175    GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1176  else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
1177           !D->hasExternalStorage() && !D->getInit() &&
1178           !D->getAttr<SectionAttr>()) {
1179    GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1180    // common vars aren't constant even if declared const.
1181    GV->setConstant(false);
1182  } else
1183    GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1184
1185  SetCommonAttributes(D, GV);
1186
1187  // Emit global variable debug information.
1188  if (CGDebugInfo *DI = getDebugInfo()) {
1189    DI->setLocation(D->getLocation());
1190    DI->EmitGlobalVariable(GV, D);
1191  }
1192}
1193
1194/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1195/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1196/// existing call uses of the old function in the module, this adjusts them to
1197/// call the new function directly.
1198///
1199/// This is not just a cleanup: the always_inline pass requires direct calls to
1200/// functions to be able to inline them.  If there is a bitcast in the way, it
1201/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1202/// run at -O0.
1203static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1204                                                      llvm::Function *NewFn) {
1205  // If we're redefining a global as a function, don't transform it.
1206  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1207  if (OldFn == 0) return;
1208
1209  const llvm::Type *NewRetTy = NewFn->getReturnType();
1210  llvm::SmallVector<llvm::Value*, 4> ArgList;
1211
1212  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1213       UI != E; ) {
1214    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1215    unsigned OpNo = UI.getOperandNo();
1216    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
1217    if (!CI || OpNo != 0) continue;
1218
1219    // If the return types don't match exactly, and if the call isn't dead, then
1220    // we can't transform this call.
1221    if (CI->getType() != NewRetTy && !CI->use_empty())
1222      continue;
1223
1224    // If the function was passed too few arguments, don't transform.  If extra
1225    // arguments were passed, we silently drop them.  If any of the types
1226    // mismatch, we don't transform.
1227    unsigned ArgNo = 0;
1228    bool DontTransform = false;
1229    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1230         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1231      if (CI->getNumOperands()-1 == ArgNo ||
1232          CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
1233        DontTransform = true;
1234        break;
1235      }
1236    }
1237    if (DontTransform)
1238      continue;
1239
1240    // Okay, we can transform this.  Create the new call instruction and copy
1241    // over the required information.
1242    ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
1243    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1244                                                     ArgList.end(), "", CI);
1245    ArgList.clear();
1246    if (!NewCall->getType()->isVoidTy())
1247      NewCall->takeName(CI);
1248    NewCall->setAttributes(CI->getAttributes());
1249    NewCall->setCallingConv(CI->getCallingConv());
1250
1251    // Finally, remove the old call, replacing any uses with the new one.
1252    if (!CI->use_empty())
1253      CI->replaceAllUsesWith(NewCall);
1254
1255    // Copy any custom metadata attached with CI.
1256    if (llvm::MDNode *DbgNode = CI->getMetadata("dbg"))
1257      NewCall->setMetadata("dbg", DbgNode);
1258    CI->eraseFromParent();
1259  }
1260}
1261
1262
1263void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1264  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1265  const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1266  getMangleContext().mangleInitDiscriminator();
1267  // Get or create the prototype for the function.
1268  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1269
1270  // Strip off a bitcast if we got one back.
1271  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1272    assert(CE->getOpcode() == llvm::Instruction::BitCast);
1273    Entry = CE->getOperand(0);
1274  }
1275
1276
1277  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1278    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1279
1280    // If the types mismatch then we have to rewrite the definition.
1281    assert(OldFn->isDeclaration() &&
1282           "Shouldn't replace non-declaration");
1283
1284    // F is the Function* for the one with the wrong type, we must make a new
1285    // Function* and update everything that used F (a declaration) with the new
1286    // Function* (which will be a definition).
1287    //
1288    // This happens if there is a prototype for a function
1289    // (e.g. "int f()") and then a definition of a different type
1290    // (e.g. "int f(int x)").  Start by making a new function of the
1291    // correct type, RAUW, then steal the name.
1292    GlobalDeclMap.erase(getMangledName(D));
1293    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1294    NewFn->takeName(OldFn);
1295
1296    // If this is an implementation of a function without a prototype, try to
1297    // replace any existing uses of the function (which may be calls) with uses
1298    // of the new function
1299    if (D->getType()->isFunctionNoProtoType()) {
1300      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1301      OldFn->removeDeadConstantUsers();
1302    }
1303
1304    // Replace uses of F with the Function we will endow with a body.
1305    if (!Entry->use_empty()) {
1306      llvm::Constant *NewPtrForOldDecl =
1307        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1308      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1309    }
1310
1311    // Ok, delete the old function now, which is dead.
1312    OldFn->eraseFromParent();
1313
1314    Entry = NewFn;
1315  }
1316
1317  llvm::Function *Fn = cast<llvm::Function>(Entry);
1318
1319  CodeGenFunction(*this).GenerateCode(D, Fn);
1320
1321  SetFunctionDefinitionAttributes(D, Fn);
1322  SetLLVMFunctionAttributesForDefinition(D, Fn);
1323
1324  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1325    AddGlobalCtor(Fn, CA->getPriority());
1326  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1327    AddGlobalDtor(Fn, DA->getPriority());
1328}
1329
1330void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
1331  const AliasAttr *AA = D->getAttr<AliasAttr>();
1332  assert(AA && "Not an alias?");
1333
1334  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1335
1336  // Unique the name through the identifier table.
1337  const char *AliaseeName =
1338    getContext().Idents.get(AA->getAliasee()).getNameStart();
1339
1340  // Create a reference to the named value.  This ensures that it is emitted
1341  // if a deferred decl.
1342  llvm::Constant *Aliasee;
1343  if (isa<llvm::FunctionType>(DeclTy))
1344    Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
1345  else
1346    Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1347                                    llvm::PointerType::getUnqual(DeclTy), 0);
1348
1349  // Create the new alias itself, but don't set a name yet.
1350  llvm::GlobalValue *GA =
1351    new llvm::GlobalAlias(Aliasee->getType(),
1352                          llvm::Function::ExternalLinkage,
1353                          "", Aliasee, &getModule());
1354
1355  // See if there is already something with the alias' name in the module.
1356  const char *MangledName = getMangledName(D);
1357  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1358
1359  if (Entry && !Entry->isDeclaration()) {
1360    // If there is a definition in the module, then it wins over the alias.
1361    // This is dubious, but allow it to be safe.  Just ignore the alias.
1362    GA->eraseFromParent();
1363    return;
1364  }
1365
1366  if (Entry) {
1367    // If there is a declaration in the module, then we had an extern followed
1368    // by the alias, as in:
1369    //   extern int test6();
1370    //   ...
1371    //   int test6() __attribute__((alias("test7")));
1372    //
1373    // Remove it and replace uses of it with the alias.
1374
1375    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1376                                                          Entry->getType()));
1377    Entry->eraseFromParent();
1378  }
1379
1380  // Now we know that there is no conflict, set the name.
1381  Entry = GA;
1382  GA->setName(MangledName);
1383
1384  // Set attributes which are particular to an alias; this is a
1385  // specialization of the attributes which may be set on a global
1386  // variable/function.
1387  if (D->hasAttr<DLLExportAttr>()) {
1388    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1389      // The dllexport attribute is ignored for undefined symbols.
1390      if (FD->getBody())
1391        GA->setLinkage(llvm::Function::DLLExportLinkage);
1392    } else {
1393      GA->setLinkage(llvm::Function::DLLExportLinkage);
1394    }
1395  } else if (D->hasAttr<WeakAttr>() ||
1396             D->hasAttr<WeakRefAttr>() ||
1397             D->hasAttr<WeakImportAttr>()) {
1398    GA->setLinkage(llvm::Function::WeakAnyLinkage);
1399  }
1400
1401  SetCommonAttributes(D, GA);
1402}
1403
1404/// getBuiltinLibFunction - Given a builtin id for a function like
1405/// "__builtin_fabsf", return a Function* for "fabsf".
1406llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1407                                                  unsigned BuiltinID) {
1408  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1409          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1410         "isn't a lib fn");
1411
1412  // Get the name, skip over the __builtin_ prefix (if necessary).
1413  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1414  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1415    Name += 10;
1416
1417  const llvm::FunctionType *Ty =
1418    cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1419
1420  // Unique the name through the identifier table.
1421  Name = getContext().Idents.get(Name).getNameStart();
1422  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1423}
1424
1425llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1426                                            unsigned NumTys) {
1427  return llvm::Intrinsic::getDeclaration(&getModule(),
1428                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
1429}
1430
1431llvm::Function *CodeGenModule::getMemCpyFn() {
1432  if (MemCpyFn) return MemCpyFn;
1433  const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1434  return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
1435}
1436
1437llvm::Function *CodeGenModule::getMemMoveFn() {
1438  if (MemMoveFn) return MemMoveFn;
1439  const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1440  return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
1441}
1442
1443llvm::Function *CodeGenModule::getMemSetFn() {
1444  if (MemSetFn) return MemSetFn;
1445  const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1446  return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
1447}
1448
1449static llvm::StringMapEntry<llvm::Constant*> &
1450GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1451                         const StringLiteral *Literal,
1452                         bool TargetIsLSB,
1453                         bool &IsUTF16,
1454                         unsigned &StringLength) {
1455  unsigned NumBytes = Literal->getByteLength();
1456
1457  // Check for simple case.
1458  if (!Literal->containsNonAsciiOrNull()) {
1459    StringLength = NumBytes;
1460    return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1461                                                StringLength));
1462  }
1463
1464  // Otherwise, convert the UTF8 literals into a byte string.
1465  llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1466  const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1467  UTF16 *ToPtr = &ToBuf[0];
1468
1469  ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1470                                               &ToPtr, ToPtr + NumBytes,
1471                                               strictConversion);
1472
1473  // Check for conversion failure.
1474  if (Result != conversionOK) {
1475    // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1476    // this duplicate code.
1477    assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1478    StringLength = NumBytes;
1479    return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1480                                                StringLength));
1481  }
1482
1483  // ConvertUTF8toUTF16 returns the length in ToPtr.
1484  StringLength = ToPtr - &ToBuf[0];
1485
1486  // Render the UTF-16 string into a byte array and convert to the target byte
1487  // order.
1488  //
1489  // FIXME: This isn't something we should need to do here.
1490  llvm::SmallString<128> AsBytes;
1491  AsBytes.reserve(StringLength * 2);
1492  for (unsigned i = 0; i != StringLength; ++i) {
1493    unsigned short Val = ToBuf[i];
1494    if (TargetIsLSB) {
1495      AsBytes.push_back(Val & 0xFF);
1496      AsBytes.push_back(Val >> 8);
1497    } else {
1498      AsBytes.push_back(Val >> 8);
1499      AsBytes.push_back(Val & 0xFF);
1500    }
1501  }
1502  // Append one extra null character, the second is automatically added by our
1503  // caller.
1504  AsBytes.push_back(0);
1505
1506  IsUTF16 = true;
1507  return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1508}
1509
1510llvm::Constant *
1511CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1512  unsigned StringLength = 0;
1513  bool isUTF16 = false;
1514  llvm::StringMapEntry<llvm::Constant*> &Entry =
1515    GetConstantCFStringEntry(CFConstantStringMap, Literal,
1516                             getTargetData().isLittleEndian(),
1517                             isUTF16, StringLength);
1518
1519  if (llvm::Constant *C = Entry.getValue())
1520    return C;
1521
1522  llvm::Constant *Zero =
1523      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1524  llvm::Constant *Zeros[] = { Zero, Zero };
1525
1526  // If we don't already have it, get __CFConstantStringClassReference.
1527  if (!CFConstantStringClassRef) {
1528    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1529    Ty = llvm::ArrayType::get(Ty, 0);
1530    llvm::Constant *GV = CreateRuntimeVariable(Ty,
1531                                           "__CFConstantStringClassReference");
1532    // Decay array -> ptr
1533    CFConstantStringClassRef =
1534      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1535  }
1536
1537  QualType CFTy = getContext().getCFConstantStringType();
1538
1539  const llvm::StructType *STy =
1540    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1541
1542  std::vector<llvm::Constant*> Fields(4);
1543
1544  // Class pointer.
1545  Fields[0] = CFConstantStringClassRef;
1546
1547  // Flags.
1548  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1549  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1550    llvm::ConstantInt::get(Ty, 0x07C8);
1551
1552  // String pointer.
1553  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1554
1555  llvm::GlobalValue::LinkageTypes Linkage;
1556  bool isConstant;
1557  if (isUTF16) {
1558    // FIXME: why do utf strings get "_" labels instead of "L" labels?
1559    Linkage = llvm::GlobalValue::InternalLinkage;
1560    // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1561    // does make plain ascii ones writable.
1562    isConstant = true;
1563  } else {
1564    Linkage = llvm::GlobalValue::PrivateLinkage;
1565    isConstant = !Features.WritableStrings;
1566  }
1567
1568  llvm::GlobalVariable *GV =
1569    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1570                             ".str");
1571  if (isUTF16) {
1572    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1573    GV->setAlignment(Align.getQuantity());
1574  }
1575  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1576
1577  // String length.
1578  Ty = getTypes().ConvertType(getContext().LongTy);
1579  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1580
1581  // The struct.
1582  C = llvm::ConstantStruct::get(STy, Fields);
1583  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1584                                llvm::GlobalVariable::PrivateLinkage, C,
1585                                "_unnamed_cfstring_");
1586  if (const char *Sect = getContext().Target.getCFStringSection())
1587    GV->setSection(Sect);
1588  Entry.setValue(GV);
1589
1590  return GV;
1591}
1592
1593/// GetStringForStringLiteral - Return the appropriate bytes for a
1594/// string literal, properly padded to match the literal type.
1595std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1596  const char *StrData = E->getStrData();
1597  unsigned Len = E->getByteLength();
1598
1599  const ConstantArrayType *CAT =
1600    getContext().getAsConstantArrayType(E->getType());
1601  assert(CAT && "String isn't pointer or array!");
1602
1603  // Resize the string to the right size.
1604  std::string Str(StrData, StrData+Len);
1605  uint64_t RealLen = CAT->getSize().getZExtValue();
1606
1607  if (E->isWide())
1608    RealLen *= getContext().Target.getWCharWidth()/8;
1609
1610  Str.resize(RealLen, '\0');
1611
1612  return Str;
1613}
1614
1615/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1616/// constant array for the given string literal.
1617llvm::Constant *
1618CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1619  // FIXME: This can be more efficient.
1620  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1621  llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1622  if (S->isWide()) {
1623    llvm::Type *DestTy =
1624        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1625    C = llvm::ConstantExpr::getBitCast(C, DestTy);
1626  }
1627  return C;
1628}
1629
1630/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1631/// array for the given ObjCEncodeExpr node.
1632llvm::Constant *
1633CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1634  std::string Str;
1635  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1636
1637  return GetAddrOfConstantCString(Str);
1638}
1639
1640
1641/// GenerateWritableString -- Creates storage for a string literal.
1642static llvm::Constant *GenerateStringLiteral(const std::string &str,
1643                                             bool constant,
1644                                             CodeGenModule &CGM,
1645                                             const char *GlobalName) {
1646  // Create Constant for this string literal. Don't add a '\0'.
1647  llvm::Constant *C =
1648      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1649
1650  // Create a global variable for this string
1651  return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1652                                  llvm::GlobalValue::PrivateLinkage,
1653                                  C, GlobalName);
1654}
1655
1656/// GetAddrOfConstantString - Returns a pointer to a character array
1657/// containing the literal. This contents are exactly that of the
1658/// given string, i.e. it will not be null terminated automatically;
1659/// see GetAddrOfConstantCString. Note that whether the result is
1660/// actually a pointer to an LLVM constant depends on
1661/// Feature.WriteableStrings.
1662///
1663/// The result has pointer to array type.
1664llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1665                                                       const char *GlobalName) {
1666  bool IsConstant = !Features.WritableStrings;
1667
1668  // Get the default prefix if a name wasn't specified.
1669  if (!GlobalName)
1670    GlobalName = ".str";
1671
1672  // Don't share any string literals if strings aren't constant.
1673  if (!IsConstant)
1674    return GenerateStringLiteral(str, false, *this, GlobalName);
1675
1676  llvm::StringMapEntry<llvm::Constant *> &Entry =
1677    ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1678
1679  if (Entry.getValue())
1680    return Entry.getValue();
1681
1682  // Create a global variable for this.
1683  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1684  Entry.setValue(C);
1685  return C;
1686}
1687
1688/// GetAddrOfConstantCString - Returns a pointer to a character
1689/// array containing the literal and a terminating '\-'
1690/// character. The result has pointer to array type.
1691llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1692                                                        const char *GlobalName){
1693  return GetAddrOfConstantString(str + '\0', GlobalName);
1694}
1695
1696/// EmitObjCPropertyImplementations - Emit information for synthesized
1697/// properties for an implementation.
1698void CodeGenModule::EmitObjCPropertyImplementations(const
1699                                                    ObjCImplementationDecl *D) {
1700  for (ObjCImplementationDecl::propimpl_iterator
1701         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1702    ObjCPropertyImplDecl *PID = *i;
1703
1704    // Dynamic is just for type-checking.
1705    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1706      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1707
1708      // Determine which methods need to be implemented, some may have
1709      // been overridden. Note that ::isSynthesized is not the method
1710      // we want, that just indicates if the decl came from a
1711      // property. What we want to know is if the method is defined in
1712      // this implementation.
1713      if (!D->getInstanceMethod(PD->getGetterName()))
1714        CodeGenFunction(*this).GenerateObjCGetter(
1715                                 const_cast<ObjCImplementationDecl *>(D), PID);
1716      if (!PD->isReadOnly() &&
1717          !D->getInstanceMethod(PD->getSetterName()))
1718        CodeGenFunction(*this).GenerateObjCSetter(
1719                                 const_cast<ObjCImplementationDecl *>(D), PID);
1720    }
1721  }
1722}
1723
1724/// EmitNamespace - Emit all declarations in a namespace.
1725void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1726  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1727       I != E; ++I)
1728    EmitTopLevelDecl(*I);
1729}
1730
1731// EmitLinkageSpec - Emit all declarations in a linkage spec.
1732void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1733  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1734      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1735    ErrorUnsupported(LSD, "linkage spec");
1736    return;
1737  }
1738
1739  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1740       I != E; ++I)
1741    EmitTopLevelDecl(*I);
1742}
1743
1744/// EmitTopLevelDecl - Emit code for a single top level declaration.
1745void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1746  // If an error has occurred, stop code generation, but continue
1747  // parsing and semantic analysis (to ensure all warnings and errors
1748  // are emitted).
1749  if (Diags.hasErrorOccurred())
1750    return;
1751
1752  // Ignore dependent declarations.
1753  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1754    return;
1755
1756  switch (D->getKind()) {
1757  case Decl::CXXConversion:
1758  case Decl::CXXMethod:
1759  case Decl::Function:
1760    // Skip function templates
1761    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1762      return;
1763
1764    EmitGlobal(cast<FunctionDecl>(D));
1765    break;
1766
1767  case Decl::Var:
1768    EmitGlobal(cast<VarDecl>(D));
1769    break;
1770
1771  // C++ Decls
1772  case Decl::Namespace:
1773    EmitNamespace(cast<NamespaceDecl>(D));
1774    break;
1775    // No code generation needed.
1776  case Decl::UsingShadow:
1777  case Decl::Using:
1778  case Decl::UsingDirective:
1779  case Decl::ClassTemplate:
1780  case Decl::FunctionTemplate:
1781  case Decl::NamespaceAlias:
1782    break;
1783  case Decl::CXXConstructor:
1784    // Skip function templates
1785    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1786      return;
1787
1788    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1789    break;
1790  case Decl::CXXDestructor:
1791    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1792    break;
1793
1794  case Decl::StaticAssert:
1795    // Nothing to do.
1796    break;
1797
1798  // Objective-C Decls
1799
1800  // Forward declarations, no (immediate) code generation.
1801  case Decl::ObjCClass:
1802  case Decl::ObjCForwardProtocol:
1803  case Decl::ObjCCategory:
1804  case Decl::ObjCInterface:
1805    break;
1806
1807  case Decl::ObjCProtocol:
1808    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1809    break;
1810
1811  case Decl::ObjCCategoryImpl:
1812    // Categories have properties but don't support synthesize so we
1813    // can ignore them here.
1814    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1815    break;
1816
1817  case Decl::ObjCImplementation: {
1818    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1819    EmitObjCPropertyImplementations(OMD);
1820    Runtime->GenerateClass(OMD);
1821    break;
1822  }
1823  case Decl::ObjCMethod: {
1824    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1825    // If this is not a prototype, emit the body.
1826    if (OMD->getBody())
1827      CodeGenFunction(*this).GenerateObjCMethod(OMD);
1828    break;
1829  }
1830  case Decl::ObjCCompatibleAlias:
1831    // compatibility-alias is a directive and has no code gen.
1832    break;
1833
1834  case Decl::LinkageSpec:
1835    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1836    break;
1837
1838  case Decl::FileScopeAsm: {
1839    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1840    llvm::StringRef AsmString = AD->getAsmString()->getString();
1841
1842    const std::string &S = getModule().getModuleInlineAsm();
1843    if (S.empty())
1844      getModule().setModuleInlineAsm(AsmString);
1845    else
1846      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
1847    break;
1848  }
1849
1850  default:
1851    // Make sure we handled everything we should, every other kind is a
1852    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1853    // function. Need to recode Decl::Kind to do that easily.
1854    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1855  }
1856}
1857