CodeGenModule.cpp revision 53bad4e98ed5e765df4231099bf1c737582908bf
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 "CodeGenTBAA.h"
18af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGCall.h"
195f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor#include "CGCXXABI.h"
202811ccf48d6d898c42cc4cfad37abedb36236d20Chandler Carruth#include "CGObjCRuntime.h"
215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "TargetInfo.h"
22c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/Frontend/CodeGenOptions.h"
2321ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/ASTContext.h"
241b63e4f732dbc73d90abf886b4d21f8e3a165f6dChris Lattner#include "clang/AST/CharUnits.h"
252c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/AST/DeclObjC.h"
268bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/AST/DeclCXX.h"
275f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/DeclTemplate.h"
28e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff#include "clang/AST/Mangle.h"
29ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman#include "clang/AST/RecordLayout.h"
30bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner#include "clang/Basic/Builtins.h"
315f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/Diagnostic.h"
3220ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov#include "clang/Basic/SourceManager.h"
3378f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner#include "clang/Basic/TargetInfo.h"
345f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/ConvertUTF.h"
355f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/CallingConv.h"
365f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Module.h"
375f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Intrinsics.h"
382811ccf48d6d898c42cc4cfad37abedb36236d20Chandler Carruth#include "llvm/LLVMContext.h"
39fb97b03e42d397405f617be0252be83e77a66f6eChris Lattner#include "llvm/ADT/Triple.h"
40bd3606426d389370616126af969904ec493cb105Chris Lattner#include "llvm/Target/TargetData.h"
41bd3606426d389370616126af969904ec493cb105Chris Lattner#include "llvm/Support/CallSite.h"
422811ccf48d6d898c42cc4cfad37abedb36236d20Chandler Carruth#include "llvm/Support/ErrorHandling.h"
43dbd920c7758e6dfb678a8f503fb14ba97c26f23aAnders Carlssonusing namespace clang;
44dbd920c7758e6dfb678a8f503fb14ba97c26f23aAnders Carlssonusing namespace CodeGen;
45a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Anderson
46a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Andersonstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
47208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar  switch (CGM.getContext().Target.getCXXABI()) {
483c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
493c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
503c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
513c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  }
523c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner
533c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  llvm_unreachable("invalid C++ ABI kind");
543c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  return *CreateItaniumCXXABI(CGM);
553c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner}
56e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
57e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
582811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
592b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner                             llvm::Module &M, const llvm::TargetData &TD,
602b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner                             Diagnostic &diags)
612b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner  : BlockModule(C, M, TD, Types, *this), Context(C),
62815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek    Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
63815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
64815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek    ABI(createCXXABI(*this)),
65815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
66815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek    TBAA(0),
6789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    VTables(*this), Runtime(0),
6889ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    CFConstantStringClassRef(0), ConstantStringClassRef(0),
6989ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    VMContext(M.getContext()),
7082227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner    NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
71208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
72208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar    BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
73208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar    BlockObjectAssign(0), BlockObjectDispose(0){
746bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
756bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Features.ObjC1)
76532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman    Runtime = 0;
770269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  else if (!Features.NeXTRuntime)
78f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar    Runtime = CreateGNUObjCRuntime(*this);
79f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar  else if (Features.ObjCNonFragileABI)
80488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
812c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  else
8290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    Runtime = CreateMacObjCRuntime(*this);
8390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar
8490df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  // Enable TBAA unless it's suppressed.
8590df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
8756b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                           ABI.getMangleContext());
882c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner
890a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  // If debug info generation is enabled, create the CGDebugInfo object.
900a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
912c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
9258c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
93488e993a135ce700b982bf099c3d6b856301d642Daniel DunbarCodeGenModule::~CodeGenModule() {
94c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  delete Runtime;
9590df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  delete &ABI;
9690df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  delete TBAA;
9790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  delete DebugInfo;
9890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar}
991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10056b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbarvoid CodeGenModule::createObjCRuntime() {
101c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  if (!Features.NeXTRuntime)
1020a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    Runtime = CreateGNUObjCRuntime(*this);
103c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  else if (Features.ObjCNonFragileABI)
104c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
1051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  else
10604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar    Runtime = CreateMacObjCRuntime(*this);
10704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar}
10804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
10904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbarvoid CodeGenModule::Release() {
11004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  EmitDeferred();
11140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  EmitCXXGlobalInitFunc();
11204d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  EmitCXXGlobalDtorFunc();
11304d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  if (Runtime)
1141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
11504d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
11604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
11704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
11804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  EmitAnnotations();
11904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  EmitLLVMUsed();
12004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
1217e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  SimplifyPersonality();
1226ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
12304d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  if (getCodeGenOpts().EmitDeclMetadata)
1244f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    EmitDeclMetadata();
1254f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman}
1261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbarllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
12804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  if (!TBAA)
129df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner    return 0;
1307e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  return TBAA->getTBAAInfo(QTy);
1316ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar}
1327e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar
1336ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbarvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
13404d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar                                        llvm::MDNode *TBAAInfo) {
1357cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
13604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar}
13704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
13804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbarbool CodeGenModule::isTargetDarwin() const {
13904d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
14004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar}
14104d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
1427cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian/// ErrorUnsupported - Print out an error that codegen doesn't support the
1437cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian/// specified stmt yet.
1447cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanianvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
1452a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson                                     bool OmitOnError) {
1464a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  if (OmitOnError && getDiags().hasErrorOccurred())
1471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return;
1482a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
1492a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson                                               "cannot compile this %0 yet");
1502a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  std::string Msg = Type;
1512a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
1521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    << Msg << S->getSourceRange();
1532a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson}
1542a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
1552a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson/// ErrorUnsupported - Print out an error that codegen doesn't support the
1565f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// specified decl yet.
1575f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregorvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
1585f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor                                     bool OmitOnError) {
159c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  if (OmitOnError && getDiags().hasErrorOccurred())
160c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner    return;
1615f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
1626ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor                                               "cannot compile this %0 yet");
163c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  std::string Msg = Type;
164c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
165c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner}
1663c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner
167c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattnervoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                        const NamedDecl *D) const {
1696ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  // Internal definitions always have default visibility.
1706ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  if (GV->hasLocalLinkage()) {
171b540491851910c2efa68196a8bdc2eed1071c17dAnders Carlsson    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
172fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar    return;
1733c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  }
174fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar
1755f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor  // Set visibility for definitions.
1766ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
17795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
17895d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
17995d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson}
18095d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson
18195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson/// Set the symbol visibility of type information (vtable and RTTI)
18295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson/// associated with the given type.
1831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
18495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson                                      const CXXRecordDecl *RD,
1855f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor                                      TypeVisibilityKind TVK) const {
1865f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor  setGlobalVisibility(GV, RD);
1876d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
1886d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  if (!CodeGenOpts.HiddenWeakVTables)
1896bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    return;
19049988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
1916bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // We never want to drop the visibility for RTTI names.
1926d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  if (TVK == TVK_ForRTTIName)
1936d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner    return;
1946bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
1956bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // We want to drop the visibility to hidden for weak type symbols.
1966bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // This isn't possible if there might be unresolved references
19749988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // elsewhere that rely on this symbol being visible.
1986bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
1996bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // This should be kept roughly in sync with setThunkVisibility
2006bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // in CGVTables.cpp.
2016bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2026bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Preconditions.
2036bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
2041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
2056bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    return;
2066bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
20796e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  // Don't override an explicit visibility attribute.
2086bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (RD->hasAttr<VisibilityAttr>())
2096bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    return;
2101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  switch (RD->getTemplateSpecializationKind()) {
21296e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  // We have to disable the optimization if this is an EI definition
2136bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // because there might be EI declarations in other shared objects.
2146bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  case TSK_ExplicitInstantiationDefinition:
2156bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  case TSK_ExplicitInstantiationDeclaration:
2166bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    return;
2176bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Every use of a non-template class's type information has to emit it.
2190032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  case TSK_Undeclared:
2203c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    break;
22108e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson
2226bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // In theory, implicit instantiations can ignore the possibility of
2236bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // an explicit instantiation declaration because there necessarily
2246bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // must be an EI definition somewhere with default visibility.  In
22596e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  // practice, it's possible to have an explicit instantiation for
2261c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson  // an arbitrary template class, and linkers aren't necessarily able
227572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner  // to deal with mixed-visibility symbols.
2287db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson  case TSK_ExplicitSpecialization:
2291c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson  case TSK_ImplicitInstantiation:
2306d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner    if (!CodeGenOpts.HiddenWeakTemplateVTables)
2316d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner      return;
2326d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner    break;
233532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  }
234532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
235532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  // If there's a key function, there may be translation units
236532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  // that don't have the key function's definition.  But ignore
237532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  // this if we're emitting RTTI under -fno-rtti.
238532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
23996e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    if (Context.getKeyFunction(RD))
240532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman      return;
241532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  }
2421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Otherwise, drop the visibility to hidden.
2441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
2451c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson  GV->setUnnamedAddr(true);
246532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman}
247532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
248532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begemanllvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
24986daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
2501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
25168584ed35ad819a1668e3f527ba7f5dd4ae6a333Douglas Gregor  llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
2529aeed32282fe8a775c24c01c923717ca86695685John McCall  if (!Str.empty())
2539aeed32282fe8a775c24c01c923717ca86695685John McCall    return Str;
2549aeed32282fe8a775c24c01c923717ca86695685John McCall
2559aeed32282fe8a775c24c01c923717ca86695685John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
2569aeed32282fe8a775c24c01c923717ca86695685John McCall    IdentifierInfo *II = ND->getIdentifier();
2577d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor    assert(II && "Attempt to mangle unnamed decl.");
2587d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor
2597d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor    Str = II->getName();
2607d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor    return Str;
2611fd2dd145d9bcdf0b8d60a88e1795b6ae83656f5Douglas Gregor  }
2621fd2dd145d9bcdf0b8d60a88e1795b6ae83656f5Douglas Gregor
2631fd2dd145d9bcdf0b8d60a88e1795b6ae83656f5Douglas Gregor  llvm::SmallString<256> Buffer;
2641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
265d0e3daf2b980b505e535d35b432c938c6d0208efDouglas Gregor    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
2661fd2dd145d9bcdf0b8d60a88e1795b6ae83656f5Douglas Gregor  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
2671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
2687ced9c8529b734e313f62a3b81189d6f402f6713Douglas Gregor  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
2691fd2dd145d9bcdf0b8d60a88e1795b6ae83656f5Douglas Gregor    getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
2701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  else
2711fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor    getCXXABI().getMangleContext().mangleName(ND, Buffer);
2721fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor
2731fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor  // Allocate space for the mangled name.
2741fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor  size_t Length = Buffer.size();
2751fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor  char *Name = MangledNamesAllocator.Allocate<char>(Length);
276cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner  std::copy(Buffer.begin(), Buffer.end(), Name);
2771fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor
278b3efa98e320590e8be9d62818e89e599303e65b4Douglas Gregor  Str = llvm::StringRef(Name, Length);
2791fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor
280b3efa98e320590e8be9d62818e89e599303e65b4Douglas Gregor  return Str;
2817d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor}
2827d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor
2837d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregorvoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
2847d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor                                        const BlockDecl *BD) {
2857d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor  MangleContext &MangleCtx = getCXXABI().getMangleContext();
2867d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor  const Decl *D = GD.getDecl();
2877d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor  if (D == 0)
2887d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor    MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
2897d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
2907d9c3c92c90ae36d58ec21bc53c4c08e02ac3555Douglas Gregor    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
2911fc09a92d0bffda20e06fa882388c01e192e2069Douglas Gregor  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
2927c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
2937c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  else
2947c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
295b97b69244a4e7916c7b8fca28fa21b36ce5b30b2Daniel Dunbar}
296f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump
297f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stumpllvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
2987c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  return getModule().getNamedValue(Name);
2997c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
30068584ed35ad819a1668e3f527ba7f5dd4ae6a333Douglas Gregor
3017c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar/// AddGlobalCtor - Add a function to the list that will be called before
30255d6f50b23a1fd0a04b568787a25beb7537e6c9bDaniel Dunbar/// main() runs.
3039f9427999cf69b3b89cd0ed3be16ed27a1c282c7Chris Lattnervoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
30440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  // FIXME: Type coercion of void()* types.
3057c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
30640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis}
30744b0bc008ee11cdee69ad12210ca7550e4fa426aChris Lattner
308cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner/// AddGlobalDtor - Add a function to the list that will be called
309cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner/// when the module is unloaded.
310cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattnervoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
311d9d049a93c55624908e81cf3927b7905efeba05fChris Lattner  // FIXME: Type coercion of void()* types.
3121fd2dd145d9bcdf0b8d60a88e1795b6ae83656f5Douglas Gregor  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
31386daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner}
31486daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner
31586daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattnervoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
31686daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  // Ctor function type is void()*.
31786daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  llvm::FunctionType* CtorFTy =
31886daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
31986daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
3207c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
321cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner  // Get the type of a ctor entry, { i32, void ()* }.
322cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner  llvm::StructType* CtorStructTy =
3237c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
3240dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar                          llvm::PointerType::getUnqual(CtorFTy), NULL);
325d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
3267c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Construct the constructor and destructor arrays.
327d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes  std::vector<llvm::Constant*> Ctors;
328d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
3297dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar    std::vector<llvm::Constant*> S;
3301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
3317dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                I->second, false));
332ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
333761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
334ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  }
335761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel
336ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  if (!Ctors.empty()) {
337ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
338f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar    new llvm::GlobalVariable(TheModule, AT, false,
339f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
3407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                             llvm::ConstantArray::get(AT, Ctors),
3417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                             GlobalName);
34274ac74ae244c501027924c99f2a33559a1e23b53Daniel Dunbar  }
3431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
344af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
34540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidisvoid CodeGenModule::EmitAnnotations() {
346af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar  if (Annotations.empty())
3471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return;
3481feade8e520be483293dbf55eb57a51720899589Mike Stump
34981ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson  // Create a new global variable for the ConstantStruct in the Module.
350f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump  llvm::Constant *Array =
351fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
352fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson                                                Annotations.size()),
353fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson                           Annotations);
354fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson  llvm::GlobalValue *gv =
355fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson  new llvm::GlobalVariable(TheModule, Array->getType(), false,
356f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump                           llvm::GlobalValue::AppendingLinkage, Array,
357f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump                           "llvm.global.annotations");
358fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  gv->setSection("llvm.metadata");
359bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump}
360bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump
361f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbarllvm::GlobalValue::LinkageTypes
362f80519b919a348db004fba18530706314d1ebfb5Daniel DunbarCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
3631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
3647c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3657c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (Linkage == GVA_Internal)
3667c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    return llvm::Function::InternalLinkage;
36740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis
3687c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (D->hasAttr<DLLExportAttr>())
3697c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    return llvm::Function::DLLExportLinkage;
37040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis
3717c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (D->hasAttr<WeakAttr>())
3727c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    return llvm::Function::WeakAnyLinkage;
3737c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3740e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  // In C99 mode, 'inline' functions are guaranteed to have a strong
3750e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  // definition somewhere else, so we can use available_externally linkage.
3760e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  if (Linkage == GVA_C99Inline)
3770e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar    return llvm::Function::AvailableExternallyLinkage;
3780e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar
3797c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // In C++, the compiler has to emit a definition in every translation unit
3807c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // that references the function.  We should use linkonce_odr because
3817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // a) if all references in this translation unit are optimized away, we
3820e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  // don't need to codegen it.  b) if the function persists, it needs to be
383f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar  // merged with other definitions. c) C++ has the ODR, so we know the
384f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar  // definition is dependable.
385f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
386c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman    return !Context.getLangOptions().AppleKext
387c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman             ? llvm::Function::LinkOnceODRLinkage
388c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman             : llvm::Function::InternalLinkage;
389c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman
3901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // An explicit instantiation of a template has weak linkage, since
3917c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // explicit instantiations can occur in multiple translation units
3927c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // and must all be equivalent. However, we are not allowed to
3931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // throw away these explicit instantiations.
39440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Linkage == GVA_ExplicitTemplateInstantiation)
3957c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    return !Context.getLangOptions().AppleKext
3961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump             ? llvm::Function::WeakODRLinkage
39740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis             : llvm::Function::InternalLinkage;
3987c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
3991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Otherwise, we have strong external linkage.
4007c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  assert(Linkage == GVA_StrongExternal);
4017c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  return llvm::Function::ExternalLinkage;
4021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
4037c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
4047c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
40540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis/// SetFunctionDefinitionAttributes - Set attributes for a global.
4067c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar///
407219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar/// FIXME: This is currently only done for aliases and functions, but not for
408219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar/// variables (these details are set in EmitGlobalVarDefinition for variables).
4090269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
4101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                    llvm::GlobalValue *GV) {
4110269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  SetCommonAttributes(D, GV);
41235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner}
4130269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4140269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
4150269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                                              const CGFunctionInfo &Info,
4160269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                                              llvm::Function *F) {
417ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  unsigned CallingConv;
4180269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  AttributeListType AttributeList;
4190269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  ConstructAttributeList(Info, D, AttributeList, CallingConv);
4203c0ef8cc0dc246bd3083e8cdd63005e8873d36d2Benjamin Kramer  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
4211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                          AttributeList.size()));
42235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
42335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner}
42435f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner
42535f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattnervoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
4261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                           llvm::Function *F) {
4271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
428a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Anderson    F->addFnAttr(llvm::Attribute::NoUnwind);
42935f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner
4301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (D->hasAttr<AlwaysInlineAttr>())
431c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    F->addFnAttr(llvm::Attribute::AlwaysInline);
432c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian
43396e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  if (D->hasAttr<NakedAttr>())
4341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->addFnAttr(llvm::Attribute::Naked);
4351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (D->hasAttr<NoInlineAttr>())
4370269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    F->addFnAttr(llvm::Attribute::NoInline);
4387db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson
4391c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
4400269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    F->setUnnamedAddr(true);
4410269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4420269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  if (Features.getStackProtectorMode() == LangOptions::SSPOn)
4430269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    F->addFnAttr(llvm::Attribute::StackProtect);
4440269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
44567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    F->addFnAttr(llvm::Attribute::StackProtectReq);
44667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
44767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
44867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (alignment)
4492a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    F->setAlignment(alignment);
45067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
45167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // C++ ABI requires 2-byte alignment for member functions.
45267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
45367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    F->setAlignment(2);
45467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner}
45567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
45667b00520c8f5b48fad722b790d87fea6be764efeChris Lattnervoid CodeGenModule::SetCommonAttributes(const Decl *D,
45767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner                                        llvm::GlobalValue *GV) {
4581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
45967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    setGlobalVisibility(GV, ND);
46067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  else
4611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
46267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
46367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (D->hasAttr<UsedAttr>())
46467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    AddUsedGlobal(GV);
4655f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
4665f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GV->setSection(SA->getName());
4688bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
4701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
4711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4728bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begemanvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
4738bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                  llvm::Function *F,
4748bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                  const CGFunctionInfo &FI) {
4758bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  SetLLVMFunctionAttributes(D, FI, F);
4768bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  SetLLVMFunctionAttributesForDefinition(D, F);
4778bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  F->setLinkage(llvm::Function::InternalLinkage);
4798bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4808bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  SetCommonAttributes(D, F);
4818bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
4828bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4838bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begemanvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
4848bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                          llvm::Function *F,
4853c0ef8cc0dc246bd3083e8cdd63005e8873d36d2Benjamin Kramer                                          bool IsIncompleteFunction) {
4861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4870032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson
4880032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  if (!IsIncompleteFunction)
4890032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
4908bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4918bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // Only a few attributes are set on declarations; these may later be
4928bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // overridden by a definition.
4938bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (FD->hasAttr<DLLImportAttr>()) {
49595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    F->setLinkage(llvm::Function::DLLImportLinkage);
49695b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  } else if (FD->hasAttr<WeakAttr>() ||
49795b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner             FD->hasAttr<WeakImportAttr>()) {
4988bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    // "extern_weak" is overloaded in LLVM; we probably should have
4998bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    // separate linkage types for this.
50095b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    F->setLinkage(llvm::Function::ExternalWeakLinkage);
5011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else {
50295b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    F->setLinkage(llvm::Function::ExternalLinkage);
5038bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
50457d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
5058bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
5063c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson      F->setVisibility(GetLLVMVisibility(LV.visibility()));
5073c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    }
5083c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson  }
5090032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson
5108bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
51147a434ff3d49e7906eda88e8e8242e4297725b32Owen Anderson    F->setSection(SA->getName());
5128bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
5138bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
51473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
5155c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  assert(!GV->isDeclaration() &&
5165c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar         "Only globals with definition can force usage.");
51740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  LLVMUsed.push_back(GV);
51873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
519bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
520bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
52173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  // Don't create llvm.used if there is no need.
5221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (LLVMUsed.empty())
52340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    return;
52473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
52573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
52668584ed35ad819a1668e3f527ba7f5dd4ae6a333Douglas Gregor
5271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Convert LLVMUsed to what ConstantArray needs.
528dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner  std::vector<llvm::Constant*> UsedArray;
52986daeee2d4aa6523679f07f27a826bf4c42ca95dChris Lattner  UsedArray.resize(LLVMUsed.size());
530cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
531cbb8fc18d86a886856f5b852a6a3ead71fec17f9Chris Lattner    UsedArray[i] =
532dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
533dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner                                      i8PTy);
53473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  }
5351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
536dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner  if (UsedArray.empty())
537dbb5a376c8b9272813a30c5519031e9ea2fb071fChris Lattner    return;
538b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
53974d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson
54074d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson  llvm::GlobalVariable *GV =
54174d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson    new llvm::GlobalVariable(getModule(), ATy, false,
54274d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson                             llvm::GlobalValue::AppendingLinkage,
54374d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson                             llvm::ConstantArray::get(ATy, UsedArray),
54474d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson                             "llvm.used");
54574d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson
54674d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson  GV->setSection("llvm.metadata");
54774d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson}
54874d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlsson
54974d644abe56809d9bcea7311f37aa9063ab9e064Anders Carlssonvoid CodeGenModule::EmitDeferred() {
5501028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  // Emit code for any potentially referenced deferred decls.  Since a
5511028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  // previously unused static decl may become used during the generation of code
552393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian  // for a static function, iterate until no  changes are made.
553393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian
554393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
555393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian    if (!DeferredVTables.empty()) {
556393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian      const CXXRecordDecl *RD = DeferredVTables.back();
557393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian      DeferredVTables.pop_back();
558393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian      getVTables().GenerateClassData(getVTableLinkage(RD), RD);
559393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian      continue;
560393c247fe025ccb5f914e37e948192ea86faef8cFariborz Jahanian    }
56173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
56273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    GlobalDecl D = DeferredDeclsToEmit.back();
563b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    DeferredDeclsToEmit.pop_back();
5644a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson
5651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // Check to see if we've already emitted this.  This is necessary
566bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // for a couple of reasons: first, decls can end up in the
567bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // deferred-decls queue multiple times, and second, decls can end
56840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    // up with definitions in unusual ways (e.g. by an extern inline
569bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // function acquiring a strong function redefinition).  Just
570219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // ignore these cases.
57167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    //
5725e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar    // TODO: That said, looking this up multiple times is very wasteful.
57373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    llvm::StringRef Name = getMangledName(D);
57473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
57573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    assert(CGRef && "Deferred decl wasn't referenced?");
5760269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5770269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    if (!CGRef->isDeclaration())
578bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar      continue;
579bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
580b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
5812928c2107f2e0007f35fe1c224aab63535f1403dAnders Carlsson    // purposes an alias counts as a definition.
5821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (isa<llvm::GlobalAlias>(CGRef))
58348a83b5e7ae4051c7c11680ac00c1fa02d610a62Douglas Gregor      continue;
584b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor
585b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    // Otherwise, emit the definition and move on to the next one.
586b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor    EmitGlobalDefinition(D);
587b6c8c8bd8d362c8a6cdb767415b0d21e62b77eb2Douglas Gregor  }
58873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
5894c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
5904c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
59167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// annotation information for a given GlobalValue.  The annotation struct is
59267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
59373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar/// GlobalValue being annotated.  The second field is the constant string
59467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// created from the AnnotateAttr's annotation.  The third field is a constant
59567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// string containing the name of the translation unit.  The fourth field is
5962a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson/// the line number in the file of the annotated value declaration.
59767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner///
5982a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson/// FIXME: this does not unique the annotation string constants, as llvm-gcc
59967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner///        appears to.
60067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner///
60167b00520c8f5b48fad722b790d87fea6be764efeChris Lattnerllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
60267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner                                                const AnnotateAttr *AA,
6032a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson                                                unsigned LineNo) {
60467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  llvm::Module *M = &getModule();
605bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
606bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // get [N x i8] constants for the annotation string, and the filename string
607bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // which are the 2nd and 3rd elements of the global annotation structure.
608bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
6092a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson  llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
6104c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman                                                  AA->getAnnotation(), true);
6114c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
612b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner                                                  M->getModuleIdentifier(),
6134a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson                                                  true);
6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6158e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson  // Get the two global values corresponding to the ConstantArrays we just
6168e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson  // created to hold the bytes of the strings.
6178e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson  llvm::GlobalValue *annoGV =
6188e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson    new llvm::GlobalVariable(*M, anno->getType(), false,
6192a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson                             llvm::GlobalValue::PrivateLinkage, anno,
6202a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson                             GV->getName());
6217267c1693abe7875b0c57268be05005ae013c6c9Anders Carlsson  // translation unit name string, emitted into the llvm.metadata section.
6227267c1693abe7875b0c57268be05005ae013c6c9Anders Carlsson  llvm::GlobalValue *unitGV =
623b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    new llvm::GlobalVariable(*M, unit->getType(), false,
624b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner                             llvm::GlobalValue::PrivateLinkage, unit,
6252a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson                             ".str");
626bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  unitGV->setUnnamedAddr(true);
6272a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson
628bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // Create the ConstantStruct for the global annotation.
629bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  llvm::Constant *Fields[4] = {
630bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    llvm::ConstantExpr::getBitCast(GV, SBP),
631bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    llvm::ConstantExpr::getBitCast(annoGV, SBP),
63274391b48b4791cded373683a3baf67314f358d50Chris Lattner    llvm::ConstantExpr::getBitCast(unitGV, SBP),
63374391b48b4791cded373683a3baf67314f358d50Chris Lattner    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
63474391b48b4791cded373683a3baf67314f358d50Chris Lattner  };
63574391b48b4791cded373683a3baf67314f358d50Chris Lattner  return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
63674391b48b4791cded373683a3baf67314f358d50Chris Lattner}
63774391b48b4791cded373683a3baf67314f358d50Chris Lattner
63874391b48b4791cded373683a3baf67314f358d50Chris Lattnerbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
63974391b48b4791cded373683a3baf67314f358d50Chris Lattner  // Never defer when EmitAllDecls is specified.
64074391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Features.EmitAllDecls)
641b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    return false;
6420558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
6430558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  return !getContext().DeclMustBeEmitted(Global);
6440558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
6450558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
6460558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattnerllvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
6471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const AliasAttr *AA = VD->getAttr<AliasAttr>();
6480558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  assert(AA && "No alias?");
64996e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson
6503c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
6510558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
6521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // See if there is already something with the target's name in the module.
653654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
654654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
655654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  llvm::Constant *Aliasee;
656654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (isa<llvm::FunctionType>(DeclTy))
657654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
658654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  else
659654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
660654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                    llvm::PointerType::getUnqual(DeclTy), 0);
661654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (!Entry) {
662654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
663654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    F->setLinkage(llvm::Function::ExternalWeakLinkage);
664654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    WeakRefReferences.insert(F);
665654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
666654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
667654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  return Aliasee;
668654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman}
669654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
670654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedmanvoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
67167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
67267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
67367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Weak references don't produce any output by themselves.
6741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (Global->hasAttr<WeakRefAttr>())
6759fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    return;
67667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
67767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
67867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // emit it now.
67967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (Global->hasAttr<AliasAttr>())
68067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    return EmitAliasDefinition(GD);
681b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner
6820c337ed63ff0f04fd8315afabb2d7a51969fdc97Chris Lattner  // Ignore declarations, they will be emitted on their first use.
6830c337ed63ff0f04fd8315afabb2d7a51969fdc97Chris Lattner  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
6840c337ed63ff0f04fd8315afabb2d7a51969fdc97Chris Lattner    if (FD->getIdentifier()) {
685b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      llvm::StringRef Name = FD->getName();
686b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      if (Name == "_Block_object_assign") {
687c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian        BlockObjectAssignDecl = FD;
688c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian      } else if (Name == "_Block_object_dispose") {
689c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian        BlockObjectDisposeDecl = FD;
6901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      }
691c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian    }
69297a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian
69397a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    // Forward declarations are emitted lazily on first use.
6949889652dbc10060cd604861ed2e5bc6719f845b0Fariborz Jahanian    if (!FD->isThisDeclarationADefinition())
695c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian      return;
696c7ff8e19081c2e974f05f66c4fa9b40750fc655fFariborz Jahanian  } else {
6971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    const VarDecl *VD = cast<VarDecl>(Global);
698b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
699ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
700ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    if (VD->getIdentifier()) {
701ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian      llvm::StringRef Name = VD->getName();
70267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      if (Name == "_NSConcreteGlobalBlock") {
7031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        NSConcreteGlobalBlockDecl = VD;
7040558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      } else if (Name == "_NSConcreteStackBlock") {
7050558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner        NSConcreteStackBlockDecl = VD;
7060558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      }
70797a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    }
70897a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian
7091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
71097a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
71197a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian      return;
71297a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  }
71397a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian
71497a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  // Defer code generation when possible if this is a static definition, inline
7151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // function etc.  These we only want to emit if they are used.
71697a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  if (!MayDeferGeneration(Global)) {
71797a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    // Emit the definition if it can't be deferred.
71897a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    EmitGlobalDefinition(GD);
71997a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    return;
72097a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  }
72197a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian
72297a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  // If we're deferring emission of a C++ variable with an
7231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // initializer, remember the order in which it appeared in the file.
72480e4b9e0e87064a824d72b6ff89074206ecced58Fariborz Jahanian  if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
72597a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian      cast<VarDecl>(Global)->hasInit()) {
72697a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
7271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    CXXGlobalInits.push_back(0);
72897a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  }
72997a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian
73097a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  // If the value has already been used, add it directly to the
73197a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  // DeferredDeclsToEmit list.
73297a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  llvm::StringRef MangledName = getMangledName(GD);
73397a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  if (GetGlobalValue(MangledName))
73497a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    DeferredDeclsToEmit.push_back(GD);
735e64941280877d065a27e8cefd2a9038256d0e3acFariborz Jahanian  else {
736e64941280877d065a27e8cefd2a9038256d0e3acFariborz Jahanian    // Otherwise, remember that we saw a deferred decl with this name.  The
73797a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian    // first use of the mangled name will cause it to move into
738e64941280877d065a27e8cefd2a9038256d0e3acFariborz Jahanian    // DeferredDeclsToEmit.
7391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    DeferredDecls[MangledName] = GD;
74080e4b9e0e87064a824d72b6ff89074206ecced58Fariborz Jahanian  }
74197a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian}
74297a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian
74397a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanianvoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
74497a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
745ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
746ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
747ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian                                 Context.getSourceManager(),
748ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian                                 "Generating code for declaration");
749ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
750ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
7511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // At -O0, don't generate IR for functions with available_externally
752ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    // linkage.
753ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    if (CodeGenOpts.OptimizationLevel == 0 &&
754ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian        !Function->hasAttr<AlwaysInlineAttr>() &&
7551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        getFunctionLinkage(Function)
756ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian                                  == llvm::Function::AvailableExternallyLinkage)
757ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian      return;
758ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
759ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
760ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian      if (Method->isVirtual())
761ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian        getVTables().EmitThunks(GD);
762ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
763ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
764183d7181fd59842ac969cbc6fe0376f85dc63ae4Fariborz Jahanian        return EmitCXXConstructor(CD, GD.getCtorType());
765183d7181fd59842ac969cbc6fe0376f85dc63ae4Fariborz Jahanian
766183d7181fd59842ac969cbc6fe0376f85dc63ae4Fariborz Jahanian      if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
767555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson        return EmitCXXDestructor(DD, GD.getDtorType());
768ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    }
7691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
770ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    return EmitGlobalFunctionDefinition(GD);
771ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian  }
772ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
773ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
774ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian    return EmitGlobalVarDefinition(VD);
775ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
776ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian  assert(0 && "Invalid argument to EmitGlobalDefinition()");
777ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian}
778ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian
779ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
780ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian/// module, create and return an llvm Function with the specified type. If there
781ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanian/// is something in the module with the specified name, return it potentially
782183d7181fd59842ac969cbc6fe0376f85dc63ae4Fariborz Jahanian/// bitcasted to the right type.
783183d7181fd59842ac969cbc6fe0376f85dc63ae4Fariborz Jahanian///
784183d7181fd59842ac969cbc6fe0376f85dc63ae4Fariborz Jahanian/// If D is non-null, it specifies a decl that correspond to this.  This is used
785555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson/// to set the attributes on the function when it is first created.
786ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz Jahanianllvm::Constant *
787ad25883a644dd6b52c7923dd128a7d05fb26213cFariborz JahanianCodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
7881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                       const llvm::Type *Ty,
78997a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian                                       GlobalDecl D) {
79097a937532c24a8ea44317d4fdee26d9701a1e83cFariborz Jahanian  // Lookup the entry, lazily creating it if necessary.
791b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
792b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  if (Entry) {
793b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    if (WeakRefReferences.count(Entry)) {
794b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
795b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian      if (FD && !FD->hasAttr<WeakAttr>())
796b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian        Entry->setLinkage(llvm::Function::ExternalLinkage);
797b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian
798b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian      WeakRefReferences.erase(Entry);
799b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    }
800b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian
801b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    if (Entry->getType()->getElementType() == Ty)
8021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      return Entry;
803b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian
804b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    // Make sure the result is of the correct type.
805b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
8061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return llvm::ConstantExpr::getBitCast(Entry, PTy);
807b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  }
808b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian
809b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  // This function doesn't have a complete type (for example, the return
810b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  // type is an incomplete struct). Use a fake type instead, and make
811b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  // sure not to try to set attributes.
812b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  bool IsIncompleteFunction = false;
813b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian
814b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  const llvm::FunctionType *FTy;
815b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  if (isa<llvm::FunctionType>(Ty)) {
816b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    FTy = cast<llvm::FunctionType>(Ty);
817b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  } else {
8181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
819b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian    IsIncompleteFunction = true;
820b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  }
821b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian
822b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  llvm::Function *F = llvm::Function::Create(FTy,
823b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian                                             llvm::Function::ExternalLinkage,
824b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian                                             MangledName, &getModule());
825b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  assert(F->getName() == MangledName && "name was uniqued!");
826b193a414f13d7cfa2524a8149eff8d4871f8cbf6Fariborz Jahanian  if (D.getDecl())
82774391b48b4791cded373683a3baf67314f358d50Chris Lattner    SetFunctionAttributes(D, F, IsIncompleteFunction);
82874391b48b4791cded373683a3baf67314f358d50Chris Lattner
82974391b48b4791cded373683a3baf67314f358d50Chris Lattner  // This is the first use or definition of a mangled name.  If there is a
830b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  // deferred decl with this name, remember that we need to emit it at the end
83174391b48b4791cded373683a3baf67314f358d50Chris Lattner  // of the file.
83274391b48b4791cded373683a3baf67314f358d50Chris Lattner  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
83374391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (DDI != DeferredDecls.end()) {
8344a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
8354fe95f99a2693f1145785ea5835ba6937e49c730Douglas Gregor    // list, and remove it from DeferredDecls (since we don't need it anymore).
83674391b48b4791cded373683a3baf67314f358d50Chris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
83777ba708819285931932ecd33691a672bb59d221aEli Friedman    DeferredDecls.erase(DDI);
83874391b48b4791cded373683a3baf67314f358d50Chris Lattner
83974391b48b4791cded373683a3baf67314f358d50Chris Lattner  // Otherwise, there are cases we have to worry about where we're
84074391b48b4791cded373683a3baf67314f358d50Chris Lattner  // using a declaration for which we must emit a definition but where
84174391b48b4791cded373683a3baf67314f358d50Chris Lattner  // we might not find a top-level definition:
84274391b48b4791cded373683a3baf67314f358d50Chris Lattner  //   - member functions defined inline in their classes
84374391b48b4791cded373683a3baf67314f358d50Chris Lattner  //   - friend functions defined inline in some class
844e013d685c6689ac7ae103ee88acf573422d1ed6aDaniel Dunbar  //   - special member functions with implicit definitions
845b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  // If we ever change our AST traversal to walk into class methods,
84674391b48b4791cded373683a3baf67314f358d50Chris Lattner  // this will be unnecessary.
847bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  } else if (getLangOptions().CPlusPlus && D.getDecl()) {
84874391b48b4791cded373683a3baf67314f358d50Chris Lattner    // Look for a declaration that's lexically in a record.
84974391b48b4791cded373683a3baf67314f358d50Chris Lattner    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
85074391b48b4791cded373683a3baf67314f358d50Chris Lattner    do {
85174391b48b4791cded373683a3baf67314f358d50Chris Lattner      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
85274391b48b4791cded373683a3baf67314f358d50Chris Lattner        if (FD->isImplicit()) {
85374391b48b4791cded373683a3baf67314f358d50Chris Lattner          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
85474391b48b4791cded373683a3baf67314f358d50Chris Lattner          DeferredDeclsToEmit.push_back(D);
85574391b48b4791cded373683a3baf67314f358d50Chris Lattner          break;
85674391b48b4791cded373683a3baf67314f358d50Chris Lattner        } else if (FD->isThisDeclarationADefinition()) {
85774391b48b4791cded373683a3baf67314f358d50Chris Lattner          DeferredDeclsToEmit.push_back(D);
8583c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar          break;
8595d4f5c724533b994de05df49ae259120482ec366Chris Lattner        }
86099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner      }
86174391b48b4791cded373683a3baf67314f358d50Chris Lattner      FD = FD->getPreviousDeclaration();
862570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    } while (FD);
8631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
86499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner
8653c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson  // Make sure the result is of the requested type.
86699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (!IsIncompleteFunction) {
8671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    assert(F->getType()->getElementType() == Ty);
86867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    return F;
86967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
87067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
8711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
87267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  return llvm::ConstantExpr::getBitCast(F, PTy);
87367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner}
87467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
87567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
87667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// non-null, then this function will use the specified type if it has to
87767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner/// create it (this occurs when we see a definition of the function).
87867b00520c8f5b48fad722b790d87fea6be764efeChris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
8791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                 const llvm::Type *Ty) {
8801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // If there was no specific requested type, just convert it now.
8811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!Ty)
88299b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
8831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
88456ebe5082da7411fb37479e230b52735f77cff35Eli Friedman  llvm::StringRef MangledName = getMangledName(GD);
885d972678a053d4785772b75cf6c8d4ab74ac2c7f6Chris Lattner  return GetOrCreateLLVMFunction(MangledName, Ty, GD);
88649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar}
88799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner
88874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
889f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump/// type and name.
890f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stumpllvm::Constant *
89174391b48b4791cded373683a3baf67314f358d50Chris LattnerCodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
89249988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar                                     llvm::StringRef Name) {
89374391b48b4791cded373683a3baf67314f358d50Chris Lattner  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
89474391b48b4791cded373683a3baf67314f358d50Chris Lattner}
89504d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar
89649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbarstatic bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
8971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
89840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    return false;
89974391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Context.getLangOptions().CPlusPlus &&
90056ebe5082da7411fb37479e230b52735f77cff35Eli Friedman      Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
90156ebe5082da7411fb37479e230b52735f77cff35Eli Friedman    // FIXME: We should do something fancier here!
90274391b48b4791cded373683a3baf67314f358d50Chris Lattner    return false;
9031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
90474391b48b4791cded373683a3baf67314f358d50Chris Lattner  return true;
90574391b48b4791cded373683a3baf67314f358d50Chris Lattner}
906eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
907eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
90874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
90974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
91074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
91174391b48b4791cded373683a3baf67314f358d50Chris Lattner///
91274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
91374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
91474391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
91574391b48b4791cded373683a3baf67314f358d50Chris LattnerCodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
91674391b48b4791cded373683a3baf67314f358d50Chris Lattner                                     const llvm::PointerType *Ty,
91774391b48b4791cded373683a3baf67314f358d50Chris Lattner                                     const VarDecl *D,
9181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                     bool UnnamedAddr) {
9191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Lookup the entry, lazily creating it if necessary.
92096e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
92174391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Entry) {
92274391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (WeakRefReferences.count(Entry)) {
9233f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar      if (D && !D->hasAttr<WeakAttr>())
92474391b48b4791cded373683a3baf67314f358d50Chris Lattner        Entry->setLinkage(llvm::Function::ExternalLinkage);
92574391b48b4791cded373683a3baf67314f358d50Chris Lattner
92674391b48b4791cded373683a3baf67314f358d50Chris Lattner      WeakRefReferences.erase(Entry);
92774391b48b4791cded373683a3baf67314f358d50Chris Lattner    }
92874391b48b4791cded373683a3baf67314f358d50Chris Lattner
92974391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (UnnamedAddr)
930e013d685c6689ac7ae103ee88acf573422d1ed6aDaniel Dunbar      Entry->setUnnamedAddr(true);
93196e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson
932bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    if (Entry->getType() == Ty)
933bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar      return Entry;
93403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
93503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Make sure the result is of the correct type.
93603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    return llvm::ConstantExpr::getBitCast(Entry, Ty);
9377520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
9387520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
9397520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // This is the first use or definition of a mangled name.  If there is a
9407520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // deferred decl with this name, remember that we need to emit it at the end
9417520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // of the file.
9427520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
943555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson  if (DDI != DeferredDecls.end()) {
94403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
9457520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // list, and remove it from DeferredDecls (since we don't need it anymore).
9467520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    DeferredDeclsToEmit.push_back(DDI->second);
9477520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    DeferredDecls.erase(DDI);
9487520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
94903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
95003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  llvm::GlobalVariable *GV =
95103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
9521028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor                             llvm::GlobalValue::ExternalLinkage,
9531028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor                             0, MangledName, 0,
9541028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor                             false, Ty->getAddressSpace());
9551028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor
9561028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  // Handle things which are present even on external declarations.
9571028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  if (D) {
9581028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    // FIXME: This code is overly simple and should be merged with other global
9591028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    // handling.
9601028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    GV->setConstant(DeclIsConstantGlobal(Context, D));
9611028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor
9621028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    // Set linkage and visibility in case we never see a definition.
9631028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
9641028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    if (LV.linkage() != ExternalLinkage) {
9651028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor      GV->setLinkage(llvm::GlobalValue::InternalLinkage);
9661028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    } else {
9671028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor      if (D->hasAttr<DLLImportAttr>())
9689f0306d969700c9d79a31d559f95a1eb4c0bfcb4Douglas Gregor        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
9691028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor      else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
9701028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
9711028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor
9721028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor      // Set visibility on a declaration only if it's explicit.
9731028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor      if (LV.visibilityExplicit())
9741028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
9751028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    }
9761028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor
9771028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    GV->setThreadLocal(D->isThreadSpecified());
9781028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  }
9791028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor
9801028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  return GV;
9811028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor}
9821028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor
983bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
9848f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattnerllvm::GlobalVariable *
98577ba708819285931932ecd33691a672bb59d221aEli FriedmanCodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
9861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                      const llvm::Type *Ty,
9878f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner                                      llvm::GlobalValue::LinkageTypes Linkage) {
988cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
98903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  llvm::GlobalVariable *OldGV = 0;
99003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
99103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
99203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  if (GV) {
99303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Check if the variable has the right type.
99403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    if (GV->getType()->getElementType() == Ty)
99503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return GV;
99603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
99703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Because C++ name mangling, the only way we can end up with an already
998b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
99977ba708819285931932ecd33691a672bb59d221aEli Friedman      assert(GV->isDeclaration() && "Declaration has wrong type!");
1000e9352cc9818ba59e7cf88500ef048991c90f3821Anders Carlsson    OldGV = GV;
10011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
10026e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman
10036e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman  // Create a new variable.
100489ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
100589ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson                                Linkage, 0, Name);
100689ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson
100789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson  if (OldGV) {
100889ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    // Replace occurrences of the old variable if needed.
100989ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson    GV->takeName(OldGV);
101089ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson
10116e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!OldGV->use_empty()) {
10128f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner      llvm::Constant *NewPtrForOldDecl =
10138e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
10142d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1015570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    }
10161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1017570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    OldGV->eraseFromParent();
1018570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
10199d4a15fd3b85434c43ea27562793de63a793321aChris Lattner
10209d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  return GV;
10219d4a15fd3b85434c43ea27562793de63a793321aChris Lattner}
1022570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
1023570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
10241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// given global variable.  If Ty is non-null and if the global doesn't exist,
1025570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner/// then it will be greated with the specified type instead of whatever the
1026570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner/// normal requested type would be.
10271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1028570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner                                                  const llvm::Type *Ty) {
1029570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
1030570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  QualType ASTTy = D->getType();
1031570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (Ty == 0)
1032570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
1033570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
1034570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  const llvm::PointerType *PTy =
1035570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
1036570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner
1037570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::StringRef MangledName = getMangledName(D);
1038570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1039570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner}
10401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1041570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
1042570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner/// specified type and name.
1043232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbarllvm::Constant *
1044570585c91dee98d7ba8ccf1198c03208ba17966bChris LattnerCodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1045570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner                                     llvm::StringRef Name) {
10460558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  return GetOrCreateLLVMGlobal(Name,  llvm::PointerType::getUnqual(Ty), 0,
10470558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner                               true);
104877ba708819285931932ecd33691a672bb59d221aEli Friedman}
10491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10503c4972def972f8ca44dcd0561779a12aaa6fec97Owen Andersonvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1051570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  assert(!D->getInit() && "Cannot emit definite definitions here!");
105277ba708819285931932ecd33691a672bb59d221aEli Friedman
105377ba708819285931932ecd33691a672bb59d221aEli Friedman  if (MayDeferGeneration(D)) {
1054570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // If we have not seen a reference to this variable yet, place it
105577ba708819285931932ecd33691a672bb59d221aEli Friedman    // into the deferred declarations table to be emitted if needed
105677ba708819285931932ecd33691a672bb59d221aEli Friedman    // later.
105740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    llvm::StringRef MangledName = getMangledName(D);
10588bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    if (!GetGlobalValue(MangledName)) {
10598bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman      DeferredDecls[MangledName] = D;
1060f7cf85b330bedd2877e1371fb0a83e99751ae162Chris Lattner      return;
10618bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    }
10628bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  }
106388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner
1064e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // The tentative definition is the only definition.
1065e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  EmitGlobalVarDefinition(D);
1066e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner}
1067e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1068e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattnervoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1069e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  if (DefinitionRequired)
1070e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1071e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner}
10721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10730de40af3a3aa14e3854c0eafeabd08f6762801f9Eli Friedmanllvm::GlobalVariable::LinkageTypes
107408d7802a406ee4a7cc18e8fce0c137b8c410ea7cEli FriedmanCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
107588a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
10761028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor    return llvm::GlobalVariable::InternalLinkage;
1077a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor
10788fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner  if (const CXXMethodDecl *KeyFunction
107940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis                                    = RD->getASTContext().getKeyFunction(RD)) {
1080ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    // If this class has a key function, use that to determine the linkage of
108140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    // the vtable.
1082ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    const FunctionDecl *Def = 0;
1083e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (KeyFunction->hasBody(Def))
1084e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner      KeyFunction = cast<CXXMethodDecl>(Def);
1085e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1086e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    switch (KeyFunction->getTemplateSpecializationKind()) {
1087e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner      case TSK_Undeclared:
10881028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor      case TSK_ExplicitSpecialization:
10891028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor        // When compiling with optimizations turned on, we emit all vtables,
10902811ccf48d6d898c42cc4cfad37abedb36236d20Chandler Carruth        // even if the key function is not defined in the current translation
1091309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner        // unit. If this is the case, use available_externally linkage.
1092e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner        if (!Def && CodeGenOpts.OptimizationLevel)
109304d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar          return llvm::GlobalVariable::AvailableExternallyLinkage;
1094e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1095e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner        if (KeyFunction->isInlined())
1096e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner          return !Context.getLangOptions().AppleKext ?
109704d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar                   llvm::GlobalVariable::LinkOnceODRLinkage :
10987e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar                   llvm::Function::InternalLinkage;
10997c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
110004d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar        return llvm::GlobalVariable::ExternalLinkage;
1101686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta
11022d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner      case TSK_ImplicitInstantiation:
110366031a5594bc9a7dc0dc5137c3e7955f835e4639Daniel Dunbar        return !Context.getLangOptions().AppleKext ?
1104686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta                 llvm::GlobalVariable::LinkOnceODRLinkage :
1105686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta                 llvm::Function::InternalLinkage;
110688a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner
11075f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer      case TSK_ExplicitInstantiationDefinition:
1108bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        return !Context.getLangOptions().AppleKext ?
1109bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                 llvm::GlobalVariable::WeakODRLinkage :
1110bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                 llvm::Function::InternalLinkage;
1111bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1112bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      case TSK_ExplicitInstantiationDeclaration:
1113bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        // FIXME: Use available_externally linkage. However, this currently
1114bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        // breaks LLVM's build due to undefined symbols.
1115bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1116bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        return !Context.getLangOptions().AppleKext ?
1117bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                 llvm::GlobalVariable::LinkOnceODRLinkage :
1118bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                 llvm::Function::InternalLinkage;
1119bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1120bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1121bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
11221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (Context.getLangOptions().AppleKext)
1123bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    return llvm::Function::InternalLinkage;
1124bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1125bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  switch (RD->getTemplateSpecializationKind()) {
1126bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  case TSK_Undeclared:
1127bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  case TSK_ExplicitSpecialization:
1128bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  case TSK_ImplicitInstantiation:
112908c93a7f2210b464e5abe298a5474b99414615f6Chris Lattner    // FIXME: Use available_externally linkage. However, this currently
1130bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // breaks LLVM's build due to undefined symbols.
113108c93a7f2210b464e5abe298a5474b99414615f6Chris Lattner    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
11321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case TSK_ExplicitInstantiationDeclaration:
1133bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    return llvm::GlobalVariable::LinkOnceODRLinkage;
1134bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1135bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  case TSK_ExplicitInstantiationDefinition:
1136bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      return llvm::GlobalVariable::WeakODRLinkage;
1137bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1138bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1139bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // Silence GCC warning.
1140bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  return llvm::GlobalVariable::LinkOnceODRLinkage;
1141bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1142bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1143bdb0132722082886558f31eccdba06ae1852c0eeChris LattnerCharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1144bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    return Context.toCharUnitsFromBits(
1145bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      TheTargetData.getTypeStoreSizeInBits(Ty));
1146bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1147bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1148bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnervoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1149bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Constant *Init = 0;
1150bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  QualType ASTTy = D->getType();
1151bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  bool NonConstInit = false;
1152bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
11531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const Expr *InitExpr = D->getAnyInitializer();
1154bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1155bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (!InitExpr) {
1156bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // This is a tentative definition; tentative definitions are
1157bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // implicitly initialized with { 0 }.
1158bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    //
1159bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Note that tentative definitions are only emitted at the end of
1160ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    // a translation unit, so they should never have incomplete
1161bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // type. In addition, EmitTentativeDefinition makes sure that we
1162bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // never attempt to emit a tentative definition if a real one
1163ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    // exists. A use may still exists, however, so we still may need
1164bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // to do a RAUW.
1165bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
116600549fcec0490b2daf27543e532f94adbb186063Chris Lattner    Init = EmitNullConstant(D->getType());
116700549fcec0490b2daf27543e532f94adbb186063Chris Lattner  } else {
11683b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel    Init = EmitConstantExpr(InitExpr, D->getType());
1169aa40454a14837c573f323e29269cc0b53f495a13Devang Patel    if (!Init) {
1170aa40454a14837c573f323e29269cc0b53f495a13Devang Patel      QualType T = InitExpr->getType();
1171aa40454a14837c573f323e29269cc0b53f495a13Devang Patel      if (D->getType()->isReferenceType())
1172aa40454a14837c573f323e29269cc0b53f495a13Devang Patel        T = D->getType();
1173bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1174bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      if (getLangOptions().CPlusPlus) {
1175bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        Init = EmitNullConstant(T);
1176bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        NonConstInit = true;
1177bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar      } else {
1178b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner        ErrorUnsupported(D, "static initializer");
11792b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1180b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      }
11811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    } else {
11822b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson      // We don't need an initializer, so remove the entry for the delayed
1183183700f494ec9b6701b6efe82bcb25f4c79ba561John McCall      // initializer position (just in case this entry was delayed).
11841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      if (getLangOptions().CPlusPlus)
11852b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson        DelayedCXXInitPosition.erase(D);
11862b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    }
11872b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  }
11881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
11892b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  const llvm::Type* InitType = Init->getType();
11902b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
11912b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson
11922b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  // Strip off a bitcast if we got one back.
11932b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
11941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
11951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump           // all zero index gep.
11962b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson           CE->getOpcode() == llvm::Instruction::GetElementPtr);
11972b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson    Entry = CE->getOperand(0);
119896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  }
11992b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson
1200ff75e1db95a53c7606e0bb114cf9adc59ab3d7f6Chris Lattner  // Entry is now either a Function or GlobalVariable.
1201d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
12029fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner
1203b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  // We have a definition after a declaration with the wrong type.
12041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // We must make a new GlobalVariable* and update everything that used OldGV
12050558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
12060558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // (which will be a definition).
12070558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  //
12080558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // This happens if there is a prototype for a global (e.g.
12090558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
12101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // "int x[10];"). This also happens when an initializer has a different type
12111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // from the type of the global (this happens with unions).
12120558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (GV == 0 ||
1213bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      GV->getType()->getElementType() != InitType ||
12141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
121542745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar
1216bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Move the old entry aside so that we'll create a new one.
12170558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry->setName(llvm::StringRef());
121834809507232bc4c3c4840c7d092c7440219fddafChris Lattner
121962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
122062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
122162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
122262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace all uses of the old global with the new global
122362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    llvm::Constant *NewPtrForOldDecl =
122462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
122562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
122662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
122734809507232bc4c3c4840c7d092c7440219fddafChris Lattner    // Erase the old global, since it is no longer used.
1228b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1229bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
12301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1231bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1232bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    SourceManager &SM = Context.getSourceManager();
1233bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    AddAnnotation(EmitAnnotateAttr(GV, AA,
12349fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner                              SM.getInstantiationLineNumber(D->getLocation())));
1235bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
12369fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner
12379fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  GV->setInitializer(Init);
12381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
123962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  // If it is safe to mark the global 'constant', do so now.
1240bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  GV->setConstant(false);
12411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!NonConstInit && DeclIsConstantGlobal(Context, D))
12423c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    GV->setConstant(true);
1243bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1244bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
12451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
124662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  // Set the llvm linkage type as appropriate.
1247bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::GlobalValue::LinkageTypes Linkage =
12481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetLLVMLinkageVarDefinition(D, GV);
12490558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  GV->setLinkage(Linkage);
1250bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  if (Linkage == llvm::GlobalVariable::CommonLinkage)
12511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // common vars aren't constant even if declared const.
12520558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    GV->setConstant(false);
1253bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1254219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  SetCommonAttributes(D, GV);
12556379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
12567c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Emit the initializer function if necessary.
12577c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  if (NonConstInit)
12581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    EmitCXXGlobalVarDeclInitFunc(D, GV);
125940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis
1260219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  // Emit global variable debug information.
126140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (CGDebugInfo *DI = getDebugInfo()) {
1262219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    DI->setLocation(D->getLocation());
1263bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    DI->EmitGlobalVariable(GV, D);
1264bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
1265bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
126640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis
1267bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattnerllvm::GlobalValue::LinkageTypes
1268bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris LattnerCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1269bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                           llvm::GlobalVariable *GV) {
12701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1271bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Linkage == GVA_Internal)
1272bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    return llvm::Function::InternalLinkage;
1273e013d685c6689ac7ae103ee88acf573422d1ed6aDaniel Dunbar  else if (D->hasAttr<DLLImportAttr>())
1274bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    return llvm::Function::DLLImportLinkage;
1275bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else if (D->hasAttr<DLLExportAttr>())
1276bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    return llvm::Function::DLLExportLinkage;
1277bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1278bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    if (GV->isConstant())
1279b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner      return llvm::GlobalVariable::WeakODRLinkage;
1280bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    else
1281bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner      return llvm::GlobalVariable::WeakAnyLinkage;
128296e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  } else if (Linkage == GVA_TemplateInstantiation ||
1283bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner             Linkage == GVA_ExplicitTemplateInstantiation)
1284bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // FIXME: It seems like we can provide more specific linkage here
12851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // (LinkOnceODR, WeakODR).
1286bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    return llvm::GlobalVariable::WeakAnyLinkage;
1287bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else if (!getLangOptions().CPlusPlus &&
1288bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
12891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump             D->getAttr<CommonAttr>()) &&
1290bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
1291bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner           !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1292bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Thread local vars aren't considered common linkage.
12931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    return llvm::GlobalVariable::CommonLinkage;
1294bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
1295bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  return llvm::GlobalVariable::ExternalLinkage;
1296bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
1297bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1298bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1299bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
13001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// existing call uses of the old function in the module, this adjusts them to
1301bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// call the new function directly.
1302bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner///
1303bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
1304bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
1305bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1306bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner/// run at -O0.
1307bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1308bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                      llvm::Function *NewFn) {
13091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // If we're redefining a global as a function, don't transform it.
13103c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1311bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (OldFn == 0) return;
1312bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1313bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  const llvm::Type *NewRetTy = NewFn->getReturnType();
13141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::SmallVector<llvm::Value*, 4> ArgList;
1315bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1316bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1317bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner       UI != E; ) {
1318bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
13197c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
13207c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
13217c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
132240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    llvm::CallSite CS(CI);
13237c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (!CI || !CS.isCallee(I)) continue;
13247c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
13256fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    // If the return types don't match exactly, and if the call isn't dead, then
13267c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // we can't transform this call.
13277c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (CI->getType() != NewRetTy && !CI->use_empty())
13287c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      continue;
13297c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
13301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // If the function was passed too few arguments, don't transform.  If extra
133140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis    // arguments were passed, we silently drop them.  If any of the types
13327c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // mismatch, we don't transform.
13337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    unsigned ArgNo = 0;
13347c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    bool DontTransform = false;
13357c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1336bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1337bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner      if (CS.arg_size() == ArgNo ||
1338b808c952bbff821dce727dd801a1098d64394f98Chris Lattner          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1339b808c952bbff821dce727dd801a1098d64394f98Chris Lattner        DontTransform = true;
134034771b594ca8cdf8cd2e40b27170efa4ed2833c5Daniel Dunbar        break;
134134771b594ca8cdf8cd2e40b27170efa4ed2833c5Daniel Dunbar      }
13423e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    }
13431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (DontTransform)
13443e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor      continue;
13451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
13463e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    // Okay, we can transform this.  Create the new call instruction and copy
13473e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    // over the required information.
13483e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
13493e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
13501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                     ArgList.end(), "", CI);
1351bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    ArgList.clear();
135286df27bbdbb98c39ec2184695c0561209f91beddChris Lattner    if (!NewCall->getType()->isVoidTy())
135386df27bbdbb98c39ec2184695c0561209f91beddChris Lattner      NewCall->takeName(CI);
135486df27bbdbb98c39ec2184695c0561209f91beddChris Lattner    NewCall->setAttributes(CI->getAttributes());
1355370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor    NewCall->setCallingConv(CI->getCallingConv());
13561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1357bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    // Finally, remove the old call, replacing any uses with the new one.
1358bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    if (!CI->use_empty())
1359b808c952bbff821dce727dd801a1098d64394f98Chris Lattner      CI->replaceAllUsesWith(NewCall);
1360e013d685c6689ac7ae103ee88acf573422d1ed6aDaniel Dunbar
136134771b594ca8cdf8cd2e40b27170efa4ed2833c5Daniel Dunbar    // Copy debug location attached to CI.
1362bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    if (!CI->getDebugLoc().isUnknown())
1363bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner      NewCall->setDebugLoc(CI->getDebugLoc());
13647acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner    CI->eraseFromParent();
13657acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner  }
13667acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
13677acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner
13687acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner
1369bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
13705f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
13715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
13720032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  // Get or create the prototype for the function.
13734e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
13745f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1375c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Strip off a bitcast if we got one back.
13760c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
13770c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman    assert(CE->getOpcode() == llvm::Instruction::BitCast);
13780032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson    Entry = CE->getOperand(0);
13794e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  }
13800c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman
13810c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman
138241ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
138341ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
13840032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson
13854e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner    // If the types mismatch then we have to rewrite the definition.
138641ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio    assert(OldFn->isDeclaration() &&
13877acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner           "Shouldn't replace non-declaration");
13881d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
13891d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    // F is the Function* for the one with the wrong type, we must make a new
13901d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    // Function* and update everything that used F (a declaration) with the new
139170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    // Function* (which will be a definition).
13921d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    //
13931d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    // This happens if there is a prototype for a function
1394df4eee9b035cc4b95b1ea72635e7429d06b0ecc8Daniel Dunbar    // (e.g. "int f()") and then a definition of a different type
13951d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    // (e.g. "int f(int x)").  Move the old function aside so that it
1396f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    // doesn't interfere with GetAddrOfFunction.
1397f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    OldFn->setName(llvm::StringRef());
1398f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1399f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
1400f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    // If this is an implementation of a function without a prototype, try to
1401f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    // replace any existing uses of the function (which may be calls) with uses
1402f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    // of the new function
14031d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    if (D->getType()->isFunctionNoProtoType()) {
14041d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
14051d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar      OldFn->removeDeadConstantUsers();
14061d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    }
14071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // Replace uses of F with the Function we will endow with a body.
14091d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    if (!Entry->use_empty()) {
14101d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar      llvm::Constant *NewPtrForOldDecl =
14111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
14121d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar      Entry->replaceAllUsesWith(NewPtrForOldDecl);
14131d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    }
14141d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
14151d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    // Ok, delete the old function now, which is dead.
14161d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    OldFn->eraseFromParent();
1417f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
1418f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    Entry = NewFn;
1419f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
1420e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff
14211d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // We need to set linkage and visibility on the function before
142270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // generating code for it because various parts of IR generation
14231d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // want to propagate this information down (e.g. to local static
142470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // declarations).
142570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  llvm::Function *Fn = cast<llvm::Function>(Entry);
142670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  setFunctionLinkage(D, Fn);
142770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
142870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
142970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  setGlobalVisibility(Fn, D);
143070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
143170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  CodeGenFunction(*this).GenerateCode(D, Fn);
143270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
143370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
143470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
143570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
143670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
143770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
143870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
143970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
144070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar}
1441434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar
1442434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbarvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1443434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
144470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  const AliasAttr *AA = D->getAttr<AliasAttr>();
14451d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  assert(AA && "Not an alias?");
144670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
14471d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringRef MangledName = getMangledName(GD);
14481d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
14491d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // If there is a definition in the module, then it wins over the alias.
14501d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // This is dubious, but allow it to be safe.  Just ignore the alias.
14511d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
14521d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (Entry && !Entry->isDeclaration())
14531d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return;
14541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
145570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
145670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
14571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Create a reference to the named value.  This ensures that it is emitted
14581d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // if a deferred decl.
14591d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::Constant *Aliasee;
14601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (isa<llvm::FunctionType>(DeclTy))
14610032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
14620032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  else
14633e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
14641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                    llvm::PointerType::getUnqual(DeclTy), 0);
14659d4a15fd3b85434c43ea27562793de63a793321aChris Lattner
1466c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Create the new alias itself, but don't set a name yet.
1467c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  llvm::GlobalValue *GA =
146896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    new llvm::GlobalAlias(Aliasee->getType(),
14691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                          llvm::Function::ExternalLinkage,
14709d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                          "", Aliasee, &getModule());
14713e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
14723e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  if (Entry) {
14733c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    assert(Entry->isDeclaration());
1474c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
14751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // If there is a declaration in the module, then we had an extern followed
1476e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    // by the alias, as in:
14773e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    //   extern int test6();
14781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    //   ...
1479e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    //   int test6() __attribute__((alias("test7")));
1480e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    //
14815add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    // Remove it and replace uses of it with the alias.
148244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    GA->takeName(Entry);
1483c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
14845add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
14851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                          Entry->getType()));
1486c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    Entry->eraseFromParent();
14873e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  } else {
14881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GA->setName(MangledName);
14895add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  }
14905add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1491c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Set attributes which are particular to an alias; this is a
14920032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  // specialization of the attributes which may be set on a global
1493a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  // variable/function.
1494278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  if (D->hasAttr<DLLExportAttr>()) {
149595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1496278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner      // The dllexport attribute is ignored for undefined symbols.
1497a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar      if (FD->hasBody())
1498a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
1499278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    } else {
150095b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner      GA->setLinkage(llvm::Function::DLLExportLinkage);
1501278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    }
1502278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  } else if (D->hasAttr<WeakAttr>() ||
1503278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner             D->hasAttr<WeakRefAttr>() ||
1504a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar             D->hasAttr<WeakImportAttr>()) {
150595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GA->setLinkage(llvm::Function::WeakAnyLinkage);
1506278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  }
1507a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
1508278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  SetCommonAttributes(D, GA);
15091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
1510278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
1511278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner/// getBuiltinLibFunction - Given a builtin id for a function like
1512a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar/// "__builtin_fabsf", return a Function* for "fabsf".
15138e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbarllvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1514a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar                                                  unsigned BuiltinID) {
1515a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
15161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1517a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar         "isn't a lib fn");
15185add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
15195add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  // Get the name, skip over the __builtin_ prefix (if necessary).
1520c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1521c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
15225add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    Name += 10;
15231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1524c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  const llvm::FunctionType *Ty =
152508e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
15261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
152895b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner}
15298e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
15308e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbarllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
15311d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                                            unsigned NumTys) {
15321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  return llvm::Intrinsic::getDeclaration(&getModule(),
15330c67829763b98bc670062b553897a851fab17401Anders Carlsson                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
1534c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
153545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
15366143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
15371e04976fc2611d8cc06986a81deed4c42183b870Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
15386143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar                         const StringLiteral *Literal,
15391e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar                         bool TargetIsLSB,
15401e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar                         bool &IsUTF16,
15411e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar                         unsigned &StringLength) {
15421e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  llvm::StringRef String = Literal->getString();
15431e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  unsigned NumBytes = String.size();
15441e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
15451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Check for simple case.
1546dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  if (!Literal->containsNonAsciiOrNull()) {
15471e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar    StringLength = NumBytes;
15481e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar    return Map.GetOrCreateValue(String);
15491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
1550dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner
1551dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  // Otherwise, convert the UTF8 literals into a byte string.
15521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
15531e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const UTF8 *FromPtr = (UTF8 *)String.data();
15541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  UTF16 *ToPtr = &ToBuf[0];
15551e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
15561e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
15571e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar                           &ToPtr, ToPtr + NumBytes,
15586143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar                           strictConversion);
15596143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
15606143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
15616143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
15626143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
15637eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  // Render the UTF-16 string into a byte array and convert to the target byte
15647eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  // order.
15657eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  //
15667eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  // FIXME: This isn't something we should need to do here.
15677eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  llvm::SmallString<128> AsBytes;
15687eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  AsBytes.reserve(StringLength * 2);
15697eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  for (unsigned i = 0; i != StringLength; ++i) {
15707eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman    unsigned short Val = ToBuf[i];
15716143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    if (TargetIsLSB) {
15726143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
1573eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner      AsBytes.push_back(Val >> 8);
1574eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    } else {
1575eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner      AsBytes.push_back(Val >> 8);
1576eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner      AsBytes.push_back(Val & 0xFF);
1577eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    }
1578eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  }
1579a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  // Append one extra null character, the second is automatically added by our
1580a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  // caller.
1581eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  AsBytes.push_back(0);
1582eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1583eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  IsUTF16 = true;
1584a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner  return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
15851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
158645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
15875fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbarllvm::Constant *
15885fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
15896143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  unsigned StringLength = 0;
15900032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  bool isUTF16 = false;
15910032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::StringMapEntry<llvm::Constant*> &Entry =
15921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
159345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                             getTargetData().isLittleEndian(),
15941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                             isUTF16, StringLength);
159595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner
15961c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson  if (llvm::Constant *C = Entry.getValue())
159745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner    return C;
159845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
15996143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  llvm::Constant *Zero =
16006143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
16016143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
16026143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
16036143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // If we don't already have it, get __CFConstantStringClassReference.
16046143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  if (!CFConstantStringClassRef) {
16056143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
16066143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    Ty = llvm::ArrayType::get(Ty, 0);
16075fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar    llvm::Constant *GV = CreateRuntimeVariable(Ty,
16085fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                           "__CFConstantStringClassReference");
16098e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    // Decay array -> ptr
16108e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    CFConstantStringClassRef =
16118e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
16128e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  }
161395b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner
16148e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  QualType CFTy = getContext().getCFConstantStringType();
16158e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
16168e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  const llvm::StructType *STy =
16175fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
16181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  std::vector<llvm::Constant*> Fields(4);
162095b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner
162145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Class pointer.
162245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  Fields[0] = CFConstantStringClassRef;
1623eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
162445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Flags.
162545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
16265fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
162745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner    llvm::ConstantInt::get(Ty, 0x07C8);
162845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
162945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // String pointer.
16306143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
16316143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
16326143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  llvm::GlobalValue::LinkageTypes Linkage;
16336143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  bool isConstant;
16345fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar  if (isUTF16) {
16355fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar    // FIXME: why do utf strings get "_" labels instead of "L" labels?
1636c9f29c61856ffb5f643cedbe87ac076f21a1381aChris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
16376143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar    // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
163841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // does make plain ascii ones writable.
1639af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    isConstant = true;
1640af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  } else {
16411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Linkage = llvm::GlobalValue::PrivateLinkage;
1642af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    isConstant = !Features.WritableStrings;
16431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
164417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis
1645af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  llvm::GlobalVariable *GV =
16461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1647af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                             ".str");
1648af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  GV->setUnnamedAddr(true);
1649af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  if (isUTF16) {
1650af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1651af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
1652af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
1653af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1654af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1655af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // String length.
165617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  Ty = getTypes().ConvertType(getContext().LongTy);
1657fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1658fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian
1659af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // The struct.
166017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  C = llvm::ConstantStruct::get(STy, Fields);
1661fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1662fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
1663af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                "_unnamed_cfstring_");
1664af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  if (const char *Sect = getContext().Target.getCFStringSection())
1665af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    GV->setSection(Sect);
1666af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  Entry.setValue(GV);
166791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
1668984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson  return GV;
166917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis}
1670984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
1671984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonllvm::Constant *
1672984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders CarlssonCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1673984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson  unsigned StringLength = 0;
167491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  bool isUTF16 = false;
167591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  llvm::StringMapEntry<llvm::Constant*> &Entry =
1676f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman    GetConstantCFStringEntry(CFConstantStringMap, Literal,
1677f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman                             getTargetData().isLittleEndian(),
167891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson                             isUTF16, StringLength);
167991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
168091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  if (llvm::Constant *C = Entry.getValue())
168191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return C;
168217945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis
168391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  llvm::Constant *Zero =
168491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
168591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  llvm::Constant *Zeros[] = { Zero, Zero };
168691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
168741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If we don't already have it, get _NSConstantStringClassReference.
168841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (!ConstantStringClassRef) {
168941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    std::string StringClass(getLangOptions().ObjCConstantStringClass);
169041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
169141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    Ty = llvm::ArrayType::get(Ty, 0);
169241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    llvm::Constant *GV;
169341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (StringClass.empty())
169441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      GV = CreateRuntimeVariable(Ty,
169516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor                                 Features.ObjCNonFragileABI ?
169616e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor                                 "OBJC_CLASS_$_NSConstantString" :
169716e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor                                 "_NSConstantStringClassReference");
16981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    else {
169941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      std::string str;
1700293361afd4199c92aabff9267fddea890943c586Anders Carlsson      if (Features.ObjCNonFragileABI)
17012b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson        str = "OBJC_CLASS_$_" + StringClass;
170241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      else
170316e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor        str = "_" + StringClass + "ClassReference";
170416e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      GV = CreateRuntimeVariable(Ty, str);
170516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    }
17061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // Decay array -> ptr
1707555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    ConstantStringClassRef =
1708555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1709555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson  }
171041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1711555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson  QualType NSTy = getContext().getNSConstantStringType();
171241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
171341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  const llvm::StructType *STy =
171495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  cast<llvm::StructType>(getTypes().ConvertType(NSTy));
171541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1716984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson  std::vector<llvm::Constant*> Fields(3);
171741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
17189cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  // Class pointer.
17199d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  Fields[0] = ConstantStringClassRef;
17209cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor
1721dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  // String pointer.
1722127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1723127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor
1724018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  llvm::GlobalValue::LinkageTypes Linkage;
17259cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  bool isConstant;
172695d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  if (isUTF16) {
172795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    // FIXME: why do utf strings get "_" labels instead of "L" labels?
172895d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    Linkage = llvm::GlobalValue::InternalLinkage;
172927ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
173027ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    // does make plain ascii ones writable.
173127ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    isConstant = true;
173236674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  } else {
173336674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    Linkage = llvm::GlobalValue::PrivateLinkage;
173436674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    isConstant = !Features.WritableStrings;
173536674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  }
173636674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
173795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  llvm::GlobalVariable *GV =
17381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
173938e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian                           ".str");
174041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  GV->setUnnamedAddr(true);
174141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (isUTF16) {
1742b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1743b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian    GV->setAlignment(Align.getQuantity());
174441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
1745285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
174641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1747b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  // String length.
174841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
174941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
175041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1751af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // The struct.
1752af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  C = llvm::ConstantStruct::get(STy, Fields);
175341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
175441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar                                llvm::GlobalVariable::PrivateLinkage, C,
175541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar                                "_unnamed_nsstring_");
1756af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  // FIXME. Fix section.
1757af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  if (const char *Sect =
1758af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar        Features.ObjCNonFragileABI
1759af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar          ? getContext().Target.getNSStringNonFragileABISection()
176041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar          : getContext().Target.getNSStringSection())
17611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GV->setSection(Sect);
176241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  Entry.setValue(GV);
176341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
176441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  return GV;
17656fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis}
176641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
176741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// GetStringForStringLiteral - Return the appropriate bytes for a
176841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// string literal, properly padded to match the literal type.
17691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1770305c658ebce84bb9833fc0e7675554656453b8e8Fariborz Jahanian  const ASTContext &Context = getContext();
177141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  const ConstantArrayType *CAT =
177241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    Context.getAsConstantArrayType(E->getType());
177391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  assert(CAT && "String isn't pointer or array!");
177491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
177541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // Resize the string to the right size.
177641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  uint64_t RealLen = CAT->getSize().getZExtValue();
177741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
177841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (E->isWide())
177941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
178041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
17811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  std::string Str = E->getString().str();
178241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  Str.resize(RealLen, '\0');
178341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
178441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  return Str;
178541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
178641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
178741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
178841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// constant array for the given string literal.
17891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *
17901eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1791f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // FIXME: This can be more efficient.
1792f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1793f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump  llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
179441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (S->isWide()) {
179541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    llvm::Type *DestTy =
179641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1797    C = llvm::ConstantExpr::getBitCast(C, DestTy);
1798  }
1799  return C;
1800}
1801
1802/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1803/// array for the given ObjCEncodeExpr node.
1804llvm::Constant *
1805CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1806  std::string Str;
1807  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1808
1809  return GetAddrOfConstantCString(Str);
1810}
1811
1812
1813/// GenerateWritableString -- Creates storage for a string literal.
1814static llvm::Constant *GenerateStringLiteral(const std::string &str,
1815                                             bool constant,
1816                                             CodeGenModule &CGM,
1817                                             const char *GlobalName) {
1818  // Create Constant for this string literal. Don't add a '\0'.
1819  llvm::Constant *C =
1820      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1821
1822  // Create a global variable for this string
1823  llvm::GlobalVariable *GV =
1824    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1825                             llvm::GlobalValue::PrivateLinkage,
1826                             C, GlobalName);
1827  GV->setUnnamedAddr(true);
1828  return GV;
1829}
1830
1831/// GetAddrOfConstantString - Returns a pointer to a character array
1832/// containing the literal. This contents are exactly that of the
1833/// given string, i.e. it will not be null terminated automatically;
1834/// see GetAddrOfConstantCString. Note that whether the result is
1835/// actually a pointer to an LLVM constant depends on
1836/// Feature.WriteableStrings.
1837///
1838/// The result has pointer to array type.
1839llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1840                                                       const char *GlobalName) {
1841  bool IsConstant = !Features.WritableStrings;
1842
1843  // Get the default prefix if a name wasn't specified.
1844  if (!GlobalName)
1845    GlobalName = ".str";
1846
1847  // Don't share any string literals if strings aren't constant.
1848  if (!IsConstant)
1849    return GenerateStringLiteral(str, false, *this, GlobalName);
1850
1851  llvm::StringMapEntry<llvm::Constant *> &Entry =
1852    ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1853
1854  if (Entry.getValue())
1855    return Entry.getValue();
1856
1857  // Create a global variable for this.
1858  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1859  Entry.setValue(C);
1860  return C;
1861}
1862
1863/// GetAddrOfConstantCString - Returns a pointer to a character
1864/// array containing the literal and a terminating '\-'
1865/// character. The result has pointer to array type.
1866llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1867                                                        const char *GlobalName){
1868  return GetAddrOfConstantString(str + '\0', GlobalName);
1869}
1870
1871/// EmitObjCPropertyImplementations - Emit information for synthesized
1872/// properties for an implementation.
1873void CodeGenModule::EmitObjCPropertyImplementations(const
1874                                                    ObjCImplementationDecl *D) {
1875  for (ObjCImplementationDecl::propimpl_iterator
1876         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1877    ObjCPropertyImplDecl *PID = *i;
1878
1879    // Dynamic is just for type-checking.
1880    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1881      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1882
1883      // Determine which methods need to be implemented, some may have
1884      // been overridden. Note that ::isSynthesized is not the method
1885      // we want, that just indicates if the decl came from a
1886      // property. What we want to know is if the method is defined in
1887      // this implementation.
1888      if (!D->getInstanceMethod(PD->getGetterName()))
1889        CodeGenFunction(*this).GenerateObjCGetter(
1890                                 const_cast<ObjCImplementationDecl *>(D), PID);
1891      if (!PD->isReadOnly() &&
1892          !D->getInstanceMethod(PD->getSetterName()))
1893        CodeGenFunction(*this).GenerateObjCSetter(
1894                                 const_cast<ObjCImplementationDecl *>(D), PID);
1895    }
1896  }
1897}
1898
1899/// EmitObjCIvarInitializations - Emit information for ivar initialization
1900/// for an implementation.
1901void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1902  if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1903    return;
1904  DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1905  assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1906  IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1907  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1908  ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1909                                                  D->getLocation(),
1910                                                  D->getLocation(), cxxSelector,
1911                                                  getContext().VoidTy, 0,
1912                                                  DC, true, false, true, false,
1913                                                  ObjCMethodDecl::Required);
1914  D->addInstanceMethod(DTORMethod);
1915  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1916
1917  II = &getContext().Idents.get(".cxx_construct");
1918  cxxSelector = getContext().Selectors.getSelector(0, &II);
1919  // The constructor returns 'self'.
1920  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1921                                                D->getLocation(),
1922                                                D->getLocation(), cxxSelector,
1923                                                getContext().getObjCIdType(), 0,
1924                                                DC, true, false, true, false,
1925                                                ObjCMethodDecl::Required);
1926  D->addInstanceMethod(CTORMethod);
1927  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1928
1929
1930}
1931
1932/// EmitNamespace - Emit all declarations in a namespace.
1933void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1934  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1935       I != E; ++I)
1936    EmitTopLevelDecl(*I);
1937}
1938
1939// EmitLinkageSpec - Emit all declarations in a linkage spec.
1940void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1941  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1942      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1943    ErrorUnsupported(LSD, "linkage spec");
1944    return;
1945  }
1946
1947  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1948       I != E; ++I)
1949    EmitTopLevelDecl(*I);
1950}
1951
1952/// EmitTopLevelDecl - Emit code for a single top level declaration.
1953void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1954  // If an error has occurred, stop code generation, but continue
1955  // parsing and semantic analysis (to ensure all warnings and errors
1956  // are emitted).
1957  if (Diags.hasErrorOccurred())
1958    return;
1959
1960  // Ignore dependent declarations.
1961  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1962    return;
1963
1964  switch (D->getKind()) {
1965  case Decl::CXXConversion:
1966  case Decl::CXXMethod:
1967  case Decl::Function:
1968    // Skip function templates
1969    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1970      return;
1971
1972    EmitGlobal(cast<FunctionDecl>(D));
1973    break;
1974
1975  case Decl::Var:
1976    EmitGlobal(cast<VarDecl>(D));
1977    break;
1978
1979  // C++ Decls
1980  case Decl::Namespace:
1981    EmitNamespace(cast<NamespaceDecl>(D));
1982    break;
1983    // No code generation needed.
1984  case Decl::UsingShadow:
1985  case Decl::Using:
1986  case Decl::UsingDirective:
1987  case Decl::ClassTemplate:
1988  case Decl::FunctionTemplate:
1989  case Decl::NamespaceAlias:
1990    break;
1991  case Decl::CXXConstructor:
1992    // Skip function templates
1993    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1994      return;
1995
1996    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1997    break;
1998  case Decl::CXXDestructor:
1999    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2000    break;
2001
2002  case Decl::StaticAssert:
2003    // Nothing to do.
2004    break;
2005
2006  // Objective-C Decls
2007
2008  // Forward declarations, no (immediate) code generation.
2009  case Decl::ObjCClass:
2010  case Decl::ObjCForwardProtocol:
2011  case Decl::ObjCInterface:
2012    break;
2013
2014    case Decl::ObjCCategory: {
2015      ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2016      if (CD->IsClassExtension() && CD->hasSynthBitfield())
2017        Context.ResetObjCLayout(CD->getClassInterface());
2018      break;
2019    }
2020
2021
2022  case Decl::ObjCProtocol:
2023    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2024    break;
2025
2026  case Decl::ObjCCategoryImpl:
2027    // Categories have properties but don't support synthesize so we
2028    // can ignore them here.
2029    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2030    break;
2031
2032  case Decl::ObjCImplementation: {
2033    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2034    if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2035      Context.ResetObjCLayout(OMD->getClassInterface());
2036    EmitObjCPropertyImplementations(OMD);
2037    EmitObjCIvarInitializations(OMD);
2038    Runtime->GenerateClass(OMD);
2039    break;
2040  }
2041  case Decl::ObjCMethod: {
2042    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2043    // If this is not a prototype, emit the body.
2044    if (OMD->getBody())
2045      CodeGenFunction(*this).GenerateObjCMethod(OMD);
2046    break;
2047  }
2048  case Decl::ObjCCompatibleAlias:
2049    // compatibility-alias is a directive and has no code gen.
2050    break;
2051
2052  case Decl::LinkageSpec:
2053    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2054    break;
2055
2056  case Decl::FileScopeAsm: {
2057    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2058    llvm::StringRef AsmString = AD->getAsmString()->getString();
2059
2060    const std::string &S = getModule().getModuleInlineAsm();
2061    if (S.empty())
2062      getModule().setModuleInlineAsm(AsmString);
2063    else
2064      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2065    break;
2066  }
2067
2068  default:
2069    // Make sure we handled everything we should, every other kind is a
2070    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2071    // function. Need to recode Decl::Kind to do that easily.
2072    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2073  }
2074}
2075
2076/// Turns the given pointer into a constant.
2077static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2078                                          const void *Ptr) {
2079  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2080  const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2081  return llvm::ConstantInt::get(i64, PtrInt);
2082}
2083
2084static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2085                                   llvm::NamedMDNode *&GlobalMetadata,
2086                                   GlobalDecl D,
2087                                   llvm::GlobalValue *Addr) {
2088  if (!GlobalMetadata)
2089    GlobalMetadata =
2090      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2091
2092  // TODO: should we report variant information for ctors/dtors?
2093  llvm::Value *Ops[] = {
2094    Addr,
2095    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2096  };
2097  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2098}
2099
2100/// Emits metadata nodes associating all the global values in the
2101/// current module with the Decls they came from.  This is useful for
2102/// projects using IR gen as a subroutine.
2103///
2104/// Since there's currently no way to associate an MDNode directly
2105/// with an llvm::GlobalValue, we create a global named metadata
2106/// with the name 'clang.global.decl.ptrs'.
2107void CodeGenModule::EmitDeclMetadata() {
2108  llvm::NamedMDNode *GlobalMetadata = 0;
2109
2110  // StaticLocalDeclMap
2111  for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2112         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2113       I != E; ++I) {
2114    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2115    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2116  }
2117}
2118
2119/// Emits metadata nodes for all the local variables in the current
2120/// function.
2121void CodeGenFunction::EmitDeclMetadata() {
2122  if (LocalDeclMap.empty()) return;
2123
2124  llvm::LLVMContext &Context = getLLVMContext();
2125
2126  // Find the unique metadata ID for this name.
2127  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2128
2129  llvm::NamedMDNode *GlobalMetadata = 0;
2130
2131  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2132         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2133    const Decl *D = I->first;
2134    llvm::Value *Addr = I->second;
2135
2136    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2137      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2138      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2139    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2140      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2141      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2142    }
2143  }
2144}
2145
2146///@name Custom Runtime Function Interfaces
2147///@{
2148//
2149// FIXME: These can be eliminated once we can have clients just get the required
2150// AST nodes from the builtin tables.
2151
2152llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2153  if (BlockObjectDispose)
2154    return BlockObjectDispose;
2155
2156  // If we saw an explicit decl, use that.
2157  if (BlockObjectDisposeDecl) {
2158    return BlockObjectDispose = GetAddrOfFunction(
2159      BlockObjectDisposeDecl,
2160      getTypes().GetFunctionType(BlockObjectDisposeDecl));
2161  }
2162
2163  // Otherwise construct the function by hand.
2164  const llvm::FunctionType *FTy;
2165  std::vector<const llvm::Type*> ArgTys;
2166  const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2167  ArgTys.push_back(PtrToInt8Ty);
2168  ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2169  FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2170  return BlockObjectDispose =
2171    CreateRuntimeFunction(FTy, "_Block_object_dispose");
2172}
2173
2174llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2175  if (BlockObjectAssign)
2176    return BlockObjectAssign;
2177
2178  // If we saw an explicit decl, use that.
2179  if (BlockObjectAssignDecl) {
2180    return BlockObjectAssign = GetAddrOfFunction(
2181      BlockObjectAssignDecl,
2182      getTypes().GetFunctionType(BlockObjectAssignDecl));
2183  }
2184
2185  // Otherwise construct the function by hand.
2186  const llvm::FunctionType *FTy;
2187  std::vector<const llvm::Type*> ArgTys;
2188  const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2189  ArgTys.push_back(PtrToInt8Ty);
2190  ArgTys.push_back(PtrToInt8Ty);
2191  ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2192  FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2193  return BlockObjectAssign =
2194    CreateRuntimeFunction(FTy, "_Block_object_assign");
2195}
2196
2197llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2198  if (NSConcreteGlobalBlock)
2199    return NSConcreteGlobalBlock;
2200
2201  // If we saw an explicit decl, use that.
2202  if (NSConcreteGlobalBlockDecl) {
2203    return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2204      NSConcreteGlobalBlockDecl,
2205      getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2206  }
2207
2208  // Otherwise construct the variable by hand.
2209  return NSConcreteGlobalBlock = CreateRuntimeVariable(
2210    PtrToInt8Ty, "_NSConcreteGlobalBlock");
2211}
2212
2213llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2214  if (NSConcreteStackBlock)
2215    return NSConcreteStackBlock;
2216
2217  // If we saw an explicit decl, use that.
2218  if (NSConcreteStackBlockDecl) {
2219    return NSConcreteStackBlock = GetAddrOfGlobalVar(
2220      NSConcreteStackBlockDecl,
2221      getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2222  }
2223
2224  // Otherwise construct the variable by hand.
2225  return NSConcreteStackBlock = CreateRuntimeVariable(
2226    PtrToInt8Ty, "_NSConcreteStackBlock");
2227}
2228
2229///@}
2230