CodeGenModule.cpp revision b4880bab7fc1b61267cfd9a0ad52188e7a828cb3
15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// This coordinates the per-module state used while generating code.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenModule.h"
15bd3606426d389370616126af969904ec493cb105Chris Lattner#include "CGDebugInfo.h"
165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenFunction.h"
170dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar#include "CGCall.h"
18af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGObjCRuntime.h"
195f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor#include "Mangle.h"
20bd3606426d389370616126af969904ec493cb105Chris Lattner#include "clang/Frontend/CompileOptions.h"
215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
22c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2321ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
242c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/Basic/Diagnostic.h"
258bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
265f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
27e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff#include "clang/Basic/ConvertUTF.h"
28ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman#include "llvm/CallingConv.h"
29bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner#include "llvm/Module.h"
305f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Intrinsics.h"
3120ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov#include "llvm/Target/TargetData.h"
325f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
335f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
345f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
355f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
36bd3606426d389370616126af969904ec493cb105Chris LattnerCodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
37fb97b03e42d397405f617be0252be83e77a66f6eChris Lattner                             llvm::Module &M, const llvm::TargetData &TD,
38bd3606426d389370616126af969904ec493cb105Chris Lattner                             Diagnostic &diags)
39bd3606426d389370616126af969904ec493cb105Chris Lattner  : BlockModule(C, M, TD, Types, *this), Context(C),
40bd3606426d389370616126af969904ec493cb105Chris Lattner    Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
412a998148a6823c44d67da347c95eb2ea21f6b986Mike Stump    TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
422a998148a6823c44d67da347c95eb2ea21f6b986Mike Stump    MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
43208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar
443c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  if (!Features.ObjC1)
453c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = 0;
463c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  else if (!Features.NeXTRuntime)
473c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = CreateGNUObjCRuntime(*this);
483c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  else if (Features.ObjCNonFragileABI)
493c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
503c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  else
513c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = CreateMacObjCRuntime(*this);
52e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
53e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta  // If debug info generation is enabled, create the CGDebugInfo object.
54bd3606426d389370616126af969904ec493cb105Chris Lattner  DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
552b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
562b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
572b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
58815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete Runtime;
59815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
60815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
61815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
62815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
6382227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
64208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar  if (Runtime)
65208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
66208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
676bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
686bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
69532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  EmitAnnotations();
700269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
71f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
72f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
73488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
742c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
7590df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
7690df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
7790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
7890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
79488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
8056b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
812c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
820a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
830a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
842c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
8558c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
86488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
87c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
8890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
8990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
9090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
9190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
92488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
9356b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
94c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
950a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
96c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
97c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
9804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel DunbarLangOptions::VisibilityMode
9904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel DunbarCodeGenModule::getDeclVisibilityMode(const Decl *D) const {
10004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10104d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    if (VD->getStorageClass() == VarDecl::PrivateExtern)
10204d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar      return LangOptions::Hidden;
10304d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
10404d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
10504d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    switch (attr->getVisibility()) {
10604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    default: assert(0 && "Unknown visibility!");
10704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    case VisibilityAttr::DefaultVisibility:
10804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar      return LangOptions::Default;
10904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    case VisibilityAttr::HiddenVisibility:
11004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar      return LangOptions::Hidden;
11104d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    case VisibilityAttr::ProtectedVisibility:
11204d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar      return LangOptions::Protected;
11304d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    }
1147e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
1156ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
11604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  return getLangOptions().getVisibilityMode();
1174f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman}
1184f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman
11904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbarvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
12004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar                                        const Decl *D) const {
12104d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
122df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
1237e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1246ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
1257e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
1266ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
12704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  switch (getDeclVisibilityMode(D)) {
1287cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian  default: assert(0 && "Unknown visibility!");
12904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  case LangOptions::Default:
13004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
13104d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  case LangOptions::Hidden:
13204d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
13304d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  case LangOptions::Protected:
13404d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1357cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian  }
1367cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
1377cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
1382a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlssonconst char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
1392a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  const NamedDecl *ND = GD.getDecl();
1402a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
1412a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
1422a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    return getMangledCXXCtorName(D, GD.getCtorType());
1432a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
1442a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    return getMangledCXXDtorName(D, GD.getDtorType());
1452a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
1462a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  return getMangledName(ND);
1472a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson}
1482a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
1495f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// \brief Retrieves the mangled name for the given declaration.
1505f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor///
1515f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// If the given declaration requires a mangled name, returns an
152c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner/// const char* containing the mangled name.  Otherwise, returns
153c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner/// the unmangled name.
1545f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor///
1556ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregorconst char *CodeGenModule::getMangledName(const NamedDecl *ND) {
156c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  // In C, functions with no attributes never need to be mangled. Fastpath them.
157c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
158c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
1593c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    return ND->getNameAsCString();
160c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  }
161c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner
1626ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  llvm::SmallString<256> Name;
1636ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  llvm::raw_svector_ostream Out(Name);
164fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar  if (!mangleName(ND, Context, Out)) {
165fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
1663c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    return ND->getNameAsCString();
167fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar  }
1685f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
1696ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  Name += '\0';
17095d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  return UniqueMangledName(Name.begin(), Name.end());
17195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson}
17295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson
17395d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlssonconst char *CodeGenModule::UniqueMangledName(const char *NameStart,
17495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson                                             const char *NameEnd) {
17595d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
17695d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson
17795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
1785f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
1795f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
1806d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
1816d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
1826bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
18349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
1846bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
1856d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
1866d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
1876bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
1886bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
1896bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
19049988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
1916bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
1926bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
1936bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
1946bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
1956bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
1966bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  llvm::FunctionType* CtorFTy =
1976bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    llvm::FunctionType::get(llvm::Type::VoidTy,
1986bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                            std::vector<const llvm::Type*>(),
1996bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                            false);
2006bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
2016bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2026bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
203572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner  llvm::StructType* CtorStructTy =
2046bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    llvm::StructType::get(llvm::Type::Int32Ty,
2056bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                          llvm::PointerType::getUnqual(CtorFTy), NULL);
2066bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2076bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
2086bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  std::vector<llvm::Constant*> Ctors;
2096bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
2106bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    std::vector<llvm::Constant*> S;
2116bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
2126bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
2136bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
2146bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
2156bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2166bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
2176bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
2186bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    new llvm::GlobalVariable(AT, false,
219572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
2206bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                             llvm::ConstantArray::get(AT, Ctors),
2216bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                             GlobalName,
222572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             &TheModule);
2236d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
2246d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
2256d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
226532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begemanvoid CodeGenModule::EmitAnnotations() {
227532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  if (Annotations.empty())
228532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman    return;
229532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
230532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  // Create a new global variable for the ConstantStruct in the Module.
231532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::Constant *Array =
232532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
233532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                                                Annotations.size()),
234532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           Annotations);
235532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::GlobalValue *gv =
236532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  new llvm::GlobalVariable(Array->getType(), false,
237532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           llvm::GlobalValue::AppendingLinkage, Array,
238532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           "llvm.global.annotations", &TheModule);
239532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  gv->setSection("llvm.metadata");
240532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman}
241532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
24286daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattnerstatic CodeGenModule::GVALinkage
24386daeee2d4aa6523679f07f27a826bf4c42ca95dChris LattnerGetLinkageForFunction(const FunctionDecl *FD, const LangOptions &Features) {
24443907e87c776391d7d96da04b48e7bf06d8baafcEli Friedman  // "static" functions get internal linkage.
2455e222139610a9f8b2b5f4ddd112f10dec9ec1e97Eli Friedman  if (FD->getStorageClass() == FunctionDecl::Static)
2467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    return CodeGenModule::GVA_Internal;
2477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
248005eedce54da6580de37bb115bf581008637e4b1Chris Lattner  if (!FD->isInline())
249cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    return CodeGenModule::GVA_StrongExternal;
25086daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner
251d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner  // If the inline function explicitly has the GNU inline attribute on it, or if
252d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner  // this is C89 mode, we use to GNU semantics.
2539f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor  if (!Features.C99 && !Features.CPlusPlus) {
254d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner    // extern inline in GNU mode is like C99 inline.
2559f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    if (FD->getStorageClass() == FunctionDecl::Extern)
2569f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor      return CodeGenModule::GVA_C99Inline;
2579f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    // Normal inline is a strong symbol.
2589f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    return CodeGenModule::GVA_StrongExternal;
2599f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor  } else if (FD->hasActiveGNUInlineAttribute()) {
2609f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    // GCC in C99 mode seems to use a different decision-making
2619f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    // process for extern inline, which factors in previous
2629f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    // declarations.
2639f9bf258f8ebae30bfb70feb9d797d6eb67b0460Douglas Gregor    if (FD->isExternGNUInline())
264d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner      return CodeGenModule::GVA_C99Inline;
265d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner    // Normal inline is a strong symbol.
266cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    return CodeGenModule::GVA_StrongExternal;
267d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner  }
268cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner
26986daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  // The definition of inline changes based on the language.  Note that we
27086daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  // have already handled "static inline" above, with the GVA_Internal case.
271cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner  if (Features.CPlusPlus)  // inline and extern inline.
27286daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    return CodeGenModule::GVA_CXXInline;
27386daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner
274d55a71d852d4d8b785122b8d033a0c06b187067bChris Lattner  assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode");
275b3efa98e320590e8be9d62818e89e599303e65b4Douglas Gregor  if (FD->isC99InlineDefinition())
276b3efa98e320590e8be9d62818e89e599303e65b4Douglas Gregor    return CodeGenModule::GVA_C99Inline;
277b3efa98e320590e8be9d62818e89e599303e65b4Douglas Gregor
278b3efa98e320590e8be9d62818e89e599303e65b4Douglas Gregor  return CodeGenModule::GVA_StrongExternal;
2797c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
2807c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
2817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar/// SetFunctionDefinitionAttributes - Set attributes for a global.
282b97b69244a4e7916c7b8fca28fa21b36ce5b30b2Daniel Dunbar///
283b97b69244a4e7916c7b8fca28fa21b36ce5b30b2Daniel Dunbar/// FIXME: This is currently only done for aliases and functions, but
284b97b69244a4e7916c7b8fca28fa21b36ce5b30b2Daniel Dunbar/// not for variables (these details are set in
285b97b69244a4e7916c7b8fca28fa21b36ce5b30b2Daniel Dunbar/// EmitGlobalVarDefinition for variables).
2867c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
2877c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                    llvm::GlobalValue *GV) {
28886daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  GVALinkage Linkage = GetLinkageForFunction(D, Features);
2897c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
29055d6f50b23a1fd0a04b568787a25beb7537e6c9bDaniel Dunbar  if (Linkage == GVA_Internal) {
2919f9427999cf69b3b89cd0ed3be16ed27a1c282c7Chris Lattner    GV->setLinkage(llvm::Function::InternalLinkage);
2929f9427999cf69b3b89cd0ed3be16ed27a1c282c7Chris Lattner  } else if (D->hasAttr<DLLExportAttr>()) {
2937c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setLinkage(llvm::Function::DLLExportLinkage);
29444b0bc008ee11cdee69ad12210ca7550e4fa426aChris Lattner  } else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>()) {
29544b0bc008ee11cdee69ad12210ca7550e4fa426aChris Lattner    GV->setLinkage(llvm::Function::WeakAnyLinkage);
296cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner  } else if (Linkage == GVA_C99Inline) {
297cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    // In C99 mode, 'inline' functions are guaranteed to have a strong
298cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    // definition somewhere else, so we can use available_externally linkage.
299d9d049a93c55624908e81cf3927b7905efeba05fChris Lattner    GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
30086daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  } else if (Linkage == GVA_CXXInline) {
30186daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // In C++, the compiler has to emit a definition in every translation unit
30286daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // that references the function.  We should use linkonce_odr because
30386daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // a) if all references in this translation unit are optimized away, we
30486daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // don't need to codegen it.  b) if the function persists, it needs to be
30586daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // merged with other definitions. c) C++ has the ODR, so we know the
30686daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // definition is dependable.
30786daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
3087c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
309cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    assert(Linkage == GVA_StrongExternal);
310cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    // Otherwise, we have strong external linkage.
3117c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setLinkage(llvm::Function::ExternalLinkage);
3120dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar  }
313d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
3147c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
315d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
316d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
3177dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
3187dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              const CGFunctionInfo &Info,
3197dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
320761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
32188b5396b0897f28d22ae3debf4a0d97b33b6c362Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList);
322c134fcb0d7989fe6937e47e6216637647e074aefEli Friedman
323761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
324761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel                                        AttributeList.size()));
325ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman
326ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman  // Set the appropriate calling convention for the Function.
327b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  if (D->hasAttr<FastCallAttr>())
328f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov    F->setCallingConv(llvm::CallingConv::X86_FastCall);
329f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov
330b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  if (D->hasAttr<StdCallAttr>())
331f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov    F->setCallingConv(llvm::CallingConv::X86_StdCall);
332f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
333f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
3347c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
3357c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
33674ac74ae244c501027924c99f2a33559a1e23b53Daniel Dunbar  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
337f93349f3ec4d69eafba42436c33aaa91bfca7e70Daniel Dunbar    F->addFnAttr(llvm::Attribute::NoUnwind);
338af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
339b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  if (D->hasAttr<AlwaysInlineAttr>())
340af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar    F->addFnAttr(llvm::Attribute::AlwaysInline);
34181ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson
342b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  if (D->hasAttr<NoinlineAttr>())
34381ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson    F->addFnAttr(llvm::Attribute::NoInline);
344f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
345f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
3467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetCommonAttributes(const Decl *D,
3477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
3487c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  setGlobalVisibility(GV, D);
3497c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3507c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (D->hasAttr<UsedAttr>())
3517c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
3527c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3537c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
3557c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
3567c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3570e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
3580e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
3590e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
3600e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
3610e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
3627c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3637c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
3647c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3650e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
366f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
367f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
368f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbarvoid CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
369f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar                                          llvm::Function *F) {
3707dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar  SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
37145c25ba11cbf8c9a461def5b03f6ee9481e06769Daniel Dunbar
3727c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
3737c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
3747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (FD->hasAttr<DLLImportAttr>()) {
3767c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
3777c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else if (FD->hasAttr<WeakAttr>() || FD->hasAttr<WeakImportAttr>()) {
3787c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
3797c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // separate linkage types for this.
3807c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
3817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
3827c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalLinkage);
3837c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
3847c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3857c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
3867c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
387219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
388219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
3890269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
3900269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  assert(!GV->isDeclaration() &&
3910269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
39235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
3930269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
3940269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
3950269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
3960269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
3970269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  if (LLVMUsed.empty())
3980269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
3990269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
40035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
40135f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, LLVMUsed.size());
40235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner
40335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
40435f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  std::vector<llvm::Constant*> UsedArray;
40535f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
40635f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
40735f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner    UsedArray[i] =
40835f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), i8PTy);
40935f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
41035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner
4110269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  llvm::GlobalVariable *GV =
4120269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    new llvm::GlobalVariable(ATy, false,
4130269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
41435f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner                             llvm::ConstantArray::get(ATy, UsedArray),
4150269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             "llvm.used", &getModule());
4160269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4170269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
4180269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
4190269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4200269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
42167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
42267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
42367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // for a static function, iterate until no  changes are made.
42467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  while (!DeferredDeclsToEmit.empty()) {
4252a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
42667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
42767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
42867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // The mangled name for the decl must have been emitted in GlobalDeclMap.
42967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Look it up to see if it was defined with a stronger definition (e.g. an
43067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // extern inline function with a strong function redefinition).  If so,
43167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // just ignore the deferred decl.
43267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
43367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
434b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson
43567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
43667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
43767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
43867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
43967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
44067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
4415f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
4425f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
4438bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
4448bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// annotation information for a given GlobalValue.  The annotation struct is
4458bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
4463c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar/// GlobalValue being annotated.  The second field is the constant string
4478bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// created from the AnnotateAttr's annotation.  The third field is a constant
4488bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// string containing the name of the translation unit.  The fourth field is
4498bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// the line number in the file of the annotated value declaration.
4508bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///
4518bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// FIXME: this does not unique the annotation string constants, as llvm-gcc
4528bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///        appears to.
4538bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///
4548bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begemanllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
4558bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
4568bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                unsigned LineNo) {
4578bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Module *M = &getModule();
4588bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4598bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // get [N x i8] constants for the annotation string, and the filename string
4608bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // which are the 2nd and 3rd elements of the global annotation structure.
4618bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
4628bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
4638bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
4648bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                  true);
4658bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4668bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // Get the two global values corresponding to the ConstantArrays we just
4678bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // created to hold the bytes of the strings.
4688e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
4698bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::GlobalValue *annoGV =
4708bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  new llvm::GlobalVariable(anno->getType(), false,
4718bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                           llvm::GlobalValue::InternalLinkage, anno,
4728e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                           GV->getName() + StringPrefix, M);
4738bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // translation unit name string, emitted into the llvm.metadata section.
4748bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::GlobalValue *unitGV =
4758bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  new llvm::GlobalVariable(unit->getType(), false,
4768e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                           llvm::GlobalValue::InternalLinkage, unit,
4778e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                           StringPrefix, M);
4788bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
47957d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
4808bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
4818bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantExpr::getBitCast(GV, SBP),
4828bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantExpr::getBitCast(annoGV, SBP),
4838bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantExpr::getBitCast(unitGV, SBP),
4848bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
4858bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
4868bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  return llvm::ConstantStruct::get(Fields, 4, false);
4878bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
4888bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
48973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbarbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
4905c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // Never defer when EmitAllDecls is specified or the decl has
4915c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // attribute used.
492b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
49373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    return false;
494bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
495bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
49673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Constructors and destructors should never be deferred.
497b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
49873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return false;
49973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
50086daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    GVALinkage Linkage = GetLinkageForFunction(FD, Features);
501dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner
502dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner    // static, static inline, always_inline, and extern inline functions can
50386daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    // always be deferred.  Normal inline functions can be deferred in C99/C++.
504cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
505cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner        Linkage == GVA_CXXInline)
506dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner      return true;
507dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner    return false;
50873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  }
509dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner
510dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner  const VarDecl *VD = cast<VarDecl>(Global);
511dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner  assert(VD->isFileVarDecl() && "Invalid decl");
512b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor
513dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner  return VD->getStorageClass() == VarDecl::Static;
51473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
51573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
516b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
5172a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  const ValueDecl *Global = GD.getDecl();
5182a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
519bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
520bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
521b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  if (Global->hasAttr<AliasAttr>())
522bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    return EmitAliasDefinition(Global);
523219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
52467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
5255e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
52673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
52773241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    if (!FD->isThisDeclarationADefinition())
52873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
5290269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
5300269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
531bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
532bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
533b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    // In C++, if this is marked "extern", defer code generation.
534b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    if (getLangOptions().CPlusPlus &&
535b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor        VD->getStorageClass() == VarDecl::Extern && !VD->getInit())
536b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor      return;
537b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor
538b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    // In C, if this isn't a definition, defer code generation.
539b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    if (!getLangOptions().CPlusPlus && !VD->getInit())
54073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
5414c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
5424c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
54367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
54467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
54573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  if (MayDeferGeneration(Global)) {
54667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // If the value has already been used, add it directly to the
54767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // DeferredDeclsToEmit list.
5482a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    const char *MangledName = getMangledName(GD);
54967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (GlobalDeclMap.count(MangledName))
5502a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson      DeferredDeclsToEmit.push_back(GD);
55167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    else {
55267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      // Otherwise, remember that we saw a deferred decl with this name.  The
55367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      // first use of the mangled name will cause it to move into
55467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      // DeferredDeclsToEmit.
5552a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson      DeferredDecls[MangledName] = GD;
55667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    }
557bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
558bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
559bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
560bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // Otherwise emit the definition.
5612a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  EmitGlobalDefinition(GD);
5624c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
5634c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
564b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
5652a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  const ValueDecl *D = GD.getDecl();
5662a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
5672a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
5682a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    EmitCXXConstructor(CD, GD.getCtorType());
569b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  else if (isa<FunctionDecl>(D))
570b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    EmitGlobalFunctionDefinition(GD);
5712a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
572bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    EmitGlobalVarDefinition(VD);
5732a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  else {
574bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(0 && "Invalid argument to EmitGlobalDefinition()");
575bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
576bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
577bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
57874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
57974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
58074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
58174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
58274391b48b4791cded373683a3baf67314f358d50Chris Lattner///
58374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
58474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
58574391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
58674391b48b4791cded373683a3baf67314f358d50Chris Lattner                                                       const llvm::Type *Ty,
587b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner                                                       GlobalDecl D) {
5880558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
5890558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
5900558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
5910558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
5920558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
5930558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
5940558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
5950558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
5960558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, PTy);
5970558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
5980558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
59967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
60067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
60167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
6022a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
6039fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    DeferredDecls.find(MangledName);
60467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
60567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
60667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
60767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
60867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
609b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
6100c337ed63ff0f04fd8315afabb2d7a51969fdc97Chris Lattner    // If this the first reference to a C++ inline function in a class, queue up
6110c337ed63ff0f04fd8315afabb2d7a51969fdc97Chris Lattner    // the deferred function body for emission.  These are not seen as
6120c337ed63ff0f04fd8315afabb2d7a51969fdc97Chris Lattner    // top-level declarations.
613b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
614b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      DeferredDeclsToEmit.push_back(D);
61567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
61667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
6170558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // This function doesn't have a complete type (for example, the return
6180558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // type is an incomplete struct). Use a fake type instead, and make
6190558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // sure not to try to set attributes.
6200558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  bool ShouldSetAttributes = true;
6210558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (!isa<llvm::FunctionType>(Ty)) {
6220558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
6230558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner                                 std::vector<const llvm::Type*>(), false);
6240558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    ShouldSetAttributes = false;
6250558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
6260558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
6270558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner                                             llvm::Function::ExternalLinkage,
628d972678a053d4785772b75cf6c8d4ab74ac2c7f6Chris Lattner                                             "", &getModule());
629d972678a053d4785772b75cf6c8d4ab74ac2c7f6Chris Lattner  F->setName(MangledName);
630b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  if (D.getDecl() && ShouldSetAttributes)
631b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F);
6320558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  Entry = F;
6330558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  return F;
6340558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
6350558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
63674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
63774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
63874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
639b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
64074391b48b4791cded373683a3baf67314f358d50Chris Lattner                                                 const llvm::Type *Ty) {
64174391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
64274391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
643b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    Ty = getTypes().ConvertType(GD.getDecl()->getType());
644b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  return GetOrCreateLLVMFunction(getMangledName(GD.getDecl()), Ty, GD);
64574391b48b4791cded373683a3baf67314f358d50Chris Lattner}
64677ba708819285931932ecd33691a672bb59d221aEli Friedman
64774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
64874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
64974391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
65074391b48b4791cded373683a3baf67314f358d50Chris LattnerCodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
65174391b48b4791cded373683a3baf67314f358d50Chris Lattner                                     const char *Name) {
65274391b48b4791cded373683a3baf67314f358d50Chris Lattner  // Convert Name to be a uniqued string from the IdentifierInfo table.
65374391b48b4791cded373683a3baf67314f358d50Chris Lattner  Name = getContext().Idents.get(Name).getName();
654b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
65574391b48b4791cded373683a3baf67314f358d50Chris Lattner}
656bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
65774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
65874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
65974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
66074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
66174391b48b4791cded373683a3baf67314f358d50Chris Lattner///
66274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
66374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
66474391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
66574391b48b4791cded373683a3baf67314f358d50Chris Lattner                                                     const llvm::PointerType*Ty,
66674391b48b4791cded373683a3baf67314f358d50Chris Lattner                                                     const VarDecl *D) {
6673c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
6685d4f5c724533b994de05df49ae259120482ec366Chris Lattner  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
66999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
67074391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
671570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
672570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
67399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
67474391b48b4791cded373683a3baf67314f358d50Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, Ty);
67599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
67667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
67767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
67867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
67967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
6802a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
68167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.find(MangledName);
68267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
68367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
68467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
68567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
68667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
68767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
68867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
68999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  llvm::GlobalVariable *GV =
69074391b48b4791cded373683a3baf67314f358d50Chris Lattner    new llvm::GlobalVariable(Ty->getElementType(), false,
69199b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
692d972678a053d4785772b75cf6c8d4ab74ac2c7f6Chris Lattner                             0, "", &getModule(),
69356ebe5082da7411fb37479e230b52735f77cff35Eli Friedman                             false, Ty->getAddressSpace());
694d972678a053d4785772b75cf6c8d4ab74ac2c7f6Chris Lattner  GV->setName(MangledName);
69549988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
69699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
69774391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
69874391b48b4791cded373683a3baf67314f358d50Chris Lattner    // FIXME: This code is overly simple and should be merged with
69974391b48b4791cded373683a3baf67314f358d50Chris Lattner    // other global handling.
70074391b48b4791cded373683a3baf67314f358d50Chris Lattner    GV->setConstant(D->getType().isConstant(Context));
70149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
70274391b48b4791cded373683a3baf67314f358d50Chris Lattner    // FIXME: Merge with other attribute handling code.
70374391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (D->getStorageClass() == VarDecl::PrivateExtern)
70404d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
70549988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
706b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar    if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
70774391b48b4791cded373683a3baf67314f358d50Chris Lattner      GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
70856ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
70956ebe5082da7411fb37479e230b52735f77cff35Eli Friedman    GV->setThreadLocal(D->isThreadSpecified());
71074391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
71174391b48b4791cded373683a3baf67314f358d50Chris Lattner
71274391b48b4791cded373683a3baf67314f358d50Chris Lattner  return Entry = GV;
71374391b48b4791cded373683a3baf67314f358d50Chris Lattner}
714eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
715eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
71674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
71774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
71874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// then it will be greated with the specified type instead of whatever the
71974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
72074391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
72174391b48b4791cded373683a3baf67314f358d50Chris Lattner                                                  const llvm::Type *Ty) {
72274391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
72374391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
72474391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
72574391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
72674391b48b4791cded373683a3baf67314f358d50Chris Lattner
72774391b48b4791cded373683a3baf67314f358d50Chris Lattner  const llvm::PointerType *PTy =
72874391b48b4791cded373683a3baf67314f358d50Chris Lattner    llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
72974391b48b4791cded373683a3baf67314f358d50Chris Lattner  return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
73074391b48b4791cded373683a3baf67314f358d50Chris Lattner}
7313f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
73274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
73374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
73474391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
73574391b48b4791cded373683a3baf67314f358d50Chris LattnerCodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
73674391b48b4791cded373683a3baf67314f358d50Chris Lattner                                     const char *Name) {
73774391b48b4791cded373683a3baf67314f358d50Chris Lattner  // Convert Name to be a uniqued string from the IdentifierInfo table.
73874391b48b4791cded373683a3baf67314f358d50Chris Lattner  Name = getContext().Idents.get(Name).getName();
73974391b48b4791cded373683a3baf67314f358d50Chris Lattner  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
740bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
741bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
74203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
74303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
74403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
7457520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
7467520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
7477520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
7487520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
7497520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    const char *MangledName = getMangledName(D);
7507520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    if (GlobalDeclMap.count(MangledName) == 0) {
7512a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson      DeferredDecls[MangledName] = GlobalDecl(D);
75203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
7537520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
7547520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
7557520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
7567520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
75703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
75803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
75903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
760bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
7618f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
76277ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
763b75863d53b8a2bbf0ece8e6df2b6e5be7f3896c4Chris Lattner
7648f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  if (D->getInit() == 0) {
765cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
76603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
76703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
76803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
76903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
77003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
77103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
77203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
77303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
77403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
77503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    Init = llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(ASTTy));
77677ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
777e9352cc9818ba59e7cf88500ef048991c90f3821Anders Carlsson    Init = EmitConstantExpr(D->getInit(), D->getType());
7786e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
779232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar      ErrorUnsupported(D, "static initializer");
7806e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman      QualType T = D->getInit()->getType();
7816e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman      Init = llvm::UndefValue::get(getTypes().ConvertType(T));
7826e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
7838f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
7848e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
7852d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner  const llvm::Type* InitType = Init->getType();
786570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
787570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
788570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
789570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
790570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
791570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
792570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
7933c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar
794570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
795570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
796570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
797570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
798570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
799570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
800570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
801570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
802570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
803570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
804570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
805570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
806570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
807570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
808570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
809570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
810570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Remove the old entry from GlobalDeclMap so that we'll create a new one.
811570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GlobalDeclMap.erase(getMangledName(D));
812232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
813570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
814570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
8150558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    GV->takeName(cast<llvm::GlobalValue>(Entry));
8160558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
81777ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
81877ba708819285931932ecd33691a672bb59d221aEli Friedman    llvm::Constant *NewPtrForOldDecl =
819570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
820570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
82177ba708819285931932ecd33691a672bb59d221aEli Friedman
82277ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
823570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
82477ba708819285931932ecd33691a672bb59d221aEli Friedman  }
82577ba708819285931932ecd33691a672bb59d221aEli Friedman
8268bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
8278bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    SourceManager &SM = Context.getSourceManager();
8288bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    AddAnnotation(EmitAnnotateAttr(GV, AA,
829f7cf85b330bedd2877e1371fb0a83e99751ae162Chris Lattner                              SM.getInstantiationLineNumber(D->getLocation())));
8308bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  }
8318bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
83288a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
833b381aac9bae6d608c72267dd0ed08ec6369e94e4Nuno Lopes  GV->setConstant(D->getType().isConstant(Context));
8340de40af3a3aa14e3854c0eafeabd08f6762801f9Eli Friedman  GV->setAlignment(getContext().getDeclAlignInBytes(D));
83508d7802a406ee4a7cc18e8fce0c137b8c410ea7cEli Friedman
83688a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
8378fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner  if (D->getStorageClass() == VarDecl::Static)
8388fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner    GV->setLinkage(llvm::Function::InternalLinkage);
839b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  else if (D->hasAttr<DLLImportAttr>())
840ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    GV->setLinkage(llvm::Function::DLLImportLinkage);
841b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  else if (D->hasAttr<DLLExportAttr>())
842ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    GV->setLinkage(llvm::Function::DLLExportLinkage);
843b11fa0d25d86169f0e0a29d5398116c0212bb787Daniel Dunbar  else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
844286acbdbe0c82e9a6bcad5fca3c4fa582f3f1a2cMike Stump    GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
84504d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  else if (!CompileOpts.NoCommon &&
84604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar           (!D->hasExternalStorage() && !D->getInit()))
84704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
8487e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  else
84904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
8507e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar
8517c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
85204d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
853686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  // Emit global variable debug information.
8542d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner  if (CGDebugInfo *DI = getDebugInfo()) {
85566031a5594bc9a7dc0dc5137c3e7955f835e4639Daniel Dunbar    DI->setLocation(D->getLocation());
856686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta    DI->EmitGlobalVariable(GV, D);
857686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
85888a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
8595f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
860bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
861bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
862bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// existing call uses of the old function in the module, this adjusts them to
863bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// call the new function directly.
864bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
865bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
866bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
867bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
868bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// run at -O0.
869bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
870bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                      llvm::Function *NewFn) {
871bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // If we're redefining a global as a function, don't transform it.
872bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
873bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (OldFn == 0) return;
874bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
875bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  const llvm::Type *NewRetTy = NewFn->getReturnType();
876bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::SmallVector<llvm::Value*, 4> ArgList;
877bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
878bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
879bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner       UI != E; ) {
880bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
881bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
882bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!CI) continue;
883bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
884bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the return types don't match exactly, and if the call isn't dead, then
885bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // we can't transform this call.
886bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (CI->getType() != NewRetTy && !CI->use_empty())
887bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
888bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
889bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the function was passed too few arguments, don't transform.  If extra
890bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // arguments were passed, we silently drop them.  If any of the types
891bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // mismatch, we don't transform.
892bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    unsigned ArgNo = 0;
893bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    bool DontTransform = false;
894bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
895bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
896bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      if (CI->getNumOperands()-1 == ArgNo ||
897bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner          CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
898bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        DontTransform = true;
899bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
900bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
901bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
902bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (DontTransform)
903bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
904bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
905bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
906bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
907bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
908bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
909bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                     ArgList.end(), "", CI);
910bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.clear();
911bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (NewCall->getType() != llvm::Type::VoidTy)
912bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      NewCall->takeName(CI);
913bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    NewCall->setCallingConv(CI->getCallingConv());
914bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    NewCall->setAttributes(CI->getAttributes());
915bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
916bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
917bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!CI->use_empty())
918bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      CI->replaceAllUsesWith(NewCall);
919bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CI->eraseFromParent();
920bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
921bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
922bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
923bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
924b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
9252b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  const llvm::FunctionType *Ty;
926b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
927b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner
9282b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9292b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
9302b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson
9312b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
9322b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  } else {
9332b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
9342b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson
9352b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    // As a special case, make sure that definitions of K&R function
9362b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    // "type foo()" aren't declared as varargs (which forces the backend
9372b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    // to do unnecessary work).
9382b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    if (D->getType()->isFunctionNoProtoType()) {
9392b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      assert(Ty->isVarArg() && "Didn't lower type as expected");
9402b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // Due to stret, the lowered function could have arguments.
9412b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // Just create the same type as was lowered by ConvertType
9422b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // but strip off the varargs bit.
9432b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
9442b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
9452b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    }
946ff75e1db95a53c7606e0bb114cf9adc59ab3d7f6Chris Lattner  }
947d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar
9489fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
949b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
95034809507232bc4c3c4840c7d092c7440219fddafChris Lattner
9510558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
9520558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
9530558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
9540558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
9550558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
9560558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
9570558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
9580558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
959bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
960bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
96142745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
962bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
9630558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
96434809507232bc4c3c4840c7d092c7440219fddafChris Lattner
96562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
96662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
96762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
96862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
96962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
97062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
97162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f(int x)").  Start by making a new function of the
97262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // correct type, RAUW, then steal the name.
97334809507232bc4c3c4840c7d092c7440219fddafChris Lattner    GlobalDeclMap.erase(getMangledName(D));
974b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
975bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    NewFn->takeName(OldFn);
976bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
977bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If this is an implementation of a function without a prototype, try to
978bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // replace any existing uses of the function (which may be calls) with uses
979bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // of the new function
9809fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    if (D->getType()->isFunctionNoProtoType()) {
981bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
9829fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
9839fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
98462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
98562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
986bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
987bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      llvm::Constant *NewPtrForOldDecl =
988bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
989bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
990bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
99162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
99262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
993bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
99462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
9950558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
996bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
9970558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
9980558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
999bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1000219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  CodeGenFunction(*this).GenerateCode(D, Fn);
10016379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
10027c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
10037c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
1004219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
100534809507232bc4c3c4840c7d092c7440219fddafChris Lattner  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1006219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
100734809507232bc4c3c4840c7d092c7440219fddafChris Lattner  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1008219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
1009bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1010bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1011bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattnervoid CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
1012bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  const AliasAttr *AA = D->getAttr<AliasAttr>();
1013bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
1014bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1015bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1016bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1017bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Unique the name through the identifier table.
1018bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  const char *AliaseeName = AA->getAliasee().c_str();
1019bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  AliaseeName = getContext().Idents.get(AliaseeName).getName();
1020bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1021bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
1022bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
1023bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
1024bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
1025b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
1026bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
1027bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1028bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                    llvm::PointerType::getUnqual(DeclTy), 0);
1029bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1030bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
1031bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::GlobalValue *GA =
1032bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
1033bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
1034bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
1035bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1036bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // See if there is already something with the alias' name in the module.
1037bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  const char *MangledName = getMangledName(D);
1038bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1039bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1040bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry && !Entry->isDeclaration()) {
1041bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a definition in the module, then it wins over the alias.
1042bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // This is dubious, but allow it to be safe.  Just ignore the alias.
1043bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    GA->eraseFromParent();
1044bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    return;
1045bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
1046bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1047bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
1048bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
1049bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
1050bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
1051bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
1052bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
1053bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
1054bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
1055bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1056bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1057bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
1058bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
1059bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
1060bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1061bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Now we know that there is no conflict, set the name.
1062bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  Entry = GA;
1063bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  GA->setName(MangledName);
1064bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
10657c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
10667c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
10677c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
10687c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (D->hasAttr<DLLExportAttr>()) {
10697c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10707c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
10717297134f128423fce2e88f92421ed135bded7d4eDouglas Gregor      if (FD->getBody(getContext()))
10727c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
10737c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
10747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
10757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
10767c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>()) {
10777c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
10787c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
10797c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
10807c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
1081bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
1082bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1083b808c952bbff821dce727dd801a1098d64394f98Chris Lattner/// getBuiltinLibFunction - Given a builtin id for a function like
1084b808c952bbff821dce727dd801a1098d64394f98Chris Lattner/// "__builtin_fabsf", return a Function* for "fabsf".
1085c136e6cf237711f9f1324637a0b2cdf6ae8e79e4Mike Stumpllvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
10863e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
10873e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
10883e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor         "isn't a lib fn");
1089bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
10903e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  // Get the name, skip over the __builtin_ prefix (if necessary).
10913e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
10923e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
10933e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    Name += 10;
1094bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
1095bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // Get the type for the builtin.
1096370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor  Builtin::Context::GetBuiltinTypeError Error;
1097370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor  QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
1098370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor  assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
1099370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor
1100bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  const llvm::FunctionType *Ty =
1101bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1102bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
1103b808c952bbff821dce727dd801a1098d64394f98Chris Lattner  // Unique the name through the identifier table.
1104b808c952bbff821dce727dd801a1098d64394f98Chris Lattner  Name = getContext().Idents.get(Name).getName();
1105bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // FIXME: param attributes for sext/zext etc.
1106b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1107bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner}
1108bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
11097acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattnerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
11107acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner                                            unsigned NumTys) {
11117acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner  return llvm::Intrinsic::getDeclaration(&getModule(),
11127acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
11137acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
1114bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
11155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerllvm::Function *CodeGenModule::getMemCpyFn() {
11165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (MemCpyFn) return MemCpyFn;
11174e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
11184e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
11195f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
1120c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
11210c99509927a0c7a48490486b9fec287b63e5c09cEli Friedmanllvm::Function *CodeGenModule::getMemMoveFn() {
11220c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman  if (MemMoveFn) return MemMoveFn;
11234e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
11244e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
11250c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman}
11260c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman
112741ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venanciollvm::Function *CodeGenModule::getMemSetFn() {
112841ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio  if (MemSetFn) return MemSetFn;
11294e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
11304e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
113141ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio}
11327acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner
1133e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlssonstatic void appendFieldAndPadding(CodeGenModule &CGM,
1134e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson                                  std::vector<llvm::Constant*>& Fields,
113544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                                  FieldDecl *FieldD, FieldDecl *NextFieldD,
113644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                                  llvm::Constant* Field,
11373c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner                                  RecordDecl* RD, const llvm::StructType *STy) {
1138e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  // Append the field.
1139e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  Fields.push_back(Field);
1140e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
114144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
1142e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1143e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  int NextStructFieldNo;
114444b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  if (!NextFieldD) {
1145e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    NextStructFieldNo = STy->getNumElements();
1146e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  } else {
114744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
1148e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  }
1149e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1150e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  // Append padding
1151e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1152e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    llvm::Constant *C =
1153e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson      llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1154e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1155e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    Fields.push_back(C);
1156e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  }
1157e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson}
1158e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1159bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattnerllvm::Constant *CodeGenModule::
11608d4141f83d9de379547cf05bd75d4c6cf894b189Steve NaroffGetAddrOfConstantCFString(const StringLiteral *Literal) {
1161b59212a6e494d2c364b54462f545833902c29158Steve Naroff  std::string str;
1162271474e32f38cc5bd735c1006e499996cbc6e2d1Chris Lattner  unsigned StringLength = 0;
1163b59212a6e494d2c364b54462f545833902c29158Steve Naroff
1164e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff  bool isUTF16 = false;
1165e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff  if (Literal->containsNonAsciiOrNull()) {
1166e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff    // Convert from UTF-8 to UTF-16.
1167e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff    llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1168e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff    const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1169e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff    UTF16 *ToPtr = &ToBuf[0];
1170e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff
1171e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff    ConversionResult Result;
1172e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff    Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1173e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff                                &ToPtr, ToPtr+Literal->getByteLength(),
1174e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff                                strictConversion);
1175aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff    if (Result == conversionOK) {
1176aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1177aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      // without doing more surgery to this routine. Since we aren't explicitly
1178aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      // checking for endianness here, it's also a bug (when generating code for
1179aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      // a target that doesn't match the host endianness). Modeling this as an
1180aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      // i16 array is likely the cleanest solution.
1181aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      StringLength = ToPtr-&ToBuf[0];
1182aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1183aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      isUTF16 = true;
1184aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff    } else if (Result == sourceIllegal) {
1185fd942628abfe30e30427875db953222ae99b4325Steve Naroff      // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
1186aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      str.assign(Literal->getStrData(), Literal->getByteLength());
1187aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      StringLength = str.length();
1188aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff    } else
1189aa4a756185e77755aaa10ae50db08ae5be58e70aSteve Naroff      assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
1190b59212a6e494d2c364b54462f545833902c29158Steve Naroff
1191b59212a6e494d2c364b54462f545833902c29158Steve Naroff  } else {
1192b59212a6e494d2c364b54462f545833902c29158Steve Naroff    str.assign(Literal->getStrData(), Literal->getByteLength());
1193b59212a6e494d2c364b54462f545833902c29158Steve Naroff    StringLength = str.length();
1194e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff  }
1195c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  llvm::StringMapEntry<llvm::Constant *> &Entry =
1196c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1197c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
11988e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
11998e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    return C;
1200c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
12013e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
12023e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
1203c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1204c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
1205c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1206c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    Ty = llvm::ArrayType::get(Ty, 0);
12073e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
12083e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // FIXME: This is fairly broken if
12093e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // __CFConstantStringClassReference is already defined, in that it
12103e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // will get renamed and the user will most likely see an opaque
12113e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // error message. This is a general issue with relying on
12123e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // particular names.
12133e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    llvm::GlobalVariable *GV =
1214c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson      new llvm::GlobalVariable(Ty, false,
1215c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               llvm::GlobalVariable::ExternalLinkage, 0,
1216c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               "__CFConstantStringClassReference",
1217c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               &getModule());
12183e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
12193e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
12203e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
12213e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1222c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
1223c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1224e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
1225e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
12263e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
1227e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  const llvm::StructType *STy =
1228e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1229e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1230e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  std::vector<llvm::Constant*> Fields;
12316ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor  RecordDecl::field_iterator Field = CFRD->field_begin(getContext());
123244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
1233c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
123444b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  FieldDecl *CurField = *Field++;
123544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  FieldDecl *NextField = *Field++;
123644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
123744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                        CFConstantStringClassRef, CFRD, STy);
1238c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1239c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
124044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  CurField = NextField;
124144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  NextField = *Field++;
12423e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
124344b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
1244e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff                        isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0)
1245e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff                                : llvm::ConstantInt::get(Ty, 0x07C8),
1246e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff                        CFRD, STy);
1247c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1248c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
124944b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  CurField = NextField;
125044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  NextField = *Field++;
12513e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *C = llvm::ConstantArray::get(str);
1252a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
1253a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  const char *Sect, *Prefix;
1254a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  bool isConstant;
1255a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
1256a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1257a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    Sect = getContext().Target.getUnicodeStringSection();
1258a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    // FIXME: Why does GCC not set constant here?
1259a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    isConstant = false;
1260a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  } else {
1261a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    Prefix = getContext().Target.getStringSymbolPrefix(true);
1262a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    Sect = getContext().Target.getCFStringDataSection();
1263a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    // FIXME: -fwritable-strings should probably affect this, but we
1264a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    // are following gcc here.
1265a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    isConstant = true;
1266a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
12678e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  llvm::GlobalVariable *GV =
1268a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    new llvm::GlobalVariable(C->getType(), isConstant,
12698e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                             llvm::GlobalValue::InternalLinkage,
1270a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar                             C, Prefix, &getModule());
1271a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (Sect)
12728e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
1273a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
1274a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1275a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar    GV->setAlignment(Align);
1276a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
127744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
12788e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                        llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2),
1279e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson                        CFRD, STy);
1280c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1281c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
128244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  CurField = NextField;
128344b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  NextField = 0;
1284c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
128544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
1286b59212a6e494d2c364b54462f545833902c29158Steve Naroff                        llvm::ConstantInt::get(Ty, StringLength), CFRD, STy);
1287c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1288c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
1289e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  C = llvm::ConstantStruct::get(STy, Fields);
12908e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  GV = new llvm::GlobalVariable(C->getType(), true,
12918e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                                llvm::GlobalVariable::InternalLinkage, C,
12928e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                                getContext().Target.getCFStringSymbolPrefix(),
12938e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                                &getModule());
12948e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (const char *Sect = getContext().Target.getCFStringSection())
12958e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
12960c67829763b98bc670062b553897a851fab17401Anders Carlsson  Entry.setValue(GV);
12973e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
12980c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
1299c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
130045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
13016143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetStringForStringLiteral - Return the appropriate bytes for a
13021e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar/// string literal, properly padded to match the literal type.
13036143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
13041e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const char *StrData = E->getStrData();
13051e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  unsigned Len = E->getByteLength();
13061e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
13071e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const ConstantArrayType *CAT =
13081e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar    getContext().getAsConstantArrayType(E->getType());
13091e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  assert(CAT && "String isn't pointer or array!");
13101e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
1311dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  // Resize the string to the right size.
13121e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  std::string Str(StrData, StrData+Len);
13131e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  uint64_t RealLen = CAT->getSize().getZExtValue();
1314dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner
1315dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  if (E->isWide())
1316dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner    RealLen *= getContext().Target.getWCharWidth()/8;
1317dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner
13181e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  Str.resize(RealLen, '\0');
13191e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
13201e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  return Str;
13211e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar}
13221e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
13236143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
13246143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
13256143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
13266143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
13276143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // FIXME: This can be more efficient.
13286143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  return GetAddrOfConstantString(GetStringForStringLiteral(S));
13296143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
13306143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
1331eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1332eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
1333eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
1334eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1335eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
1336eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1337a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
1338a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
1339eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
1340eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1341eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1342a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
134345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattnerstatic llvm::Constant *GenerateStringLiteral(const std::string &str,
134445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
13455fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
13465fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             const char *GlobalName) {
13476143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
13486143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  llvm::Constant *C = llvm::ConstantArray::get(str, false);
134945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
135045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
1351eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  return new llvm::GlobalVariable(C->getType(), constant,
1352eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner                                  llvm::GlobalValue::InternalLinkage,
13538e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar                                  C, GlobalName, &CGM.getModule());
135445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
135545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
13566143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
13576143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
13586143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
13596143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
13606143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
13616143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
13626143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
13636143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
13645fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbarllvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
13655fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                                       const char *GlobalName) {
13668e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  bool IsConstant = !Features.WritableStrings;
13678e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
13688e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
13698e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
13708e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
13718e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
13728e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
13738e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!IsConstant)
13745fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar    return GenerateStringLiteral(str, false, *this, GlobalName);
137545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
137645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  llvm::StringMapEntry<llvm::Constant *> &Entry =
137745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
137845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
137945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  if (Entry.getValue())
1380eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    return Entry.getValue();
138145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
138245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
13835fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
138445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  Entry.setValue(C);
138545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  return C;
138645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
13876143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
13886143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
13896143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// array containing the literal and a terminating '\-'
13906143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
13915fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbarllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
13925fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                                        const char *GlobalName){
1393c9f29c61856ffb5f643cedbe87ac076f21a1381aChris Lattner  return GetAddrOfConstantString(str + '\0', GlobalName);
13946143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
139541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1396af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
1397af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
1398af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbarvoid CodeGenModule::EmitObjCPropertyImplementations(const
1399af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
1400653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor  for (ObjCImplementationDecl::propimpl_iterator
1401653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor         i = D->propimpl_begin(getContext()),
1402653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor         e = D->propimpl_end(getContext()); i != e; ++i) {
1403af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCPropertyImplDecl *PID = *i;
1404af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1405af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
1406af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1407af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1408af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1409af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
1410af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // been overridden. Note that ::isSynthesized is not the method
1411af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
1412af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
1413af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
1414653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor      if (!D->getInstanceMethod(getContext(), PD->getGetterName()))
1415fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
1416fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
1417af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
1418653f1b1bf293a9bd96fd4dd6372e779cc7af1597Douglas Gregor          !D->getInstanceMethod(getContext(), PD->getSetterName()))
1419fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
1420fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
1421af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
1422af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
1423af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
1424af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
142591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
1426984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
14276ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor  for (RecordDecl::decl_iterator I = ND->decls_begin(getContext()),
14286ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor         E = ND->decls_end(getContext());
1429984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
1430984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
1431984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
1432984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
143391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
143491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
143591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
143691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
143791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
143891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
143991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
14406ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor  for (RecordDecl::decl_iterator I = LSD->decls_begin(getContext()),
14416ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor         E = LSD->decls_end(getContext());
144291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson       I != E; ++I)
144391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
144491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
144591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
144641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
144741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
144841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
144941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
145041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
145141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
145241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
145341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
145441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
14552b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
145641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
145741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
14582a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    EmitGlobal(GlobalDecl(cast<ValueDecl>(D)));
145941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
146041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
146195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
146241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
1463984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
146441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
146595d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
146695d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
146795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
146827ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
146927ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
147027ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
147195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson
147295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
147341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
147438e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
147541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCClass:
147641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCForwardProtocol:
1477b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCCategory:
1478b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
147941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
1480285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
148141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCProtocol:
1482b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
148341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
148441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
148541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
1486af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
1487af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
148841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
148941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
149041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1491af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
1492af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1493af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
1494af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    Runtime->GenerateClass(OMD);
149541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
1496af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
149741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
149841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
149941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
15007297134f128423fce2e88f92421ed135bded7d4eDouglas Gregor    if (OMD->getBody(getContext()))
150141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
150241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
150341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
150441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCompatibleAlias:
1505305c658ebce84bb9833fc0e7675554656453b8e8Fariborz Jahanian    // compatibility-alias is a directive and has no code gen.
150641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
150741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
150891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
150991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
151041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
151141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
151241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
151341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
151441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    std::string AsmString(AD->getAsmString()->getStrData(),
151541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar                          AD->getAsmString()->getByteLength());
151641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
151741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
151841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
151941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
152041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
152141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(S + '\n' + AsmString);
152241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
152341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
152441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
152541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  default:
152641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // Make sure we handled everything we should, every other kind is
152741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // a non-top-level decl.  FIXME: Would be nice to have an
152841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // isTopLevelDeclKind function. Need to recode Decl::Kind to do
152941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // that easily.
153041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
153141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
153241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
1533