CodeGenModule.cpp revision f7e903d7a30891083420c07ebeed281726a101d6
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"
173d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman#include "CodeGenTBAA.h"
180dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar#include "CGCall.h"
194c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall#include "CGCXXABI.h"
20af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGObjCRuntime.h"
2182d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov#include "TargetInfo.h"
2206057cef0bcd7804e80f3ce2bbe352178396c715Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
235f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
24687cc4a850b59116efee061018f0d8df50728b82Ken Dyck#include "clang/AST/CharUnits.h"
25c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2621ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
27af896897f7485176f43d40c4adced7efb0fb2b06Douglas Gregor#include "clang/AST/DeclTemplate.h"
2814110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne#include "clang/AST/Mangle.h"
291a5e0d7f18485e4fb958f96dcddff3e4486a4069Anders Carlsson#include "clang/AST/RecordLayout.h"
301b63e4f732dbc73d90abf886b4d21f8e3a165f6dChris Lattner#include "clang/Basic/Builtins.h"
312c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/Basic/Diagnostic.h"
328bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
335f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
34e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff#include "clang/Basic/ConvertUTF.h"
35ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman#include "llvm/CallingConv.h"
36bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner#include "llvm/Module.h"
375f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Intrinsics.h"
38d5b8902c0329d80a216803b58dc3b689349a0c11Chris Lattner#include "llvm/LLVMContext.h"
396374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall#include "llvm/ADT/Triple.h"
40c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola#include "llvm/Target/Mangler.h"
4120ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov#include "llvm/Target/TargetData.h"
426ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif#include "llvm/Support/CallSite.h"
4378f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner#include "llvm/Support/ErrorHandling.h"
445f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
455f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
465f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
47f16aa103d3afd42fbca2ab346f191bf745cec092John McCallstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  switch (CGM.getContext().Target.getCXXABI()) {
49f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
52f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  }
53f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
54f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  llvm_unreachable("invalid C++ ABI kind");
55f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  return *CreateItaniumCXXABI(CGM);
56f16aa103d3afd42fbca2ab346f191bf745cec092John McCall}
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
585f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
592811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
60468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall                             llvm::Module &M, const llvm::TargetData &TD,
61468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall                             Diagnostic &diags)
62d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
63468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
64f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    ABI(createCXXABI(*this)),
65f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
663d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    TBAA(0),
67aa11289f754d220c9c155b68a4f84cdcfcefef6aDevang Patel    VTables(*this), Runtime(0),
684c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    CFConstantStringClassRef(0), ConstantStringClassRef(0),
69673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    VMContext(M.getContext()),
70754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
71673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
72754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
73d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockObjectAssign(0), BlockObjectDispose(0),
74d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockDescriptorType(0), GenericBlockLiteralType(0) {
7560be607e5d71627bf3dab8f51c3fdca74267c692David Chisnall  if (Features.ObjC1)
7660be607e5d71627bf3dab8f51c3fdca74267c692David Chisnall     createObjCRuntime();
77e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
783d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  // Enable TBAA unless it's suppressed.
793d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
800b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman    TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
810b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman                           ABI.getMangleContext());
823d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
83e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta  // If debug info generation is enabled, create the CGDebugInfo object.
8420f12a20ba9cfa6f8d53c8304e24f50903c45184Anders Carlsson  DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
85d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
86d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  Block.GlobalUniqueCount = 0;
875936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
885936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  // Initialize the type cache.
895936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  llvm::LLVMContext &LLVMContext = M.getContext();
905936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8Ty  = llvm::Type::getInt8Ty(LLVMContext);
915936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int32Ty  = llvm::Type::getInt32Ty(LLVMContext);
925936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int64Ty  = llvm::Type::getInt64Ty(LLVMContext);
935936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  PointerWidthInBits = C.Target.getPointerWidth(0);
9434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  PointerAlignInBytes =
9534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
965936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
975936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
985936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8PtrTy = Int8Ty->getPointerTo(0);
995936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1002b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
1012b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
1022b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
103815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete Runtime;
104f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  delete &ABI;
1054376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman  delete TBAA;
106815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
107815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
108815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
1090d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnallvoid CodeGenModule::createObjCRuntime() {
1100d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  if (!Features.NeXTRuntime)
1110d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall    Runtime = CreateGNUObjCRuntime(*this);
1120d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  else
1130d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall    Runtime = CreateMacObjCRuntime(*this);
1140d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall}
1150d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
116815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
11782227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
1186c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  EmitCXXGlobalInitFunc();
119efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar  EmitCXXGlobalDtorFunc();
120208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar  if (Runtime)
121208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
122208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
1236bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
1246bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
125532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  EmitAnnotations();
1260269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
127744016dde06fcffd50931e94a98c850f8b12cd87John McCall
128b25938303de0976b9f189363d43033e5788e3d36John McCall  SimplifyPersonality();
129b25938303de0976b9f189363d43033e5788e3d36John McCall
130744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (getCodeGenOpts().EmitDeclMetadata)
131744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitDeclMetadata();
132f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
133f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
134e80d56771736c85fd8365c394a6731923b17e91dDevang Patelvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
135e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  // Make sure that this type is translated.
136e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  Types.UpdateCompletedType(TD);
137e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  if (DebugInfo)
138e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    DebugInfo->UpdateCompletedType(TD);
139e80d56771736c85fd8365c394a6731923b17e91dDevang Patel}
140e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
1413d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
1423d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!TBAA)
1433d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return 0;
1443d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  return TBAA->getTBAAInfo(QTy);
1453d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1463d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1473d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
1483d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman                                        llvm::MDNode *TBAAInfo) {
1493d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
1503d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1513d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1526374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCallbool CodeGenModule::isTargetDarwin() const {
1536374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall  return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
1546374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall}
1556374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
15632096695c76033a6b0b1747c439f7378a11e8312John McCallvoid CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
15732096695c76033a6b0b1747c439f7378a11e8312John McCall  unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
15832096695c76033a6b0b1747c439f7378a11e8312John McCall  getDiags().Report(Context.getFullLoc(loc), diagID);
15932096695c76033a6b0b1747c439f7378a11e8312John McCall}
16032096695c76033a6b0b1747c439f7378a11e8312John McCall
161488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
1622c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
16390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
16490df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
16590df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
16690df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
1671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
16856b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
1692c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
1700a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
1710a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
1722c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
17358c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
174488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
175c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
17690df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
17790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
17890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
17990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
1801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
18156b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
182c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
1830a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
184c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
185c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
1861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
1870ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson                                        const NamedDecl *D) const {
18804d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
189df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
1907e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1916ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
1927e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
1936ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
194af14603ca61757cf4361b583b45639a04c57e651John McCall  // Set visibility for definitions.
195af14603ca61757cf4361b583b45639a04c57e651John McCall  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
196071d3af0de273b1079d79f7f979264f28d567373Rafael Espindola  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
197071d3af0de273b1079d79f7f979264f28d567373Rafael Espindola    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1987cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
1997cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
200cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// Set the symbol visibility of type information (vtable and RTTI)
201cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// associated with the given type.
202cbfe50224b19119e759802bd0c1463269dffd09eJohn McCallvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
203cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                      const CXXRecordDecl *RD,
204fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson                                      TypeVisibilityKind TVK) const {
2050ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(GV, RD);
206cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
207279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (!CodeGenOpts.HiddenWeakVTables)
208279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    return;
209279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall
2109a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  // We never want to drop the visibility for RTTI names.
2119a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  if (TVK == TVK_ForRTTIName)
2129a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    return;
2139a86a137b0872bad25161fb3408a71d919638757Anders Carlsson
214cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We want to drop the visibility to hidden for weak type symbols.
215cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // This isn't possible if there might be unresolved references
216cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // elsewhere that rely on this symbol being visible.
217cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2187a536907da776bdc47a704e7cafd641e8150e653John McCall  // This should be kept roughly in sync with setThunkVisibility
2197a536907da776bdc47a704e7cafd641e8150e653John McCall  // in CGVTables.cpp.
2207a536907da776bdc47a704e7cafd641e8150e653John McCall
221cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Preconditions.
222f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
223cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
224cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
225cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
226cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Don't override an explicit visibility attribute.
2274421d2b341d041df44013769f23c306308bbab83Douglas Gregor  if (RD->getExplicitVisibility())
228cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
229cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
230cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  switch (RD->getTemplateSpecializationKind()) {
231cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We have to disable the optimization if this is an EI definition
232cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // because there might be EI declarations in other shared objects.
233cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDefinition:
234cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDeclaration:
235cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
236cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2377a536907da776bdc47a704e7cafd641e8150e653John McCall  // Every use of a non-template class's type information has to emit it.
238cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_Undeclared:
239cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
240cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2417a536907da776bdc47a704e7cafd641e8150e653John McCall  // In theory, implicit instantiations can ignore the possibility of
2427a536907da776bdc47a704e7cafd641e8150e653John McCall  // an explicit instantiation declaration because there necessarily
2437a536907da776bdc47a704e7cafd641e8150e653John McCall  // must be an EI definition somewhere with default visibility.  In
2447a536907da776bdc47a704e7cafd641e8150e653John McCall  // practice, it's possible to have an explicit instantiation for
2457a536907da776bdc47a704e7cafd641e8150e653John McCall  // an arbitrary template class, and linkers aren't necessarily able
2467a536907da776bdc47a704e7cafd641e8150e653John McCall  // to deal with mixed-visibility symbols.
2477a536907da776bdc47a704e7cafd641e8150e653John McCall  case TSK_ExplicitSpecialization:
248cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ImplicitInstantiation:
249279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    if (!CodeGenOpts.HiddenWeakTemplateVTables)
2507a536907da776bdc47a704e7cafd641e8150e653John McCall      return;
251cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
252cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  }
253cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
254cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // If there's a key function, there may be translation units
255cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // that don't have the key function's definition.  But ignore
256cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // this if we're emitting RTTI under -fno-rtti.
257fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
258cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    if (Context.getKeyFunction(RD))
259cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      return;
260fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  }
261cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
262cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Otherwise, drop the visibility to hidden.
263cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
264b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  GV->setUnnamedAddr(true);
265cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall}
266cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
267793a990774826a0c20b0da66cec0991badfb8b63Anders Carlssonllvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
268793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
269793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
270793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
271793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (!Str.empty())
272793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
273793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
2744c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
275793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    IdentifierInfo *II = ND->getIdentifier();
276793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(II && "Attempt to mangle unnamed decl.");
277793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
278793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Str = II->getName();
279793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
280793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
281793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
282793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  llvm::SmallString<256> Buffer;
283c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer);
284793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
285c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
286793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
287c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
288793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
289c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleBlock(BD, Out);
290793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else
291c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleName(ND, Out);
292793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
293793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // Allocate space for the mangled name.
294c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  Out.flush();
295793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  size_t Length = Buffer.size();
296793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  char *Name = MangledNamesAllocator.Allocate<char>(Length);
297793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  std::copy(Buffer.begin(), Buffer.end(), Name);
298793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
299793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  Str = llvm::StringRef(Name, Length);
300793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
301793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return Str;
302793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
303793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
30414110477887e3dc168ffc6c191e72d705051f99ePeter Collingbournevoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
30514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne                                        const BlockDecl *BD) {
30614110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  MangleContext &MangleCtx = getCXXABI().getMangleContext();
30714110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  const Decl *D = GD.getDecl();
308c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer.getBuffer());
30914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  if (D == 0)
310c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleGlobalBlock(BD, Out);
31114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
312c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
31314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
314c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
31514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else
316c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
3179a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson}
3189a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson
319f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
320f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return getModule().getNamedValue(Name);
3215f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
3225f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
3236d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
3246d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
3256bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
32649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3276bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
3286d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3296d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
3306bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
3316bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
3326bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
33349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3346bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
3356bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
3366bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3376bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
3386bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
3396bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  llvm::FunctionType* CtorFTy =
34015f6765f6efd24bec4ec6f54e282c14193ef4014Benjamin Kramer    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
34196e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
3426bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3436bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
3441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::StructType* CtorStructTy =
3451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
34696e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                          llvm::PointerType::getUnqual(CtorFTy), NULL);
3476bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3486bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
3496bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  std::vector<llvm::Constant*> Ctors;
3506bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
3516bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    std::vector<llvm::Constant*> S;
3521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
3530032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson                I->second, false));
3543c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
35508e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
3566bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
3576bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3586bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
35996e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
3601c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    new llvm::GlobalVariable(TheModule, AT, false,
361572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
3627db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(AT, Ctors),
3631c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             GlobalName);
3646d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
3656d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3666d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
367532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begemanvoid CodeGenModule::EmitAnnotations() {
368532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  if (Annotations.empty())
369532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman    return;
370532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
371532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  // Create a new global variable for the ConstantStruct in the Module.
372532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::Constant *Array =
37396e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
374532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                                                Annotations.size()),
375532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           Annotations);
3761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *gv =
3771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  new llvm::GlobalVariable(TheModule, Array->getType(), false,
3781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                           llvm::GlobalValue::AppendingLinkage, Array,
3791c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                           "llvm.global.annotations");
380532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  gv->setSection("llvm.metadata");
381532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman}
382532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
383d46f98573ba104eda102dd3224b2dca69f1c6336John McCallllvm::GlobalValue::LinkageTypes
384d46f98573ba104eda102dd3224b2dca69f1c6336John McCallCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
38590e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
3867c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
387f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_Internal)
388d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::InternalLinkage;
389f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
390f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<DLLExportAttr>())
391d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::DLLExportLinkage;
392f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
393f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<WeakAttr>())
394d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::WeakAnyLinkage;
395f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
396f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C99 mode, 'inline' functions are guaranteed to have a strong
397f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition somewhere else, so we can use available_externally linkage.
398f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_C99Inline)
399fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian    return llvm::Function::AvailableExternallyLinkage;
400f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
401f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C++, the compiler has to emit a definition in every translation unit
402f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // that references the function.  We should use linkonce_odr because
403f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // a) if all references in this translation unit are optimized away, we
404f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // don't need to codegen it.  b) if the function persists, it needs to be
405f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // merged with other definitions. c) C++ has the ODR, so we know the
406f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition is dependable.
407f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
408142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    return !Context.getLangOptions().AppleKext
409142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::LinkOnceODRLinkage
410142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
411f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
412f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // An explicit instantiation of a template has weak linkage, since
413f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // explicit instantiations can occur in multiple translation units
414f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // and must all be equivalent. However, we are not allowed to
415f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // throw away these explicit instantiations.
416f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_ExplicitTemplateInstantiation)
417142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    return !Context.getLangOptions().AppleKext
418142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::WeakODRLinkage
419142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
420f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
421f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // Otherwise, we have strong external linkage.
422f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  assert(Linkage == GVA_StrongExternal);
423f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  return llvm::Function::ExternalLinkage;
424d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
425d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
426d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
427d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// SetFunctionDefinitionAttributes - Set attributes for a global.
428d46f98573ba104eda102dd3224b2dca69f1c6336John McCall///
429d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// FIXME: This is currently only done for aliases and functions, but not for
430d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// variables (these details are set in EmitGlobalVarDefinition for variables).
431d46f98573ba104eda102dd3224b2dca69f1c6336John McCallvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
432d46f98573ba104eda102dd3224b2dca69f1c6336John McCall                                                    llvm::GlobalValue *GV) {
4337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
434d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
435d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
4367dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
4371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              const CGFunctionInfo &Info,
4387dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
439ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  unsigned CallingConv;
440761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
441ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList, CallingConv);
442761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
443ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar                                          AttributeList.size()));
444ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
445f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
446f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
4477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
4487c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
44974ac74ae244c501027924c99f2a33559a1e23b53Daniel Dunbar  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
4501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->addFnAttr(llvm::Attribute::NoUnwind);
451af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
45240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<AlwaysInlineAttr>())
453af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar    F->addFnAttr(llvm::Attribute::AlwaysInline);
4541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
455dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar  if (D->hasAttr<NakedAttr>())
456dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar    F->addFnAttr(llvm::Attribute::Naked);
457dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar
4581feade8e520be483293dbf55eb57a51720899589Mike Stump  if (D->hasAttr<NoInlineAttr>())
45981ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson    F->addFnAttr(llvm::Attribute::NoInline);
460f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
461c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
462c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    F->setUnnamedAddr(true);
463c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
464fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson  if (Features.getStackProtectorMode() == LangOptions::SSPOn)
465fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtect);
466fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson  else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
467fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtectReq);
468fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson
469cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
470cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  if (alignment)
471cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    F->setAlignment(alignment);
472cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt
473fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  // C++ ABI requires 2-byte alignment for member functions.
474bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
475bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump    F->setAlignment(2);
476f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
477f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
4781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::SetCommonAttributes(const Decl *D,
4797c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
480934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
481934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson    setGlobalVisibility(GV, ND);
4821fb0caaa7bef765b85972274e3b434af2572c141John McCall  else
4831fb0caaa7bef765b85972274e3b434af2572c141John McCall    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
4847c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
48540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<UsedAttr>())
4867c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
4877c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
48840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
4897c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
49082d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov
49182d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
4927c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
4937c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
4940e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
4950e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
4960e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
4970e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
4980e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
4997c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5007c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
5017c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5020e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
503f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
504f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
505b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
506c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          llvm::Function *F,
507c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          bool IsIncompleteFunction) {
5080ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  if (unsigned IID = F->getIntrinsicID()) {
5090ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // If this is an intrinsic function, set the function's attributes
5100ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // to the intrinsic's attributes.
5110ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
5120ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    return;
5130ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  }
5140ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
515b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
516b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
517c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  if (!IsIncompleteFunction)
518b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
5191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5207c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
5217c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
5221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
52340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (FD->hasAttr<DLLImportAttr>()) {
5247c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
5251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (FD->hasAttr<WeakAttr>() ||
5260a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             FD->isWeakImported()) {
5277c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
5281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // separate linkage types for this.
5297c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
5307c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
5311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->setLinkage(llvm::Function::ExternalLinkage);
532af14603ca61757cf4361b583b45639a04c57e651John McCall
533af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
534af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
535af14603ca61757cf4361b583b45639a04c57e651John McCall      F->setVisibility(GetLLVMVisibility(LV.visibility()));
536af14603ca61757cf4361b583b45639a04c57e651John McCall    }
5377c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
5387c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
53940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
5407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
541219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
542219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
5430269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
5441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!GV->isDeclaration() &&
5450269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
54635f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
5470269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
5480269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5490269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
5500269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
551ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  if (LLVMUsed.empty())
5520269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
5530269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5543c0ef8cc0dc246bd3083e8cdd63005e8873d36d2Benjamin Kramer  const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
5551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
55635f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
55735f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  std::vector<llvm::Constant*> UsedArray;
55835f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
55935f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
5601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    UsedArray[i] =
5611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
562a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Anderson                                      i8PTy);
56335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
5641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
565c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  if (UsedArray.empty())
566c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    return;
56796e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
5681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
5701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), ATy, false,
5710269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
5727db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(ATy, UsedArray),
5731c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             "llvm.used");
5740269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5750269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
5760269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
5770269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5780269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
57967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
58067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
58167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // for a static function, iterate until no  changes are made.
582bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
583046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
584046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    if (!DeferredVTables.empty()) {
585046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      const CXXRecordDecl *RD = DeferredVTables.back();
586046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      DeferredVTables.pop_back();
587046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      getVTables().GenerateClassData(getVTableLinkage(RD), RD);
588bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola      continue;
589bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    }
590bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
5912a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
59267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
59367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
594c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // Check to see if we've already emitted this.  This is necessary
595c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // for a couple of reasons: first, decls can end up in the
596c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // deferred-decls queue multiple times, and second, decls can end
597c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // up with definitions in unusual ways (e.g. by an extern inline
598c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // function acquiring a strong function redefinition).  Just
599c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // ignore these cases.
600c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    //
601c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // TODO: That said, looking this up multiple times is very wasteful.
6029a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    llvm::StringRef Name = getMangledName(D);
603f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
60467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
6051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
60667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
60767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
6081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
609c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
610c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // purposes an alias counts as a definition.
611c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (isa<llvm::GlobalAlias>(CGRef))
612c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      continue;
613c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
61467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
61567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
61667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
6175f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
6185f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
6191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
6208bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// annotation information for a given GlobalValue.  The annotation struct is
6211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
6221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// GlobalValue being annotated.  The second field is the constant string
6231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// created from the AnnotateAttr's annotation.  The third field is a constant
6248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// string containing the name of the translation unit.  The fourth field is
6258bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// the line number in the file of the annotated value declaration.
6268bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///
6278bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// FIXME: this does not unique the annotation string constants, as llvm-gcc
6288bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///        appears to.
6298bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///
6301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
6318bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
6328bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                unsigned LineNo) {
6338bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Module *M = &getModule();
6348bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
6358bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // get [N x i8] constants for the annotation string, and the filename string
6368bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // which are the 2nd and 3rd elements of the global annotation structure.
6373c0ef8cc0dc246bd3083e8cdd63005e8873d36d2Benjamin Kramer  const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
6381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
6390032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson                                                  AA->getAnnotation(), true);
6400032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
6410032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson                                                  M->getModuleIdentifier(),
6428bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                  true);
6438bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
6448bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // Get the two global values corresponding to the ConstantArrays we just
6458bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // created to hold the bytes of the strings.
6461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *annoGV =
64795b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    new llvm::GlobalVariable(*M, anno->getType(), false,
64895b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                             llvm::GlobalValue::PrivateLinkage, anno,
64995b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                             GV->getName());
6508bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // translation unit name string, emitted into the llvm.metadata section.
6518bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::GlobalValue *unitGV =
65295b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    new llvm::GlobalVariable(*M, unit->getType(), false,
6531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                             llvm::GlobalValue::PrivateLinkage, unit,
65495b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                             ".str");
655d3d4e1ee398748468cbaaddb3b0af5953f043803Rafael Espindola  unitGV->setUnnamedAddr(true);
6568bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
65757d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
6588bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
6593c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    llvm::ConstantExpr::getBitCast(GV, SBP),
6603c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    llvm::ConstantExpr::getBitCast(annoGV, SBP),
6613c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    llvm::ConstantExpr::getBitCast(unitGV, SBP),
6620032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
6638bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
66447a434ff3d49e7906eda88e8e8242e4297725b32Owen Anderson  return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
6658bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
6668bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
667a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidisbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
66890e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  // Never defer when EmitAllDecls is specified.
66990e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  if (Features.EmitAllDecls)
670a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    return false;
6710b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor
6724ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis  return !getContext().DeclMustBeEmitted(Global);
67373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
67473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
6756a836706c40a31c716952b74785102c90fd6afa7Rafael Espindolallvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
6766a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const AliasAttr *AA = VD->getAttr<AliasAttr>();
6776a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  assert(AA && "No alias?");
6786a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
6796a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
6806a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
6816a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // See if there is already something with the target's name in the module.
682f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
6836a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
6846a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  llvm::Constant *Aliasee;
6856a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (isa<llvm::FunctionType>(DeclTy))
6861faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
6871faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
6886a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  else
689f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
6906a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                    llvm::PointerType::getUnqual(DeclTy), 0);
6916a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (!Entry) {
6926a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
6936a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    F->setLinkage(llvm::Function::ExternalWeakLinkage);
6946a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    WeakRefReferences.insert(F);
6956a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  }
6966a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
6976a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  return Aliasee;
6986a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola}
6996a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
700b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
7014a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
7021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7036a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // Weak references don't produce any output by themselves.
7046a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (Global->hasAttr<WeakRefAttr>())
7056a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    return;
7066a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
707bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
708bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
70940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Global->hasAttr<AliasAttr>())
710f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return EmitAliasDefinition(GD);
711219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
71267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
7135e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
714754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    if (FD->getIdentifier()) {
715754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      llvm::StringRef Name = FD->getName();
716754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      if (Name == "_Block_object_assign") {
717754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar        BlockObjectAssignDecl = FD;
718754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      } else if (Name == "_Block_object_dispose") {
719754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar        BlockObjectDisposeDecl = FD;
720754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      }
721754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    }
722754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
72373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
72473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    if (!FD->isThisDeclarationADefinition())
72573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
7260269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
7270269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
728bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
729bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
730754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    if (VD->getIdentifier()) {
731754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      llvm::StringRef Name = VD->getName();
732754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      if (Name == "_NSConcreteGlobalBlock") {
733754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar        NSConcreteGlobalBlockDecl = VD;
734754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      } else if (Name == "_NSConcreteStackBlock") {
735754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar        NSConcreteStackBlockDecl = VD;
736754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      }
737754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    }
738754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
739754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
740a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
74173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
7424c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
7434c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
74467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
74567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
7464357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (!MayDeferGeneration(Global)) {
7474357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Emit the definition if it can't be deferred.
7484357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    EmitGlobalDefinition(GD);
749bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
750bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
751bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
752bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // If we're deferring emission of a C++ variable with an
753bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // initializer, remember the order in which it appeared in the file.
754bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
755bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      cast<VarDecl>(Global)->hasInit()) {
756bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
757bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    CXXGlobalInits.push_back(0);
758bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  }
7594357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
7604357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // If the value has already been used, add it directly to the
7614357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // DeferredDeclsToEmit list.
7629a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson  llvm::StringRef MangledName = getMangledName(GD);
7634357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (GetGlobalValue(MangledName))
7644357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDeclsToEmit.push_back(GD);
7654357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  else {
7664357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Otherwise, remember that we saw a deferred decl with this name.  The
7674357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // first use of the mangled name will cause it to move into
7684357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // DeferredDeclsToEmit.
7694357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDecls[MangledName] = GD;
7704357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  }
7714c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
7724c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
773b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
7744a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
7751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
776cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
7778e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 Context.getSourceManager(),
7788e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 "Generating code for declaration");
7798e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson
78044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
78144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // At -O0, don't generate IR for functions with available_externally
78244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // linkage.
7837feaeeed1789fbf357fc81072966fe8f62fb4a81Douglas Gregor    if (CodeGenOpts.OptimizationLevel == 0 &&
7847feaeeed1789fbf357fc81072966fe8f62fb4a81Douglas Gregor        !Function->hasAttr<AlwaysInlineAttr>() &&
78544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getFunctionLinkage(Function)
78644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor                                  == llvm::Function::AvailableExternallyLinkage)
78744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      return;
78844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
78944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
79044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (Method->isVirtual())
79144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getVTables().EmitThunks(GD);
7927270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
79344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
79444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        return EmitCXXConstructor(CD, GD.getCtorType());
7954357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
79644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
79744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        return EmitCXXDestructor(DD, GD.getDtorType());
79844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    }
799b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
800b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalFunctionDefinition(GD);
80144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  }
802b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
803b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
804b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalVarDefinition(VD);
8054357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8064357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  assert(0 && "Invalid argument to EmitGlobalDefinition()");
807bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
808bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
80974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
81074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
81174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
81274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
81374391b48b4791cded373683a3baf67314f358d50Chris Lattner///
81474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
81574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
816f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
817f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallCodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
818f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                       const llvm::Type *Ty,
8191faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                       GlobalDecl D, bool ForVTable) {
8200558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
821f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
8220558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
8236a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
8246a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
8256a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (FD && !FD->hasAttr<WeakAttr>())
8267270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
8276a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8286a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
8296a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
8306a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8310558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
8320558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
8331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
8340558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
83596e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
8363c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, PTy);
8370558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
8381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
839654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // This function doesn't have a complete type (for example, the return
840654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // type is an incomplete struct). Use a fake type instead, and make
841654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // sure not to try to set attributes.
842654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  bool IsIncompleteFunction = false;
843784f21121a6c9418ebd86baa6814e36e1176c410John McCall
844784f21121a6c9418ebd86baa6814e36e1176c410John McCall  const llvm::FunctionType *FTy;
845784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (isa<llvm::FunctionType>(Ty)) {
846784f21121a6c9418ebd86baa6814e36e1176c410John McCall    FTy = cast<llvm::FunctionType>(Ty);
847784f21121a6c9418ebd86baa6814e36e1176c410John McCall  } else {
84815f6765f6efd24bec4ec6f54e282c14193ef4014Benjamin Kramer    FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
849654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    IsIncompleteFunction = true;
850654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
851bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
852784f21121a6c9418ebd86baa6814e36e1176c410John McCall  llvm::Function *F = llvm::Function::Create(FTy,
853654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                             llvm::Function::ExternalLinkage,
854f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                             MangledName, &getModule());
855f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  assert(F->getName() == MangledName && "name was uniqued!");
856654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (D.getDecl())
857b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetFunctionAttributes(D, F, IsIncompleteFunction);
858654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
85967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
86067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
86167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
862f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
86367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
86467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
86567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
86667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
86767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
868bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
869bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // Otherwise, there are cases we have to worry about where we're
870bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // using a declaration for which we must emit a definition but where
871bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // we might not find a top-level definition:
872bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - member functions defined inline in their classes
873bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - friend functions defined inline in some class
874bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - special member functions with implicit definitions
875bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // If we ever change our AST traversal to walk into class methods,
876bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // this will be unnecessary.
8771faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  //
8781faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // We also don't emit a definition for a function if it's going to be an entry
8791faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // in a vtable, unless it's already marked as used.
88001de7a44cea9f77cbcda65faad8edc8b48a3b617Rafael Espindola  } else if (getLangOptions().CPlusPlus && D.getDecl()) {
881bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    // Look for a declaration that's lexically in a record.
882bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
883bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    do {
884bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8851faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        if (FD->isImplicit() && !ForVTable) {
886bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
887a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
888bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
889bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        } else if (FD->isThisDeclarationADefinition()) {
890a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
891bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
892bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        }
8937b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      }
894bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      FD = FD->getPreviousDeclaration();
895bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    } while (FD);
89667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
8971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
898784f21121a6c9418ebd86baa6814e36e1176c410John McCall  // Make sure the result is of the requested type.
899784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (!IsIncompleteFunction) {
900784f21121a6c9418ebd86baa6814e36e1176c410John McCall    assert(F->getType()->getElementType() == Ty);
901784f21121a6c9418ebd86baa6814e36e1176c410John McCall    return F;
902784f21121a6c9418ebd86baa6814e36e1176c410John McCall  }
903784f21121a6c9418ebd86baa6814e36e1176c410John McCall
904784f21121a6c9418ebd86baa6814e36e1176c410John McCall  const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
905784f21121a6c9418ebd86baa6814e36e1176c410John McCall  return llvm::ConstantExpr::getBitCast(F, PTy);
9060558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
9070558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
90874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
90974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
91074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
911b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
9121faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 const llvm::Type *Ty,
9131faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 bool ForVTable) {
91474391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
91574391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
9164a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
917bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
9189a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson  llvm::StringRef MangledName = getMangledName(GD);
9191faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
92074391b48b4791cded373683a3baf67314f358d50Chris Lattner}
92177ba708819285931932ecd33691a672bb59d221aEli Friedman
92274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
92374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
92474391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
92574391b48b4791cded373683a3baf67314f358d50Chris LattnerCodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
926f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                     llvm::StringRef Name) {
9271faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
92874391b48b4791cded373683a3baf67314f358d50Chris Lattner}
929bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
93020e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedmanstatic bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
93188786862424cb2d478516d911709dc19c962af9cJohn McCall  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
93220e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
93320e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  if (Context.getLangOptions().CPlusPlus &&
93420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman      Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
93520e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    // FIXME: We should do something fancier here!
93620e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
93720e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  }
93820e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  return true;
93920e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman}
94020e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman
94174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
94274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
94374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
94474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
94574391b48b4791cded373683a3baf67314f358d50Chris Lattner///
94674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
94774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
948f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
949f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallCodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
950f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                     const llvm::PointerType *Ty,
951c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     const VarDecl *D,
952c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     bool UnnamedAddr) {
9533c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
954f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
95599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
9566a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
9576a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (D && !D->hasAttr<WeakAttr>())
9587270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
9596a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
9606a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
9616a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
9626a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
963c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola    if (UnnamedAddr)
964c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      Entry->setUnnamedAddr(true);
965c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola
96674391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
967570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
9681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
96999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
9703c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, Ty);
97199b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
9721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
97367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
97467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
97567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
976f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
97767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
97867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
97967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
98067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
98167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
98267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
9831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
9851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
98699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
987f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                             0, MangledName, 0,
98856ebe5082da7411fb37479e230b52735f77cff35Eli Friedman                             false, Ty->getAddressSpace());
98949988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
99099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
99174391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
992f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // FIXME: This code is overly simple and should be merged with other global
993f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // handling.
99420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    GV->setConstant(DeclIsConstantGlobal(Context, D));
99549988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
996110e8e56af30363072c140285961592b0107f789John McCall    // Set linkage and visibility in case we never see a definition.
997af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
998af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() != ExternalLinkage) {
99915e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      // Don't set internal linkage on declarations.
1000110e8e56af30363072c140285961592b0107f789John McCall    } else {
1001110e8e56af30363072c140285961592b0107f789John McCall      if (D->hasAttr<DLLImportAttr>())
1002110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
10030a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1004110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1005110e8e56af30363072c140285961592b0107f789John McCall
1006af14603ca61757cf4361b583b45639a04c57e651John McCall      // Set visibility on a declaration only if it's explicit.
1007af14603ca61757cf4361b583b45639a04c57e651John McCall      if (LV.visibilityExplicit())
1008af14603ca61757cf4361b583b45639a04c57e651John McCall        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1009110e8e56af30363072c140285961592b0107f789John McCall    }
101056ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
101156ebe5082da7411fb37479e230b52735f77cff35Eli Friedman    GV->setThreadLocal(D->isThreadSpecified());
101274391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
10131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1014f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GV;
101574391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1016eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
1017eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
10183bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlssonllvm::GlobalVariable *
10193bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders CarlssonCodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
10203bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      const llvm::Type *Ty,
10213bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
10223bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
10233bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *OldGV = 0;
10243bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10253bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10263bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (GV) {
10273bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Check if the variable has the right type.
10283bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (GV->getType()->getElementType() == Ty)
10293bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      return GV;
10303bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10313bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Because C++ name mangling, the only way we can end up with an already
10323bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
103396eaf2992b5955d1470fc9cce7a96e7e1e3b4ea7Anders Carlsson      assert(GV->isDeclaration() && "Declaration has wrong type!");
10343bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV = GV;
10353bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
10363bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10373bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a new variable.
10383bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
10393bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                Linkage, 0, Name);
10403bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10413bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (OldGV) {
10423bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Replace occurrences of the old variable if needed.
10433bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    GV->takeName(OldGV);
10443bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10453bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (!OldGV->use_empty()) {
10463bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::Constant *NewPtrForOldDecl =
10473bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
10483bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
10493bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
10503bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10513bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV->eraseFromParent();
10523bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
10533bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10543bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  return GV;
10553bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson}
10563bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
105774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
105874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
105974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// then it will be greated with the specified type instead of whatever the
106074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
106174391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
106274391b48b4791cded373683a3baf67314f358d50Chris Lattner                                                  const llvm::Type *Ty) {
106374391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
106474391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
106574391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
106674391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
10671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const llvm::PointerType *PTy =
1069207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1070f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
10719a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson  llvm::StringRef MangledName = getMangledName(D);
1072f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
107374391b48b4791cded373683a3baf67314f358d50Chris Lattner}
10743f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
107574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
107674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
107774391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
107874391b48b4791cded373683a3baf67314f358d50Chris LattnerCodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1079f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                     llvm::StringRef Name) {
10801de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1081c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                               true);
1082bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1083bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
108403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
108503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
108603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
10877520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
10887520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
10897520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
10907520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
10919a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    llvm::StringRef MangledName = getMangledName(D);
1092f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    if (!GetGlobalValue(MangledName)) {
1093555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      DeferredDecls[MangledName] = D;
109403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
10957520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
10967520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
10977520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
10987520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
109903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
110003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
110103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
11026fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregorvoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
11036fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  if (DefinitionRequired)
11046fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    getVTables().GenerateClassData(getVTableLinkage(Class), Class);
11056fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor}
11066fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor
11074b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregorllvm::GlobalVariable::LinkageTypes
1108046c294a43024874ff35656c6e785b64e72f1f36Anders CarlssonCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1109dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1110dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return llvm::GlobalVariable::InternalLinkage;
1111dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1112dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (const CXXMethodDecl *KeyFunction
1113dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor                                    = RD->getASTContext().getKeyFunction(RD)) {
1114dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // If this class has a key function, use that to determine the linkage of
1115dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // the vtable.
11164b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    const FunctionDecl *Def = 0;
111706a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis    if (KeyFunction->hasBody(Def))
11184b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      KeyFunction = cast<CXXMethodDecl>(Def);
1119dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
11204b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    switch (KeyFunction->getTemplateSpecializationKind()) {
11214b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_Undeclared:
11224b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitSpecialization:
11236d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // When compiling with optimizations turned on, we emit all vtables,
11246d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // even if the key function is not defined in the current translation
11256d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // unit. If this is the case, use available_externally linkage.
11266d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        if (!Def && CodeGenOpts.OptimizationLevel)
11276d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson          return llvm::GlobalVariable::AvailableExternallyLinkage;
11286d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson
11294b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        if (KeyFunction->isInlined())
1130142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian          return !Context.getLangOptions().AppleKext ?
1131142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::GlobalVariable::LinkOnceODRLinkage :
1132142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::Function::InternalLinkage;
11334b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
11344b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        return llvm::GlobalVariable::ExternalLinkage;
11354b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
11364b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ImplicitInstantiation:
1137142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1138142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1139142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1140f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
11414b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDefinition:
1142142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1143142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::WeakODRLinkage :
1144142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1145f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
11464b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDeclaration:
11474b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // FIXME: Use available_externally linkage. However, this currently
11484b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // breaks LLVM's build due to undefined symbols.
11494b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1150142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1151142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1152142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
11534b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    }
1154dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1155dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
115653bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  if (Context.getLangOptions().AppleKext)
115753bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::Function::InternalLinkage;
115853bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian
1159dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  switch (RD->getTemplateSpecializationKind()) {
1160dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_Undeclared:
1161dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ExplicitSpecialization:
1162dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ImplicitInstantiation:
1163dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // FIXME: Use available_externally linkage. However, this currently
1164dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // breaks LLVM's build due to undefined symbols.
1165dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1166142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDeclaration:
116753bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::GlobalVariable::LinkOnceODRLinkage;
1168142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1169142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDefinition:
117053bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
11714b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  }
11724b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
11734b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  // Silence GCC warning.
117453bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  return llvm::GlobalVariable::LinkOnceODRLinkage;
11754b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor}
11764b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
1177687cc4a850b59116efee061018f0d8df50728b82Ken DyckCharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
117806f486ecd05bd6788da97c39164c1903a084c26dKen Dyck    return Context.toCharUnitsFromBits(
117906f486ecd05bd6788da97c39164c1903a084c26dKen Dyck      TheTargetData.getTypeStoreSizeInBits(Ty));
1180687cc4a850b59116efee061018f0d8df50728b82Ken Dyck}
1181687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
1182bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
11838f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
118477ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
11856c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  bool NonConstInit = false;
11861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
118731310a21fb2a9f13950f864f681c86080b05d5b2Sebastian Redl  const Expr *InitExpr = D->getAnyInitializer();
11883bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson
11893bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson  if (!InitExpr) {
1190cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
119103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
119203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
119303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
119403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
119503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
119603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
119703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
119803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
119903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1200b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    Init = EmitNullConstant(D->getType());
120177ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
1202c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor    Init = EmitConstantExpr(InitExpr, D->getType());
12036e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
12043bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson      QualType T = InitExpr->getType();
1205c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor      if (D->getType()->isReferenceType())
1206c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor        T = D->getType();
1207c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor
120889ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      if (getLangOptions().CPlusPlus) {
120989ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = EmitNullConstant(T);
12106c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman        NonConstInit = true;
121189ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      } else {
121289ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        ErrorUnsupported(D, "static initializer");
121389ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
121489ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      }
1215bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    } else {
1216bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // We don't need an initializer, so remove the entry for the delayed
1217bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // initializer position (just in case this entry was delayed).
1218bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      if (getLangOptions().CPlusPlus)
1219bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall        DelayedCXXInitPosition.erase(D);
12206e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
12218f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
12228e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
12232d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner  const llvm::Type* InitType = Init->getType();
1224570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
12251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1226570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
1227570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
12289d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
12299d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           // all zero index gep.
12309d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1231570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
1232570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
12331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1234570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
1235570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
12361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1237570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
1238570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
1239570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
1240570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
1241570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
1242570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
1243570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
1244570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
1245570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
1246570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
1247570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
1248207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      GV->getType()->getAddressSpace() !=
1249207f4d8543529221932af82836016a2ef066c917Peter Collingbourne        getContext().getTargetAddressSpace(ASTTy)) {
12501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1251f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Move the old entry aside so that we'll create a new one.
1252f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Entry->setName(llvm::StringRef());
1253232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
1254570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
1255570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
12560558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
125777ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
12581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *NewPtrForOldDecl =
12593c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1260570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
126177ba708819285931932ecd33691a672bb59d221aEli Friedman
126277ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
1263570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
126477ba708819285931932ecd33691a672bb59d221aEli Friedman  }
126577ba708819285931932ecd33691a672bb59d221aEli Friedman
126640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
12678bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    SourceManager &SM = Context.getSourceManager();
12688bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    AddAnnotation(EmitAnnotateAttr(GV, AA,
1269f7cf85b330bedd2877e1371fb0a83e99751ae162Chris Lattner                              SM.getInstantiationLineNumber(D->getLocation())));
12708bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  }
12718bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
127288a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
1273e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1274e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // If it is safe to mark the global 'constant', do so now.
1275e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  GV->setConstant(false);
12766c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1277e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    GV->setConstant(true);
12781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12798b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1280354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
128188a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
1282354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage =
1283354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GetLLVMLinkageVarDefinition(D, GV);
1284354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  GV->setLinkage(Linkage);
1285354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1286354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    // common vars aren't constant even if declared const.
1287354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GV->setConstant(false);
1288354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1289354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  SetCommonAttributes(D, GV);
1290354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
12913030eb82593097502469a8b3fc26112c79c75605John McCall  // Emit the initializer function if necessary.
12923030eb82593097502469a8b3fc26112c79c75605John McCall  if (NonConstInit)
12933030eb82593097502469a8b3fc26112c79c75605John McCall    EmitCXXGlobalVarDeclInitFunc(D, GV);
12943030eb82593097502469a8b3fc26112c79c75605John McCall
1295354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // Emit global variable debug information.
1296aa11289f754d220c9c155b68a4f84cdcfcefef6aDevang Patel  if (CGDebugInfo *DI = getModuleDebugInfo()) {
1297354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    DI->setLocation(D->getLocation());
1298354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    DI->EmitGlobalVariable(GV, D);
1299354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  }
1300354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian}
1301354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1302354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianllvm::GlobalValue::LinkageTypes
1303354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz JahanianCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1304354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                           llvm::GlobalVariable *GV) {
130590e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1306a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  if (Linkage == GVA_Internal)
1307354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::InternalLinkage;
130840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLImportAttr>())
1309354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLImportLinkage;
131040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLExportAttr>())
1311354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLExportLinkage;
1312e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1313e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (GV->isConstant())
1314354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
1315e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    else
1316354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakAnyLinkage;
13178f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor  } else if (Linkage == GVA_TemplateInstantiation ||
13188f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor             Linkage == GVA_ExplicitTemplateInstantiation)
131999ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return llvm::GlobalVariable::WeakODRLinkage;
1320a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher  else if (!getLangOptions().CPlusPlus &&
1321a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1322a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher             D->getAttr<CommonAttr>()) &&
1323309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
132491f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher           !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
132591f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher    // Thread local vars aren't considered common linkage.
1326354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::GlobalVariable::CommonLinkage;
1327686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
1328354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return llvm::GlobalVariable::ExternalLinkage;
132988a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
13305f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1331bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1332bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1333bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// existing call uses of the old function in the module, this adjusts them to
1334bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// call the new function directly.
1335bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
1336bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
1337bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
1338bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1339bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// run at -O0.
1340bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1341bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                      llvm::Function *NewFn) {
1342bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // If we're redefining a global as a function, don't transform it.
1343bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1344bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (OldFn == 0) return;
13451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1346bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  const llvm::Type *NewRetTy = NewFn->getReturnType();
1347bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::SmallVector<llvm::Value*, 4> ArgList;
1348bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1349bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1350dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer       UI != E; ) {
1351bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1352dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1353dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
13548670cd3ea4dfbf86caacd270ec2441e9949bbb6aGabor Greif    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
135535db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif    llvm::CallSite CS(CI);
1356dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    if (!CI || !CS.isCallee(I)) continue;
13571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1358bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the return types don't match exactly, and if the call isn't dead, then
1359bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // we can't transform this call.
1360bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (CI->getType() != NewRetTy && !CI->use_empty())
1361bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
1362bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1363bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the function was passed too few arguments, don't transform.  If extra
1364bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // arguments were passed, we silently drop them.  If any of the types
1365bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // mismatch, we don't transform.
1366bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    unsigned ArgNo = 0;
1367bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    bool DontTransform = false;
1368bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1369bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
137035db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif      if (CS.arg_size() == ArgNo ||
137135db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1372bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        DontTransform = true;
1373bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
1374bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
1375bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1376bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (DontTransform)
1377bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
13781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1379bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
1380bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
13816ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1382bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1383bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                     ArgList.end(), "", CI);
1384bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.clear();
1385ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    if (!NewCall->getType()->isVoidTy())
1386bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      NewCall->takeName(CI);
1387bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    NewCall->setAttributes(CI->getAttributes());
1388ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    NewCall->setCallingConv(CI->getCallingConv());
1389bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1390bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
139100549fcec0490b2daf27543e532f94adbb186063Chris Lattner    if (!CI->use_empty())
139200549fcec0490b2daf27543e532f94adbb186063Chris Lattner      CI->replaceAllUsesWith(NewCall);
13933b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel
1394c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    // Copy debug location attached to CI.
1395c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    if (!CI->getDebugLoc().isUnknown())
1396c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner      NewCall->setDebugLoc(CI->getDebugLoc());
1397bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CI->eraseFromParent();
1398bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1399bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1400bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1401bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1402b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1403b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1404d26bc76c98006609002d9930f8840490e88ac5b5John McCall
14051f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  // Compute the function info and LLVM type.
1406d26bc76c98006609002d9930f8840490e88ac5b5John McCall  const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
14071f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  bool variadic = false;
14081f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
14091f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall    variadic = fpt->isVariadic();
14101f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
1411d26bc76c98006609002d9930f8840490e88ac5b5John McCall
14129fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
1413b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
14141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14150558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
14160558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
14170558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
14180558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
14190558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
14201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14220558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1423bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
14241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
142542745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
1426bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
14270558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
142834809507232bc4c3c4840c7d092c7440219fddafChris Lattner
142962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
143062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
143162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
143262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
143362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
143462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
1435f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // (e.g. "int f(int x)").  Move the old function aside so that it
1436f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // doesn't interfere with GetAddrOfFunction.
1437f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    OldFn->setName(llvm::StringRef());
1438b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
14391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1440bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If this is an implementation of a function without a prototype, try to
1441bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // replace any existing uses of the function (which may be calls) with uses
1442bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // of the new function
14439fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    if (D->getType()->isFunctionNoProtoType()) {
1444bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
14459fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
14469fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
14471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
144862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
1449bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
14501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      llvm::Constant *NewPtrForOldDecl =
14513c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1452bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1453bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
14541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
145562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
1456bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
14571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14580558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
1459bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
14601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1461112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // We need to set linkage and visibility on the function before
1462112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // generating code for it because various parts of IR generation
1463112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // want to propagate this information down (e.g. to local static
1464112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // declarations).
14650558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
14668b2423361648c39a7d8a3c5e8129e12006deac32John McCall  setFunctionLinkage(D, Fn);
1467bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1468112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
14690ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(Fn, D);
1470112c967bd5c862a0f5d7913aa06700c048807db8John McCall
1471d26bc76c98006609002d9930f8840490e88ac5b5John McCall  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
14726379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
14737c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
14747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
14751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
147640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1477219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
147840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1479219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
1480bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1481bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1482f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1483f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
148440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  const AliasAttr *AA = D->getAttr<AliasAttr>();
1485bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
1486bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
14879a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson  llvm::StringRef MangledName = getMangledName(GD);
1488f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1489f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // If there is a definition in the module, then it wins over the alias.
1490f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // This is dubious, but allow it to be safe.  Just ignore the alias.
1491f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1492f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  if (Entry && !Entry->isDeclaration())
1493f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return;
14941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1495f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1496bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1497bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
1498bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
1499bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
1500bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
15011faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
15021faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
1503bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
1504f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
150596e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                                    llvm::PointerType::getUnqual(DeclTy), 0);
1506bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1507bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
15081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *GA =
1509bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
1510bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
1511bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
15121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1513bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
1514f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    assert(Entry->isDeclaration());
1515f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1516bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
1517bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
1518bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
1519bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
1520bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
1521bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
1522bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
1523f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    GA->takeName(Entry);
15241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15253c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1526bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
1527bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
1528f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else {
15299a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    GA->setName(MangledName);
1530bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
15311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15327c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
15337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
15347c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
153540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<DLLExportAttr>()) {
15367c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
15377c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
153806a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis      if (FD->hasBody())
15397c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
15407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
15417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
15427c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
15431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (D->hasAttr<WeakAttr>() ||
154411e8ce7380856abee188b237c2600272df2ed09dRafael Espindola             D->hasAttr<WeakRefAttr>() ||
15450a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             D->isWeakImported()) {
15467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
15477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
15487c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
15497c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
1550bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
1551bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1552b808c952bbff821dce727dd801a1098d64394f98Chris Lattner/// getBuiltinLibFunction - Given a builtin id for a function like
1553b808c952bbff821dce727dd801a1098d64394f98Chris Lattner/// "__builtin_fabsf", return a Function* for "fabsf".
155434771b594ca8cdf8cd2e40b27170efa4ed2833c5Daniel Dunbarllvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
155534771b594ca8cdf8cd2e40b27170efa4ed2833c5Daniel Dunbar                                                  unsigned BuiltinID) {
15563e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
15571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
15583e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor         "isn't a lib fn");
15591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15603e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  // Get the name, skip over the __builtin_ prefix (if necessary).
15613e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
15623e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
15633e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    Name += 10;
15641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const llvm::FunctionType *Ty =
1566386ca78d0b03b1fb519e60d1a14cd12a220364a6Eli Friedman    cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1567bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
15681faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
1569bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner}
1570bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
15717acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattnerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
15727acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner                                            unsigned NumTys) {
15737acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner  return llvm::Intrinsic::getDeclaration(&getModule(),
15747acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
15757acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
1576bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
15771d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
15781d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
15791d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         const StringLiteral *Literal,
158070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                         bool TargetIsLSB,
15811d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         bool &IsUTF16,
15821d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         unsigned &StringLength) {
15832f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  llvm::StringRef String = Literal->getString();
15842f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  unsigned NumBytes = String.size();
15851d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1586f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // Check for simple case.
1587f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  if (!Literal->containsNonAsciiOrNull()) {
1588f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    StringLength = NumBytes;
15892f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    return Map.GetOrCreateValue(String);
1590f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
1591f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
15921d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // Otherwise, convert the UTF8 literals into a byte string.
15931d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
15942f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  const UTF8 *FromPtr = (UTF8 *)String.data();
15951d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  UTF16 *ToPtr = &ToBuf[0];
15961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1597e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1598e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           &ToPtr, ToPtr + NumBytes,
1599e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           strictConversion);
16001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
160170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
16021d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
160370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
160470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // Render the UTF-16 string into a byte array and convert to the target byte
160570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // order.
160670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  //
160770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // FIXME: This isn't something we should need to do here.
160870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  llvm::SmallString<128> AsBytes;
160970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  AsBytes.reserve(StringLength * 2);
161070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  for (unsigned i = 0; i != StringLength; ++i) {
161170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    unsigned short Val = ToBuf[i];
161270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    if (TargetIsLSB) {
161370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
161470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val >> 8);
161570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    } else {
161670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val >> 8);
161770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
161870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    }
161970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  }
1620434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  // Append one extra null character, the second is automatically added by our
1621434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  // caller.
1622434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  AsBytes.push_back(0);
162370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
16241d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  IsUTF16 = true;
162570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
16261d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar}
16271d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
16281d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarllvm::Constant *
16291d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
16301d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  unsigned StringLength = 0;
16311d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool isUTF16 = false;
16321d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringMapEntry<llvm::Constant*> &Entry =
16331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
163470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             getTargetData().isLittleEndian(),
163570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             isUTF16, StringLength);
16361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16371d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
16381d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return C;
16391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16400032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *Zero =
16410032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
16423e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
16431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16449d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // If we don't already have it, get __CFConstantStringClassReference.
1645c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
1646c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
164796e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    Ty = llvm::ArrayType::get(Ty, 0);
16481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *GV = CreateRuntimeVariable(Ty,
16499d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                                           "__CFConstantStringClassReference");
16503e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
16513e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
16523c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1653c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
16541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1655e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
16563e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
16571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  const llvm::StructType *STy =
1658e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1659e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
16605add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  std::vector<llvm::Constant*> Fields(4);
166144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
1662c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
16635add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[0] = CFConstantStringClassRef;
16641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1665c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
16663e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
16671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
16685add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    llvm::ConstantInt::get(Ty, 0x07C8);
16695add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1670c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
16710032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1672a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
167395b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  llvm::GlobalValue::LinkageTypes Linkage;
1674278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  bool isConstant;
1675a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
1676278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // FIXME: why do utf strings get "_" labels instead of "L" labels?
167795b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
1678278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1679278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // does make plain ascii ones writable.
1680278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    isConstant = true;
1681a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  } else {
1682584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1683584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // when using private linkage. It is not clear if this is a bug in ld
1684584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // or a reasonable new restriction.
1685dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1686278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    isConstant = !Features.WritableStrings;
1687a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
1688278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
16891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
1690278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1691278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner                             ".str");
1692b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  GV->setUnnamedAddr(true);
1693a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
16944da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
16954da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    GV->setAlignment(Align.getQuantity());
1696f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
1697f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1698f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
1699a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
17005add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
17015add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1702c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
1703c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
17045add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
17051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1706c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
170708e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  C = llvm::ConstantStruct::get(STy, Fields);
17081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
17091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                llvm::GlobalVariable::PrivateLinkage, C,
171095b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                                "_unnamed_cfstring_");
17118e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (const char *Sect = getContext().Target.getCFStringSection())
17128e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
17131d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  Entry.setValue(GV);
17141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17150c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
1716c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
171745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
171833e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanianllvm::Constant *
17194c73307c74764ba99e1379677fe92af72f676531Fariborz JahanianCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
17202bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  unsigned StringLength = 0;
17212bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isUTF16 = false;
17222bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::StringMapEntry<llvm::Constant*> &Entry =
17232bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GetConstantCFStringEntry(CFConstantStringMap, Literal,
17242bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                             getTargetData().isLittleEndian(),
17252bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                             isUTF16, StringLength);
17262bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17272bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (llvm::Constant *C = Entry.getValue())
17282bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    return C;
17292bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17302bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zero =
17312bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
17322bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zeros[] = { Zero, Zero };
17332bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
1734ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  // If we don't already have it, get _NSConstantStringClassReference.
17354c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  if (!ConstantStringClassRef) {
17364c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    std::string StringClass(getLangOptions().ObjCConstantStringClass);
17372bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
17382bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    Ty = llvm::ArrayType::get(Ty, 0);
17394c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::Constant *GV;
17404c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    if (StringClass.empty())
17414c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      GV = CreateRuntimeVariable(Ty,
17424c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian                                 Features.ObjCNonFragileABI ?
17434c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian                                 "OBJC_CLASS_$_NSConstantString" :
17444c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian                                 "_NSConstantStringClassReference");
17454c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    else {
17464c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      std::string str;
17474c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      if (Features.ObjCNonFragileABI)
17484c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian        str = "OBJC_CLASS_$_" + StringClass;
17494c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      else
17504c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian        str = "_" + StringClass + "ClassReference";
17514c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian      GV = CreateRuntimeVariable(Ty, str);
17524c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    }
17532bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    // Decay array -> ptr
17544c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    ConstantStringClassRef =
17554c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
17562bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
17572bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17582bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  QualType NSTy = getContext().getNSConstantStringType();
17592bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17602bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  const llvm::StructType *STy =
17612bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  cast<llvm::StructType>(getTypes().ConvertType(NSTy));
17622bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17632bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  std::vector<llvm::Constant*> Fields(3);
17642bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17652bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // Class pointer.
17664c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  Fields[0] = ConstantStringClassRef;
17672bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17682bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String pointer.
17692bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
17702bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17712bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage;
17722bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isConstant;
17732bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (isUTF16) {
17742bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    // FIXME: why do utf strings get "_" labels instead of "L" labels?
17752bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    Linkage = llvm::GlobalValue::InternalLinkage;
17762bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
17772bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    // does make plain ascii ones writable.
17782bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    isConstant = true;
17792bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  } else {
17802bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    Linkage = llvm::GlobalValue::PrivateLinkage;
17812bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    isConstant = !Features.WritableStrings;
17822bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
17832bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17842bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalVariable *GV =
17852bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
17862bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                           ".str");
1787803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola  GV->setUnnamedAddr(true);
17882bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (isUTF16) {
17892bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
17902bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setAlignment(Align.getQuantity());
1791f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
1792f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1793f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
17942bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
17952bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
17962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17972bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String length.
17982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
17992bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
18002bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18012bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // The struct.
18022bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  C = llvm::ConstantStruct::get(STy, Fields);
18032bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
18042bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
18052bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                "_unnamed_nsstring_");
18062bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // FIXME. Fix section.
1807ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  if (const char *Sect =
1808ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian        Features.ObjCNonFragileABI
1809ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian          ? getContext().Target.getNSStringNonFragileABISection()
1810ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian          : getContext().Target.getNSStringSection())
18112bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setSection(Sect);
18122bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Entry.setValue(GV);
18132bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18142bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  return GV;
181533e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian}
181633e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian
18176143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetStringForStringLiteral - Return the appropriate bytes for a
18181e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar/// string literal, properly padded to match the literal type.
18196143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
18203b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck  const ASTContext &Context = getContext();
18211e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const ConstantArrayType *CAT =
18223b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck    Context.getAsConstantArrayType(E->getType());
18231e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  assert(CAT && "String isn't pointer or array!");
18241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1825dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  // Resize the string to the right size.
18261e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  uint64_t RealLen = CAT->getSize().getZExtValue();
18271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1828dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  if (E->isWide())
18293b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck    RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
18301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18312f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  std::string Str = E->getString().str();
18321e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  Str.resize(RealLen, '\0');
18331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18341e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  return Str;
18351e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar}
18361e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
18376143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
18386143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
18396143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
18406143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
18416143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // FIXME: This can be more efficient.
18427eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
18437eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
18447eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  if (S->isWide()) {
18457eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman    llvm::Type *DestTy =
18467eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
18477eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman    C = llvm::ConstantExpr::getBitCast(C, DestTy);
18487eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  }
18497eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  return C;
18506143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
18516143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
1852eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1853eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
1854eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
1855eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1856eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
1857eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1858a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
1859a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
1860eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
1861eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1862eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1863a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
18649de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerstatic llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
186545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
18665fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
18675fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             const char *GlobalName) {
18686143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
18690032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C =
18700032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
18711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
187245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
18731257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  llvm::GlobalVariable *GV =
18741257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
18751257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             llvm::GlobalValue::PrivateLinkage,
18761257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             C, GlobalName);
18771257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  GV->setUnnamedAddr(true);
18781257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  return GV;
187945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
188045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
18816143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
18826143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
18836143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
18846143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
18856143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
18866143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
18876143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
18886143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
18899de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
18905fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                                       const char *GlobalName) {
18918e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  bool IsConstant = !Features.WritableStrings;
18928e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
18938e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
18948e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
189595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GlobalName = ".str";
18968e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
18978e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
18988e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!IsConstant)
18999de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    return GenerateStringLiteral(Str, false, *this, GlobalName);
19001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::StringMapEntry<llvm::Constant *> &Entry =
19029de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    ConstantStringMap.GetOrCreateValue(Str);
190345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
190445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  if (Entry.getValue())
1905eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    return Entry.getValue();
190645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
190745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
19089de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer  llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
190945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  Entry.setValue(C);
191045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  return C;
191145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
19126143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
19136143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
19149de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer/// array containing the literal and a terminating '\0'
19156143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
19169de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
19175fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                                        const char *GlobalName){
19189de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer  llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
19199de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer  return GetAddrOfConstantString(StrWithNull, GlobalName);
19206143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
192141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1922af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
1923af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
19241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::EmitObjCPropertyImplementations(const
1925af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
19261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCImplementationDecl::propimpl_iterator
192717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1928af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCPropertyImplDecl *PID = *i;
19291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1930af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
1931af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1932af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1933af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1934af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
1935af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // been overridden. Note that ::isSynthesized is not the method
1936af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
1937af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
1938af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
193917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (!D->getInstanceMethod(PD->getGetterName()))
1940fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
1941fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
1942af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
194317945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis          !D->getInstanceMethod(PD->getSetterName()))
1944fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
1945fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
1946af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
1947af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
1948af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
1949af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1950e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCallstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
1951e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  ObjCInterfaceDecl *iface
1952e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1953e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1954e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall       ivar; ivar = ivar->getNextIvar())
1955e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (ivar->getType().isDestructedType())
1956e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      return true;
1957e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
1958e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return false;
1959e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
1960e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
1961109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// EmitObjCIvarInitializations - Emit information for ivar initialization
1962109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// for an implementation.
1963109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanianvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1964e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // We might need a .cxx_destruct even if we don't have any ivar initializers.
1965e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (needsDestructMethod(D)) {
1966e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1967e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1968e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    ObjCMethodDecl *DTORMethod =
1969e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
1970e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall                             cxxSelector, getContext().VoidTy, 0, D, true,
1971e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall                             false, true, false, ObjCMethodDecl::Required);
1972e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    D->addInstanceMethod(DTORMethod);
1973e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1974e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  }
1975e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
1976e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // If the implementation doesn't have any ivar initializers, we don't need
1977e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // a .cxx_construct.
1978827bbcc8a9115782693b21030a45378abe5c1862David Chisnall  if (D->getNumIvarInitializers() == 0)
1979109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    return;
1980109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
1981e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
1982e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1983109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // The constructor returns 'self'.
1984109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1985109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(),
1986109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(), cxxSelector,
1987109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                getContext().getObjCIdType(), 0,
1988e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall                                                D, true, false, true, false,
1989109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                ObjCMethodDecl::Required);
1990109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  D->addInstanceMethod(CTORMethod);
1991109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1992109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian}
1993109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
199491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
1995984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
199617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1997984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
1998984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
1999984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
2000984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
200191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
200291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2003f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2004f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
200591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
200691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
200791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
200891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
200917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
201091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson       I != E; ++I)
201191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
201291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
201391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
201441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
201541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
201641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
201741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
201841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
201941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
202041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
202141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
202216e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  // Ignore dependent declarations.
202316e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
202416e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    return;
20251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
202641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
2027293361afd4199c92aabff9267fddea890943c586Anders Carlsson  case Decl::CXXConversion:
20282b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
202941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
203016e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    // Skip function templates
203116e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
203216e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      return;
20331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2034555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<FunctionDecl>(D));
2035555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    break;
2036555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson
203741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
2038555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<VarDecl>(D));
203941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
204041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
204126fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // Indirect fields from global anonymous structs and unions can be
204226fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // ignored; only the actual variable requires IR gen support.
204326fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  case Decl::IndirectField:
204426fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall    break;
204526fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
204695d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
204741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
2048984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
204941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
20509cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    // No code generation needed.
20519d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  case Decl::UsingShadow:
20529cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  case Decl::Using:
2053dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  case Decl::UsingDirective:
2054127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::ClassTemplate:
2055127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::FunctionTemplate:
2056018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  case Decl::NamespaceAlias:
20579cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    break;
205895d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
20591fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    // Skip function templates
20601fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
20611fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson      return;
20621fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
206395d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
206495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
206527ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
206627ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
206727ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
206836674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
206936674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  case Decl::StaticAssert:
207036674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    // Nothing to do.
207136674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    break;
207236674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
207395d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
20741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
207538e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
207641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCClass:
207741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCForwardProtocol:
2078b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
207941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2080000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian
2081baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  case Decl::ObjCCategory: {
2082baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2083baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    if (CD->IsClassExtension() && CD->hasSynthBitfield())
2084baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner      Context.ResetObjCLayout(CD->getClassInterface());
2085baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    break;
2086baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  }
2087285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
208841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCProtocol:
2089b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
209041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
209141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
209241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
2093af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
2094af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
209541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
209641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
209741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2098af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
2099af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2100000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian    if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2101000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian      Context.ResetObjCLayout(OMD->getClassInterface());
2102af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
2103109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    EmitObjCIvarInitializations(OMD);
2104af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    Runtime->GenerateClass(OMD);
210541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
21061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
210741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
210841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
210941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
21106fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (OMD->getBody())
211141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
211241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
211341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
21141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::ObjCCompatibleAlias:
2115305c658ebce84bb9833fc0e7675554656453b8e8Fariborz Jahanian    // compatibility-alias is a directive and has no code gen.
211641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
211741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
211891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
211991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
212041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
212141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
212241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
212341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
21248d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer    llvm::StringRef AsmString = AD->getAsmString()->getString();
21251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
212641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
212741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
212841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
212941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
21308d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
213141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
213241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
21331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  default:
2135f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // Make sure we handled everything we should, every other kind is a
2136f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2137f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // function. Need to recode Decl::Kind to do that easily.
213841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
213941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
214041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
2141744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2142744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Turns the given pointer into a constant.
2143744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2144744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                          const void *Ptr) {
2145744016dde06fcffd50931e94a98c850f8b12cd87John McCall  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2146744016dde06fcffd50931e94a98c850f8b12cd87John McCall  const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2147744016dde06fcffd50931e94a98c850f8b12cd87John McCall  return llvm::ConstantInt::get(i64, PtrInt);
2148744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2149744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2150744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2151744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::NamedMDNode *&GlobalMetadata,
2152744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   GlobalDecl D,
2153744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::GlobalValue *Addr) {
2154744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (!GlobalMetadata)
2155744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GlobalMetadata =
2156744016dde06fcffd50931e94a98c850f8b12cd87John McCall      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2157744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2158744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // TODO: should we report variant information for ctors/dtors?
2159744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::Value *Ops[] = {
2160744016dde06fcffd50931e94a98c850f8b12cd87John McCall    Addr,
2161744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2162744016dde06fcffd50931e94a98c850f8b12cd87John McCall  };
2163744016dde06fcffd50931e94a98c850f8b12cd87John McCall  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2164744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2165744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2166744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes associating all the global values in the
2167744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// current module with the Decls they came from.  This is useful for
2168744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// projects using IR gen as a subroutine.
2169744016dde06fcffd50931e94a98c850f8b12cd87John McCall///
2170744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Since there's currently no way to associate an MDNode directly
2171744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with an llvm::GlobalValue, we create a global named metadata
2172744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with the name 'clang.global.decl.ptrs'.
2173744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenModule::EmitDeclMetadata() {
2174744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2175744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2176744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // StaticLocalDeclMap
2177744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2178744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2179744016dde06fcffd50931e94a98c850f8b12cd87John McCall       I != E; ++I) {
2180744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2181744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2182744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2183744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2184744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2185744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes for all the local variables in the current
2186744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// function.
2187744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenFunction::EmitDeclMetadata() {
2188744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (LocalDeclMap.empty()) return;
2189744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2190744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::LLVMContext &Context = getLLVMContext();
2191744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2192744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Find the unique metadata ID for this name.
2193744016dde06fcffd50931e94a98c850f8b12cd87John McCall  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2194744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2195744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2196744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2197744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2198744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2199744016dde06fcffd50931e94a98c850f8b12cd87John McCall    const Decl *D = I->first;
2200744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::Value *Addr = I->second;
2201744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2202744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2203744016dde06fcffd50931e94a98c850f8b12cd87John McCall      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2204744016dde06fcffd50931e94a98c850f8b12cd87John McCall      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2205744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2206744016dde06fcffd50931e94a98c850f8b12cd87John McCall      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2207744016dde06fcffd50931e94a98c850f8b12cd87John McCall      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2208744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2209744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2210744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2211673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2212673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar///@name Custom Runtime Function Interfaces
2213673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar///@{
2214673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar//
2215673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar// FIXME: These can be eliminated once we can have clients just get the required
2216673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar// AST nodes from the builtin tables.
2217673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2218673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbarllvm::Constant *CodeGenModule::getBlockObjectDispose() {
2219673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  if (BlockObjectDispose)
2220673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    return BlockObjectDispose;
2221673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2222754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // If we saw an explicit decl, use that.
2223754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  if (BlockObjectDisposeDecl) {
2224754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    return BlockObjectDispose = GetAddrOfFunction(
2225754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      BlockObjectDisposeDecl,
2226754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      getTypes().GetFunctionType(BlockObjectDisposeDecl));
2227754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  }
2228754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
2229754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // Otherwise construct the function by hand.
2230673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  const llvm::FunctionType *FTy;
2231673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  std::vector<const llvm::Type*> ArgTys;
2232673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2233d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  ArgTys.push_back(Int8PtrTy);
2234673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2235673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2236673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  return BlockObjectDispose =
2237673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    CreateRuntimeFunction(FTy, "_Block_object_dispose");
2238673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar}
2239673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2240673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbarllvm::Constant *CodeGenModule::getBlockObjectAssign() {
2241673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  if (BlockObjectAssign)
2242673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    return BlockObjectAssign;
2243673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2244754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // If we saw an explicit decl, use that.
2245754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  if (BlockObjectAssignDecl) {
2246754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    return BlockObjectAssign = GetAddrOfFunction(
2247754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      BlockObjectAssignDecl,
2248754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      getTypes().GetFunctionType(BlockObjectAssignDecl));
2249754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  }
2250754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
2251754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // Otherwise construct the function by hand.
2252673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  const llvm::FunctionType *FTy;
2253673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  std::vector<const llvm::Type*> ArgTys;
2254673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2255d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  ArgTys.push_back(Int8PtrTy);
2256d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  ArgTys.push_back(Int8PtrTy);
2257673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2258673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2259673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  return BlockObjectAssign =
2260673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    CreateRuntimeFunction(FTy, "_Block_object_assign");
2261673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar}
2262673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2263673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbarllvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2264673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  if (NSConcreteGlobalBlock)
2265673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    return NSConcreteGlobalBlock;
2266754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
2267754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // If we saw an explicit decl, use that.
2268754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  if (NSConcreteGlobalBlockDecl) {
2269754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2270754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      NSConcreteGlobalBlockDecl,
2271754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2272754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  }
2273754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
2274754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // Otherwise construct the variable by hand.
2275d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  return NSConcreteGlobalBlock =
2276d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
2277673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar}
2278673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2279673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbarllvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2280673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar  if (NSConcreteStackBlock)
2281673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    return NSConcreteStackBlock;
2282754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
2283754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // If we saw an explicit decl, use that.
2284754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  if (NSConcreteStackBlockDecl) {
2285754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar    return NSConcreteStackBlock = GetAddrOfGlobalVar(
2286754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      NSConcreteStackBlockDecl,
2287754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar      getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2288754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  }
2289754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar
2290754b9fbaa13749c61393cc613eec7c79efe60ddfDaniel Dunbar  // Otherwise construct the variable by hand.
2291d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  return NSConcreteStackBlock =
2292d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");
2293673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar}
2294673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
2295673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar///@}
2296