CodeGenModule.cpp revision b219cfc4d75f0a03630b7c4509ef791b7e97b2c8
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"
218c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne#include "CGOpenCLRuntime.h"
2282d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov#include "TargetInfo.h"
2306057cef0bcd7804e80f3ce2bbe352178396c715Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
245f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
25687cc4a850b59116efee061018f0d8df50728b82Ken Dyck#include "clang/AST/CharUnits.h"
26c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2721ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
28af896897f7485176f43d40c4adced7efb0fb2b06Douglas Gregor#include "clang/AST/DeclTemplate.h"
2914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne#include "clang/AST/Mangle.h"
301a5e0d7f18485e4fb958f96dcddff3e4486a4069Anders Carlsson#include "clang/AST/RecordLayout.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
4777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougestatic const char AnnotationSection[] = "llvm.metadata";
4877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
49f16aa103d3afd42fbca2ab346f191bf745cec092John McCallstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
50bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  switch (CGM.getContext().getTargetInfo().getCXXABI()) {
51f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
52f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
53f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
54f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  }
55f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
56f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  llvm_unreachable("invalid C++ ABI kind");
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  return *CreateItaniumCXXABI(CGM);
58f16aa103d3afd42fbca2ab346f191bf745cec092John McCall}
59f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
605f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
612811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
62468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall                             llvm::Module &M, const llvm::TargetData &TD,
63468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall                             Diagnostic &diags)
64d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
65468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
66f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    ABI(createCXXABI(*this)),
6708d4792bb5d9e0e7f122c6273636807029c06aaaDaniel Dunbar    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
683d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    TBAA(0),
698c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), DebugInfo(0), ARCData(0),
708c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    RRData(0), CFConstantStringClassRef(0), ConstantStringClassRef(0),
7145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NSConstantStringType(0),
72673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    VMContext(M.getContext()),
73673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
74d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockObjectAssign(0), BlockObjectDispose(0),
75d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockDescriptorType(0), GenericBlockLiteralType(0) {
7660be607e5d71627bf3dab8f51c3fdca74267c692David Chisnall  if (Features.ObjC1)
778c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createObjCRuntime();
788c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  if (Features.OpenCL)
798c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createOpenCLRuntime();
80e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
813d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  // Enable TBAA unless it's suppressed.
823d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
830b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman    TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
840b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman                           ABI.getMangleContext());
853d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
86e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // If debug info or coverage generation is enabled, create the CGDebugInfo
87e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // object.
88e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
89e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky      CodeGenOpts.EmitGcovNotes)
90e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky    DebugInfo = new CGDebugInfo(*this);
91d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
92d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  Block.GlobalUniqueCount = 0;
935936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
94f85e193739c953358c865005855253af4f68a497John McCall  if (C.getLangOptions().ObjCAutoRefCount)
95f85e193739c953358c865005855253af4f68a497John McCall    ARCData = new ARCEntrypoints();
96f85e193739c953358c865005855253af4f68a497John McCall  RRData = new RREntrypoints();
97f85e193739c953358c865005855253af4f68a497John McCall
985936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  // Initialize the type cache.
995936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  llvm::LLVMContext &LLVMContext = M.getContext();
1000774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  VoidTy = llvm::Type::getVoidTy(LLVMContext);
1010774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1020774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1030774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
104bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
10534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  PointerAlignInBytes =
106bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1085936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
1095936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8PtrTy = Int8Ty->getPointerTo(0);
1105936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1112b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
1122b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
1132b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
114e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  delete ObjCRuntime;
1158c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  delete OpenCLRuntime;
116f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  delete &ABI;
1174376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman  delete TBAA;
118815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
119f85e193739c953358c865005855253af4f68a497John McCall  delete ARCData;
120f85e193739c953358c865005855253af4f68a497John McCall  delete RRData;
121815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
122815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
1230d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnallvoid CodeGenModule::createObjCRuntime() {
1240d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  if (!Features.NeXTRuntime)
125e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateGNUObjCRuntime(*this);
1260d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  else
127e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateMacObjCRuntime(*this);
1280d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall}
1290d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
1308c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbournevoid CodeGenModule::createOpenCLRuntime() {
1318c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  OpenCLRuntime = new CGOpenCLRuntime(*this);
1328c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne}
1338c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
134815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
13582227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
1366c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  EmitCXXGlobalInitFunc();
137efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar  EmitCXXGlobalDtorFunc();
138e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  if (ObjCRuntime)
139e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
140208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
1416bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
1426bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
14377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  EmitGlobalAnnotations();
1440269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
145744016dde06fcffd50931e94a98c850f8b12cd87John McCall
146b25938303de0976b9f189363d43033e5788e3d36John McCall  SimplifyPersonality();
147b25938303de0976b9f189363d43033e5788e3d36John McCall
148744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (getCodeGenOpts().EmitDeclMetadata)
149744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitDeclMetadata();
1505ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky
1515ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
1523dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    EmitCoverageFile();
153f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
154f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel  if (DebugInfo)
155f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel    DebugInfo->finalize();
156f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
157f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
158e80d56771736c85fd8365c394a6731923b17e91dDevang Patelvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
159e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  // Make sure that this type is translated.
160e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  Types.UpdateCompletedType(TD);
161e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  if (DebugInfo)
162e80d56771736c85fd8365c394a6731923b17e91dDevang Patel    DebugInfo->UpdateCompletedType(TD);
163e80d56771736c85fd8365c394a6731923b17e91dDevang Patel}
164e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
1653d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
1663d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!TBAA)
1673d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return 0;
1683d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  return TBAA->getTBAAInfo(QTy);
1693d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1703d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1713d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
1723d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman                                        llvm::MDNode *TBAAInfo) {
1733d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
1743d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1753d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1766374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCallbool CodeGenModule::isTargetDarwin() const {
177bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  return getContext().getTargetInfo().getTriple().isOSDarwin();
1786374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall}
1796374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
1805f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnervoid CodeGenModule::Error(SourceLocation loc, StringRef error) {
18132096695c76033a6b0b1747c439f7378a11e8312John McCall  unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
18232096695c76033a6b0b1747c439f7378a11e8312John McCall  getDiags().Report(Context.getFullLoc(loc), diagID);
18332096695c76033a6b0b1747c439f7378a11e8312John McCall}
18432096695c76033a6b0b1747c439f7378a11e8312John McCall
185488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
1862c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
18790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
18890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
18990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
19090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
1911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
19256b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
1932c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
1940a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
1950a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
1962c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
19758c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
198488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
199c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
20090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
20190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
20290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
20390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
2041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
20556b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
206c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
2070a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
208c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
209c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
210bc8d40d85f3fa1e34569834916f18fecaa635152John McCallllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
211bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
212bc8d40d85f3fa1e34569834916f18fecaa635152John McCall}
213bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
2141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
2150ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson                                        const NamedDecl *D) const {
21604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
217df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
2187e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2196ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
2207e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
2216ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
222af14603ca61757cf4361b583b45639a04c57e651John McCall  // Set visibility for definitions.
223af14603ca61757cf4361b583b45639a04c57e651John McCall  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
224c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
225c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
2267cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
2277cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
228cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// Set the symbol visibility of type information (vtable and RTTI)
229cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// associated with the given type.
230cbfe50224b19119e759802bd0c1463269dffd09eJohn McCallvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
231cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                      const CXXRecordDecl *RD,
232fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson                                      TypeVisibilityKind TVK) const {
2330ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(GV, RD);
234cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
235279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (!CodeGenOpts.HiddenWeakVTables)
236279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    return;
237279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall
2389a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  // We never want to drop the visibility for RTTI names.
2399a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  if (TVK == TVK_ForRTTIName)
2409a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    return;
2419a86a137b0872bad25161fb3408a71d919638757Anders Carlsson
242cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We want to drop the visibility to hidden for weak type symbols.
243cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // This isn't possible if there might be unresolved references
244cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // elsewhere that rely on this symbol being visible.
245cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2467a536907da776bdc47a704e7cafd641e8150e653John McCall  // This should be kept roughly in sync with setThunkVisibility
2477a536907da776bdc47a704e7cafd641e8150e653John McCall  // in CGVTables.cpp.
2487a536907da776bdc47a704e7cafd641e8150e653John McCall
249cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Preconditions.
250f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
251cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
252cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
253cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
254cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Don't override an explicit visibility attribute.
2554421d2b341d041df44013769f23c306308bbab83Douglas Gregor  if (RD->getExplicitVisibility())
256cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
257cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
258cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  switch (RD->getTemplateSpecializationKind()) {
259cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We have to disable the optimization if this is an EI definition
260cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // because there might be EI declarations in other shared objects.
261cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDefinition:
262cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDeclaration:
263cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
264cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2657a536907da776bdc47a704e7cafd641e8150e653John McCall  // Every use of a non-template class's type information has to emit it.
266cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_Undeclared:
267cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
268cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2697a536907da776bdc47a704e7cafd641e8150e653John McCall  // In theory, implicit instantiations can ignore the possibility of
2707a536907da776bdc47a704e7cafd641e8150e653John McCall  // an explicit instantiation declaration because there necessarily
2717a536907da776bdc47a704e7cafd641e8150e653John McCall  // must be an EI definition somewhere with default visibility.  In
2727a536907da776bdc47a704e7cafd641e8150e653John McCall  // practice, it's possible to have an explicit instantiation for
2737a536907da776bdc47a704e7cafd641e8150e653John McCall  // an arbitrary template class, and linkers aren't necessarily able
2747a536907da776bdc47a704e7cafd641e8150e653John McCall  // to deal with mixed-visibility symbols.
2757a536907da776bdc47a704e7cafd641e8150e653John McCall  case TSK_ExplicitSpecialization:
276cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ImplicitInstantiation:
277279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    if (!CodeGenOpts.HiddenWeakTemplateVTables)
2787a536907da776bdc47a704e7cafd641e8150e653John McCall      return;
279cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
280cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  }
281cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
282cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // If there's a key function, there may be translation units
283cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // that don't have the key function's definition.  But ignore
284cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // this if we're emitting RTTI under -fno-rtti.
285fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
286cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    if (Context.getKeyFunction(RD))
287cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      return;
288fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  }
289cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
290cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Otherwise, drop the visibility to hidden.
291cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
292b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  GV->setUnnamedAddr(true);
293cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall}
294cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2955f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerStringRef CodeGenModule::getMangledName(GlobalDecl GD) {
296793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
297793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
2985f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
299793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (!Str.empty())
300793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
301793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3024c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
303793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    IdentifierInfo *II = ND->getIdentifier();
304793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(II && "Attempt to mangle unnamed decl.");
305793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
306793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Str = II->getName();
307793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
308793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
309793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
310793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  llvm::SmallString<256> Buffer;
311c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer);
312793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
313c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
314793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
315c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
316793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
317c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleBlock(BD, Out);
318793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else
319c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleName(ND, Out);
320793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
321793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // Allocate space for the mangled name.
322c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  Out.flush();
323793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  size_t Length = Buffer.size();
324793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  char *Name = MangledNamesAllocator.Allocate<char>(Length);
325793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  std::copy(Buffer.begin(), Buffer.end(), Name);
326793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3275f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  Str = StringRef(Name, Length);
328793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
329793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return Str;
330793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
331793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
33214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbournevoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
33314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne                                        const BlockDecl *BD) {
33414110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  MangleContext &MangleCtx = getCXXABI().getMangleContext();
33514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  const Decl *D = GD.getDecl();
336c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer.getBuffer());
33714110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  if (D == 0)
338c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleGlobalBlock(BD, Out);
33914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
340c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
34114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
342c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
34314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else
344c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
3459a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson}
3469a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson
3475f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
348f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return getModule().getNamedValue(Name);
3495f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
3505f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
3516d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
3526d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
3536bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
35449988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3556bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
3566d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3576d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
3586bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
3596bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
3606bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
36149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3626bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
3636bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
3646bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3656bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
3666bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
3670774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
36896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
3696bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3706bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
371c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::StructType *CtorStructTy =
3727650d95a1a616ea300f37126a8dfc93dc19a662aChris Lattner    llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
37396e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                          llvm::PointerType::getUnqual(CtorFTy), NULL);
3746bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3756bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
3766bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  std::vector<llvm::Constant*> Ctors;
3776bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
3786bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    std::vector<llvm::Constant*> S;
3791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
3800032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson                I->second, false));
3813c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
38208e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
3836bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
3846bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3856bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
38696e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
3871c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    new llvm::GlobalVariable(TheModule, AT, false,
388572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
3897db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(AT, Ctors),
3901c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             GlobalName);
3916d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
3926d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3936d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
394d46f98573ba104eda102dd3224b2dca69f1c6336John McCallllvm::GlobalValue::LinkageTypes
395d46f98573ba104eda102dd3224b2dca69f1c6336John McCallCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
39690e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
3977c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
398f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_Internal)
399d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::InternalLinkage;
400f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
401f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<DLLExportAttr>())
402d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::DLLExportLinkage;
403f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
404f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<WeakAttr>())
405d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::WeakAnyLinkage;
406f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
407f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C99 mode, 'inline' functions are guaranteed to have a strong
408f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition somewhere else, so we can use available_externally linkage.
409f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_C99Inline)
410fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian    return llvm::Function::AvailableExternallyLinkage;
4115584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
4125584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Note that Apple's kernel linker doesn't support symbol
4135584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // coalescing, so we need to avoid linkonce and weak linkages there.
4145584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Normally, this means we just map to internal, but for explicit
4155584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // instantiations we'll map to external.
4165584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
417f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C++, the compiler has to emit a definition in every translation unit
418f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // that references the function.  We should use linkonce_odr because
419f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // a) if all references in this translation unit are optimized away, we
420f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // don't need to codegen it.  b) if the function persists, it needs to be
421f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // merged with other definitions. c) C++ has the ODR, so we know the
422f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition is dependable.
423f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
424142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    return !Context.getLangOptions().AppleKext
425142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::LinkOnceODRLinkage
426142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
427f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
428f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // An explicit instantiation of a template has weak linkage, since
429f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // explicit instantiations can occur in multiple translation units
430f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // and must all be equivalent. However, we are not allowed to
431f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // throw away these explicit instantiations.
432f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_ExplicitTemplateInstantiation)
433142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian    return !Context.getLangOptions().AppleKext
434142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::WeakODRLinkage
4355584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall             : llvm::Function::ExternalLinkage;
436f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
437f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // Otherwise, we have strong external linkage.
438f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  assert(Linkage == GVA_StrongExternal);
439f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  return llvm::Function::ExternalLinkage;
440d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
441d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
442d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
443d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// SetFunctionDefinitionAttributes - Set attributes for a global.
444d46f98573ba104eda102dd3224b2dca69f1c6336John McCall///
445d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// FIXME: This is currently only done for aliases and functions, but not for
446d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// variables (these details are set in EmitGlobalVarDefinition for variables).
447d46f98573ba104eda102dd3224b2dca69f1c6336John McCallvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
448d46f98573ba104eda102dd3224b2dca69f1c6336John McCall                                                    llvm::GlobalValue *GV) {
4497c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
450d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
451d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
4527dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
4531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              const CGFunctionInfo &Info,
4547dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
455ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  unsigned CallingConv;
456761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
457ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList, CallingConv);
458761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
459ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar                                          AttributeList.size()));
460ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
461f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
462f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
4637c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
4647c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
465abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola  if (CodeGenOpts.UnwindTables)
466abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola    F->setHasUWTable();
467abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola
46874ac74ae244c501027924c99f2a33559a1e23b53Daniel Dunbar  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
4691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->addFnAttr(llvm::Attribute::NoUnwind);
470af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
4712873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<NakedAttr>()) {
4722873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    // Naked implies noinline: we should not be inlining such functions.
473dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar    F->addFnAttr(llvm::Attribute::Naked);
4742873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    F->addFnAttr(llvm::Attribute::NoInline);
4752873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  }
476dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar
4771feade8e520be483293dbf55eb57a51720899589Mike Stump  if (D->hasAttr<NoInlineAttr>())
47881ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson    F->addFnAttr(llvm::Attribute::NoInline);
479f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
4802873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  // (noinline wins over always_inline, and we can't specify both in IR)
4812873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<AlwaysInlineAttr>() &&
4822873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman      !F->hasFnAttr(llvm::Attribute::NoInline))
4832873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    F->addFnAttr(llvm::Attribute::AlwaysInline);
4842873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman
485c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
486c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    F->setUnnamedAddr(true);
487c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
488e289d81369914678db386f6aa86faf8f178e245dDouglas Gregor  if (Features.getStackProtector() == LangOptions::SSPOn)
489fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtect);
490e289d81369914678db386f6aa86faf8f178e245dDouglas Gregor  else if (Features.getStackProtector() == LangOptions::SSPReq)
491fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtectReq);
492fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson
493cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
494cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  if (alignment)
495cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    F->setAlignment(alignment);
496cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt
497fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  // C++ ABI requires 2-byte alignment for member functions.
498bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
499bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump    F->setAlignment(2);
500f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
501f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
5021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::SetCommonAttributes(const Decl *D,
5037c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
504934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
505934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson    setGlobalVisibility(GV, ND);
5061fb0caaa7bef765b85972274e3b434af2572c141John McCall  else
5071fb0caaa7bef765b85972274e3b434af2572c141John McCall    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
5087c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
50940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<UsedAttr>())
5107c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
5117c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
51240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5137c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
51482d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov
51582d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
5167c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
5177c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5180e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
5190e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
5200e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
5210e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
5220e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
5237c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5247c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
5257c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5260e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
527f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
528f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
529b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
530c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          llvm::Function *F,
531c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          bool IsIncompleteFunction) {
5320ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  if (unsigned IID = F->getIntrinsicID()) {
5330ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // If this is an intrinsic function, set the function's attributes
5340ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // to the intrinsic's attributes.
5350ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
5360ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    return;
5370ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  }
5380ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
539b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
540b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
541c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  if (!IsIncompleteFunction)
542b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
5431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5447c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
5457c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
5461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
54740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (FD->hasAttr<DLLImportAttr>()) {
5487c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
5491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (FD->hasAttr<WeakAttr>() ||
5500a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             FD->isWeakImported()) {
5517c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
5521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // separate linkage types for this.
5537c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
5547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
5551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->setLinkage(llvm::Function::ExternalLinkage);
556af14603ca61757cf4361b583b45639a04c57e651John McCall
557af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
558af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
559af14603ca61757cf4361b583b45639a04c57e651John McCall      F->setVisibility(GetLLVMVisibility(LV.visibility()));
560af14603ca61757cf4361b583b45639a04c57e651John McCall    }
5617c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
5627c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
56340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
5647c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
565219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
566219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
5670269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
5681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!GV->isDeclaration() &&
5690269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
57035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
5710269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
5720269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5730269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
5740269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
575ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  if (LLVMUsed.empty())
5760269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
5770269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5782acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
5791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
58035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
58135f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  std::vector<llvm::Constant*> UsedArray;
58235f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
58335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
5841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    UsedArray[i] =
5851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
586a1cf15f4680e5cf39e72e28c5ea854fcba792e84Owen Anderson                                      i8PTy);
58735f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
5881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
589c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  if (UsedArray.empty())
590c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    return;
59196e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
5921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
5941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), ATy, false,
5950269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
5967db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(ATy, UsedArray),
5971c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             "llvm.used");
5980269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
5990269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
6000269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
6010269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6020269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
60367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
60467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
605dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  // for a static function, iterate until no changes are made.
606bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
607046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
608046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    if (!DeferredVTables.empty()) {
609046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      const CXXRecordDecl *RD = DeferredVTables.back();
610046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      DeferredVTables.pop_back();
611046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      getVTables().GenerateClassData(getVTableLinkage(RD), RD);
612bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola      continue;
613bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    }
614bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
6152a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
61667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
61767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
618c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // Check to see if we've already emitted this.  This is necessary
619c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // for a couple of reasons: first, decls can end up in the
620c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // deferred-decls queue multiple times, and second, decls can end
621c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // up with definitions in unusual ways (e.g. by an extern inline
622c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // function acquiring a strong function redefinition).  Just
623c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // ignore these cases.
624c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    //
625c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // TODO: That said, looking this up multiple times is very wasteful.
6265f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = getMangledName(D);
627f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
62867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
6291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
63067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
63167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
6321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
633c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
634c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // purposes an alias counts as a definition.
635c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (isa<llvm::GlobalAlias>(CGRef))
636c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      continue;
637c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
63867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
63967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
64067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
6415f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
6425f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
64377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::EmitGlobalAnnotations() {
64477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (Annotations.empty())
64577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return;
64677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
64777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Create a new global variable for the ConstantStruct in the Module.
64877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
64977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations[0]->getType(), Annotations.size()), Annotations);
65077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
65177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
65277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    "llvm.global.annotations");
65377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
65477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
65577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
65677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
65777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
65877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (i != AnnotationStrings.end())
65977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return i->second;
66077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
66177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Not found yet, create a new global.
66277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true);
66377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
66477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
66577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
66677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setUnnamedAddr(true);
66777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  AnnotationStrings[Str] = gv;
66877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return gv;
66977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
67077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
67177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
67277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
67377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
67477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (PLoc.isValid())
67577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return EmitAnnotationString(PLoc.getFilename());
67677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return EmitAnnotationString(SM.getBufferName(Loc));
67777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
67877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
67977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
68077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
68177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(L);
68277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
68377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    SM.getExpansionLineNumber(L);
68477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return llvm::ConstantInt::get(Int32Ty, LineNo);
68577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
68677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
6871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
6888bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
68977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                                SourceLocation L) {
69077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the globals for file name, annotation, and the line number.
69177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
69277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *UnitGV = EmitAnnotationUnit(L),
69377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *LineNoCst = EmitAnnotationLineNo(L);
6948bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
69557d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
6968bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
69777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
69877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
69977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
70077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    LineNoCst
7018bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
702c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  return llvm::ConstantStruct::getAnon(Fields);
7038bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
7048bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
70577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
70677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         llvm::GlobalValue *GV) {
70777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
70877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the struct elements for these annotations.
70977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  for (specific_attr_iterator<AnnotateAttr>
71077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ai = D->specific_attr_begin<AnnotateAttr>(),
71177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
71277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
71377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
71477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
715a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidisbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
71690e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  // Never defer when EmitAllDecls is specified.
71790e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  if (Features.EmitAllDecls)
718a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    return false;
7190b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor
7204ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis  return !getContext().DeclMustBeEmitted(Global);
72173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
72273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
7236a836706c40a31c716952b74785102c90fd6afa7Rafael Espindolallvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
7246a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const AliasAttr *AA = VD->getAttr<AliasAttr>();
7256a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  assert(AA && "No alias?");
7266a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7272acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
7286a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7296a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // See if there is already something with the target's name in the module.
730f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
7316a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7326a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  llvm::Constant *Aliasee;
7336a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (isa<llvm::FunctionType>(DeclTy))
7341faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
7351faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
7366a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  else
737f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
7386a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                    llvm::PointerType::getUnqual(DeclTy), 0);
7396a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (!Entry) {
7406a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
7416a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    F->setLinkage(llvm::Function::ExternalWeakLinkage);
7426a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    WeakRefReferences.insert(F);
7436a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  }
7446a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7456a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  return Aliasee;
7466a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola}
7476a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
748b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
7494a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
7501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7516a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // Weak references don't produce any output by themselves.
7526a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (Global->hasAttr<WeakRefAttr>())
7536a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    return;
7546a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
755bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
756bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
75740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Global->hasAttr<AliasAttr>())
758f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return EmitAliasDefinition(GD);
759219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
76067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
7615e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
76273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
763dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    if (!FD->doesThisDeclarationHaveABody()) {
764dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
765dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        return;
766dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
767dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      const FunctionDecl *InlineDefinition = 0;
768dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      FD->getBody(InlineDefinition);
769dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
7705f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      StringRef MangledName = getMangledName(GD);
771dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      llvm::StringMap<GlobalDecl>::iterator DDI =
772dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky          DeferredDecls.find(MangledName);
773dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (DDI != DeferredDecls.end())
774dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        DeferredDecls.erase(DDI);
775dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      EmitGlobalDefinition(InlineDefinition);
77673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
777dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    }
7780269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
7790269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
780bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
781bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
782a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
78373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
7844c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
7854c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
78667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
78767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
7884357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (!MayDeferGeneration(Global)) {
7894357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Emit the definition if it can't be deferred.
7904357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    EmitGlobalDefinition(GD);
791bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
792bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
793bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
794bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // If we're deferring emission of a C++ variable with an
795bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // initializer, remember the order in which it appeared in the file.
796bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
797bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      cast<VarDecl>(Global)->hasInit()) {
798bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
799bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    CXXGlobalInits.push_back(0);
800bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  }
8014357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8024357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // If the value has already been used, add it directly to the
8034357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // DeferredDeclsToEmit list.
8045f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
8054357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (GetGlobalValue(MangledName))
8064357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDeclsToEmit.push_back(GD);
8074357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  else {
8084357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Otherwise, remember that we saw a deferred decl with this name.  The
8094357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // first use of the mangled name will cause it to move into
8104357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // DeferredDeclsToEmit.
8114357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDecls[MangledName] = GD;
8124357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  }
8134c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
8144c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
815b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
8164a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
8171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
818cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
8198e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 Context.getSourceManager(),
8208e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 "Generating code for declaration");
8218e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson
82244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
82344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // At -O0, don't generate IR for functions with available_externally
82444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // linkage.
8257feaeeed1789fbf357fc81072966fe8f62fb4a81Douglas Gregor    if (CodeGenOpts.OptimizationLevel == 0 &&
8267feaeeed1789fbf357fc81072966fe8f62fb4a81Douglas Gregor        !Function->hasAttr<AlwaysInlineAttr>() &&
82744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getFunctionLinkage(Function)
82844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor                                  == llvm::Function::AvailableExternallyLinkage)
82944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      return;
83044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
83144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8327dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // Make sure to emit the definition(s) before we emit the thunks.
8337dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // This is necessary for the generation of certain thunks.
8347dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
8357dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXConstructor(CD, GD.getCtorType());
8367dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
8377dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXDestructor(DD, GD.getDtorType());
8387dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else
8397dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitGlobalFunctionDefinition(GD);
8407dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman
84144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (Method->isVirtual())
84244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getVTables().EmitThunks(GD);
8437270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
8447dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      return;
84544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    }
846b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
847b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalFunctionDefinition(GD);
84844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  }
849b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
850b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
851b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalVarDefinition(VD);
8524357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
853b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
854bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
855bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
85674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
85774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
85874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
85974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
86074391b48b4791cded373683a3baf67314f358d50Chris Lattner///
86174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
86274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
863f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
8645f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
8652acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                       llvm::Type *Ty,
866f85e193739c953358c865005855253af4f68a497John McCall                                       GlobalDecl D, bool ForVTable,
867f85e193739c953358c865005855253af4f68a497John McCall                                       llvm::Attributes ExtraAttrs) {
8680558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
869f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
8700558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
8716a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
8726a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
8736a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (FD && !FD->hasAttr<WeakAttr>())
8747270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
8756a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8766a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
8776a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
8786a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
8790558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
8800558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
8811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
8820558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
8839cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
8840558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
8851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
886654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // This function doesn't have a complete type (for example, the return
887654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // type is an incomplete struct). Use a fake type instead, and make
888654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // sure not to try to set attributes.
889654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  bool IsIncompleteFunction = false;
890784f21121a6c9418ebd86baa6814e36e1176c410John McCall
8912acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *FTy;
892784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (isa<llvm::FunctionType>(Ty)) {
893784f21121a6c9418ebd86baa6814e36e1176c410John McCall    FTy = cast<llvm::FunctionType>(Ty);
894784f21121a6c9418ebd86baa6814e36e1176c410John McCall  } else {
8950774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    FTy = llvm::FunctionType::get(VoidTy, false);
896654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    IsIncompleteFunction = true;
897654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
898bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
899784f21121a6c9418ebd86baa6814e36e1176c410John McCall  llvm::Function *F = llvm::Function::Create(FTy,
900654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                             llvm::Function::ExternalLinkage,
901f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                             MangledName, &getModule());
902f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  assert(F->getName() == MangledName && "name was uniqued!");
903654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (D.getDecl())
904b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetFunctionAttributes(D, F, IsIncompleteFunction);
905f85e193739c953358c865005855253af4f68a497John McCall  if (ExtraAttrs != llvm::Attribute::None)
906f85e193739c953358c865005855253af4f68a497John McCall    F->addFnAttr(ExtraAttrs);
907654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
90867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
90967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
91067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
911f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
91267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
91367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
91467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
91567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
91667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
917bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
918bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // Otherwise, there are cases we have to worry about where we're
919bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // using a declaration for which we must emit a definition but where
920bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // we might not find a top-level definition:
921bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - member functions defined inline in their classes
922bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - friend functions defined inline in some class
923bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - special member functions with implicit definitions
924bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // If we ever change our AST traversal to walk into class methods,
925bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // this will be unnecessary.
9261faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  //
9271faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // We also don't emit a definition for a function if it's going to be an entry
9281faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // in a vtable, unless it's already marked as used.
92901de7a44cea9f77cbcda65faad8edc8b48a3b617Rafael Espindola  } else if (getLangOptions().CPlusPlus && D.getDecl()) {
930bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    // Look for a declaration that's lexically in a record.
931bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
932bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    do {
933bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9341faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        if (FD->isImplicit() && !ForVTable) {
935bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
936a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
937bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
93810620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt        } else if (FD->doesThisDeclarationHaveABody()) {
939a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
940bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
941bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        }
9427b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      }
943bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      FD = FD->getPreviousDeclaration();
944bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    } while (FD);
94567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
9461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
947784f21121a6c9418ebd86baa6814e36e1176c410John McCall  // Make sure the result is of the requested type.
948784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (!IsIncompleteFunction) {
949784f21121a6c9418ebd86baa6814e36e1176c410John McCall    assert(F->getType()->getElementType() == Ty);
950784f21121a6c9418ebd86baa6814e36e1176c410John McCall    return F;
951784f21121a6c9418ebd86baa6814e36e1176c410John McCall  }
952784f21121a6c9418ebd86baa6814e36e1176c410John McCall
9539cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
954784f21121a6c9418ebd86baa6814e36e1176c410John McCall  return llvm::ConstantExpr::getBitCast(F, PTy);
9550558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
9560558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
95774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
95874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
95974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
960b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
9612acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                 llvm::Type *Ty,
9621faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 bool ForVTable) {
96374391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
96474391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
9654a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
966bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
9675f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
9681faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
96974391b48b4791cded373683a3baf67314f358d50Chris Lattner}
97077ba708819285931932ecd33691a672bb59d221aEli Friedman
97174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
97274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
97374391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
9742acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
9755f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name,
976f85e193739c953358c865005855253af4f68a497John McCall                                     llvm::Attributes ExtraAttrs) {
977f85e193739c953358c865005855253af4f68a497John McCall  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
978f85e193739c953358c865005855253af4f68a497John McCall                                 ExtraAttrs);
97974391b48b4791cded373683a3baf67314f358d50Chris Lattner}
980bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
981da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregorstatic bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
982da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor                                 bool ConstantInit) {
98388786862424cb2d478516d911709dc19c962af9cJohn McCall  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
98420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
985da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor
986da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  if (Context.getLangOptions().CPlusPlus) {
987da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor    if (const RecordType *Record
988da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor          = Context.getBaseElementType(D->getType())->getAs<RecordType>())
9892bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor      return ConstantInit &&
9902bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor             cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
9912bb110125e0e5adb7c1c65d12adfa34151ca1c47Douglas Gregor             !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
99220e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  }
993da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor
99420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  return true;
99520e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman}
99620e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman
99774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
99874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
99974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
100074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
100174391b48b4791cded373683a3baf67314f358d50Chris Lattner///
100274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
100374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
1004f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
10055f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
10062acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                     llvm::PointerType *Ty,
1007c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     const VarDecl *D,
1008c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     bool UnnamedAddr) {
10093c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
1010f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
101199b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
10126a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
10136a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (D && !D->hasAttr<WeakAttr>())
10147270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
10156a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10166a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
10176a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
10186a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1019c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola    if (UnnamedAddr)
1020c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      Entry->setUnnamedAddr(true);
1021c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola
102274391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
1023570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
10241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
102599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
10263c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, Ty);
102799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
10281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
102967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
103067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
103167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1032f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
103367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
103467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
103567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
103667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
103767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
103867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
10391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
10411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
104299b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
1043f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                             0, MangledName, 0,
104456ebe5082da7411fb37479e230b52735f77cff35Eli Friedman                             false, Ty->getAddressSpace());
104549988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
104699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
104774391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
1048f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // FIXME: This code is overly simple and should be merged with other global
1049f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // handling.
1050da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor    GV->setConstant(DeclIsConstantGlobal(Context, D, false));
105149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
1052110e8e56af30363072c140285961592b0107f789John McCall    // Set linkage and visibility in case we never see a definition.
1053af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1054af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() != ExternalLinkage) {
105515e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      // Don't set internal linkage on declarations.
1056110e8e56af30363072c140285961592b0107f789John McCall    } else {
1057110e8e56af30363072c140285961592b0107f789John McCall      if (D->hasAttr<DLLImportAttr>())
1058110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
10590a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1060110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1061110e8e56af30363072c140285961592b0107f789John McCall
1062af14603ca61757cf4361b583b45639a04c57e651John McCall      // Set visibility on a declaration only if it's explicit.
1063af14603ca61757cf4361b583b45639a04c57e651John McCall      if (LV.visibilityExplicit())
1064af14603ca61757cf4361b583b45639a04c57e651John McCall        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1065110e8e56af30363072c140285961592b0107f789John McCall    }
106656ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
106756ebe5082da7411fb37479e230b52735f77cff35Eli Friedman    GV->setThreadLocal(D->isThreadSpecified());
106874391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
10691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1070f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GV;
107174391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1072eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
1073eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
10743bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlssonllvm::GlobalVariable *
10755f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
10762acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                      llvm::Type *Ty,
10773bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
10783bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
10793bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *OldGV = 0;
10803bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10813bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10823bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (GV) {
10833bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Check if the variable has the right type.
10843bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (GV->getType()->getElementType() == Ty)
10853bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      return GV;
10863bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10873bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Because C++ name mangling, the only way we can end up with an already
10883bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
108996eaf2992b5955d1470fc9cce7a96e7e1e3b4ea7Anders Carlsson      assert(GV->isDeclaration() && "Declaration has wrong type!");
10903bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV = GV;
10913bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
10923bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10933bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a new variable.
10943bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
10953bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                Linkage, 0, Name);
10963bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
10973bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (OldGV) {
10983bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Replace occurrences of the old variable if needed.
10993bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    GV->takeName(OldGV);
11003bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
11013bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (!OldGV->use_empty()) {
11023bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::Constant *NewPtrForOldDecl =
11033bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
11043bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
11053bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
11063bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
11073bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV->eraseFromParent();
11083bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
11093bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
11103bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  return GV;
11113bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson}
11123bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
111374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
111474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
111574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// then it will be greated with the specified type instead of whatever the
111674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
111774391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
11182acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                  llvm::Type *Ty) {
111974391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
112074391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
112174391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
112274391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
11231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
11242acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::PointerType *PTy =
1125207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1126f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
11275f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(D);
1128f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
112974391b48b4791cded373683a3baf67314f358d50Chris Lattner}
11303f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
113174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
113274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
113374391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
11342acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
11355f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name) {
11361de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1137c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                               true);
1138bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1139bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
114003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
114103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
114203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
11437520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
11447520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
11457520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
11467520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
11475f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef MangledName = getMangledName(D);
1148f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    if (!GetGlobalValue(MangledName)) {
1149555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      DeferredDecls[MangledName] = D;
115003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
11517520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
11527520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
11537520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
11547520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
115503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
115603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
115703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
11586fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregorvoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
11596fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  if (DefinitionRequired)
11606fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    getVTables().GenerateClassData(getVTableLinkage(Class), Class);
11616fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor}
11626fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor
11634b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregorllvm::GlobalVariable::LinkageTypes
1164046c294a43024874ff35656c6e785b64e72f1f36Anders CarlssonCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1165cb5d2d0647fdab2e36c85b417e03bf18916ce10cEli Friedman  if (RD->getLinkage() != ExternalLinkage)
1166dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return llvm::GlobalVariable::InternalLinkage;
1167dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1168dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (const CXXMethodDecl *KeyFunction
1169dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor                                    = RD->getASTContext().getKeyFunction(RD)) {
1170dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // If this class has a key function, use that to determine the linkage of
1171dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // the vtable.
11724b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    const FunctionDecl *Def = 0;
117306a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis    if (KeyFunction->hasBody(Def))
11744b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      KeyFunction = cast<CXXMethodDecl>(Def);
1175dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
11764b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    switch (KeyFunction->getTemplateSpecializationKind()) {
11774b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_Undeclared:
11784b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitSpecialization:
11796d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // When compiling with optimizations turned on, we emit all vtables,
11806d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // even if the key function is not defined in the current translation
11816d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // unit. If this is the case, use available_externally linkage.
11826d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        if (!Def && CodeGenOpts.OptimizationLevel)
11836d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson          return llvm::GlobalVariable::AvailableExternallyLinkage;
11846d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson
11854b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        if (KeyFunction->isInlined())
1186142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian          return !Context.getLangOptions().AppleKext ?
1187142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::GlobalVariable::LinkOnceODRLinkage :
1188142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::Function::InternalLinkage;
11894b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
11904b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        return llvm::GlobalVariable::ExternalLinkage;
11914b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
11924b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ImplicitInstantiation:
1193142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1194142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1195142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1196f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
11974b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDefinition:
1198142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1199142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::WeakODRLinkage :
1200142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1201f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
12024b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDeclaration:
12034b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // FIXME: Use available_externally linkage. However, this currently
12044b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // breaks LLVM's build due to undefined symbols.
12054b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1206142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian        return !Context.getLangOptions().AppleKext ?
1207142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1208142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
12094b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    }
1210dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1211dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
121253bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  if (Context.getLangOptions().AppleKext)
121353bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::Function::InternalLinkage;
121453bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian
1215dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  switch (RD->getTemplateSpecializationKind()) {
1216dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_Undeclared:
1217dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ExplicitSpecialization:
1218dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ImplicitInstantiation:
1219dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // FIXME: Use available_externally linkage. However, this currently
1220dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // breaks LLVM's build due to undefined symbols.
1221dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1222142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDeclaration:
122353bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::GlobalVariable::LinkOnceODRLinkage;
1224142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1225142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDefinition:
122653bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
12274b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  }
12284b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
12294b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  // Silence GCC warning.
123053bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian  return llvm::GlobalVariable::LinkOnceODRLinkage;
12314b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor}
12324b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
12332acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
123406f486ecd05bd6788da97c39164c1903a084c26dKen Dyck    return Context.toCharUnitsFromBits(
123506f486ecd05bd6788da97c39164c1903a084c26dKen Dyck      TheTargetData.getTypeStoreSizeInBits(Ty));
1236687cc4a850b59116efee061018f0d8df50728b82Ken Dyck}
1237687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
1238bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
12398f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
124077ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
12416c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  bool NonConstInit = false;
12421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
124331310a21fb2a9f13950f864f681c86080b05d5b2Sebastian Redl  const Expr *InitExpr = D->getAnyInitializer();
12443bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson
12453bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson  if (!InitExpr) {
1246cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
124703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
124803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
124903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
125003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
125103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
125203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
125303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
125403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
125503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1256b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    Init = EmitNullConstant(D->getType());
125777ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
1258c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor    Init = EmitConstantExpr(InitExpr, D->getType());
12596e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
12603bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson      QualType T = InitExpr->getType();
1261c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor      if (D->getType()->isReferenceType())
1262c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor        T = D->getType();
1263c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor
126489ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      if (getLangOptions().CPlusPlus) {
126589ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = EmitNullConstant(T);
12666c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman        NonConstInit = true;
126789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      } else {
126889ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        ErrorUnsupported(D, "static initializer");
126989ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
127089ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      }
1271bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    } else {
1272bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // We don't need an initializer, so remove the entry for the delayed
1273bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // initializer position (just in case this entry was delayed).
1274bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      if (getLangOptions().CPlusPlus)
1275bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall        DelayedCXXInitPosition.erase(D);
12766e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
12778f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
12788e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
12792acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type* InitType = Init->getType();
1280570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
12811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1282570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
1283570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
12849d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
12859d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           // all zero index gep.
12869d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1287570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
1288570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
12891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1290570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
1291570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
12921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1293570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
1294570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
1295570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
1296570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
1297570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
1298570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
1299570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
1300570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
1301570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
1302570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
1303570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
1304207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      GV->getType()->getAddressSpace() !=
1305207f4d8543529221932af82836016a2ef066c917Peter Collingbourne        getContext().getTargetAddressSpace(ASTTy)) {
13061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1307f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Move the old entry aside so that we'll create a new one.
13085f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    Entry->setName(StringRef());
1309232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
1310570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
1311570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
13120558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
131377ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
13141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *NewPtrForOldDecl =
13153c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1316570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
131777ba708819285931932ecd33691a672bb59d221aEli Friedman
131877ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
1319570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
132077ba708819285931932ecd33691a672bb59d221aEli Friedman  }
132177ba708819285931932ecd33691a672bb59d221aEli Friedman
132277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
132377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, GV);
13248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
132588a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
1326e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1327e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // If it is safe to mark the global 'constant', do so now.
1328e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  GV->setConstant(false);
1329da55074866ca2fe7f718c5d3334648d6e340fb15Douglas Gregor  if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1330e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    GV->setConstant(true);
13311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
13328b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1333354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
133488a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
1335354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage =
1336354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GetLLVMLinkageVarDefinition(D, GV);
1337354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  GV->setLinkage(Linkage);
1338354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1339354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    // common vars aren't constant even if declared const.
1340354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GV->setConstant(false);
1341354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1342354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  SetCommonAttributes(D, GV);
1343354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
13443030eb82593097502469a8b3fc26112c79c75605John McCall  // Emit the initializer function if necessary.
13453030eb82593097502469a8b3fc26112c79c75605John McCall  if (NonConstInit)
13463030eb82593097502469a8b3fc26112c79c75605John McCall    EmitCXXGlobalVarDeclInitFunc(D, GV);
13473030eb82593097502469a8b3fc26112c79c75605John McCall
1348354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // Emit global variable debug information.
1349aa11289f754d220c9c155b68a4f84cdcfcefef6aDevang Patel  if (CGDebugInfo *DI = getModuleDebugInfo()) {
1350354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    DI->setLocation(D->getLocation());
1351354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    DI->EmitGlobalVariable(GV, D);
1352354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  }
1353354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian}
1354354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1355354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianllvm::GlobalValue::LinkageTypes
1356354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz JahanianCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1357354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                           llvm::GlobalVariable *GV) {
135890e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1359a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  if (Linkage == GVA_Internal)
1360354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::InternalLinkage;
136140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLImportAttr>())
1362354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLImportLinkage;
136340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLExportAttr>())
1364354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLExportLinkage;
1365e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1366e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (GV->isConstant())
1367354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
1368e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    else
1369354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakAnyLinkage;
13708f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor  } else if (Linkage == GVA_TemplateInstantiation ||
13718f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor             Linkage == GVA_ExplicitTemplateInstantiation)
137299ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return llvm::GlobalVariable::WeakODRLinkage;
1373a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher  else if (!getLangOptions().CPlusPlus &&
1374a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1375a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher             D->getAttr<CommonAttr>()) &&
1376309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
1377ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1378ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<WeakImportAttr>()) {
137991f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher    // Thread local vars aren't considered common linkage.
1380354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::GlobalVariable::CommonLinkage;
1381686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
1382354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return llvm::GlobalVariable::ExternalLinkage;
138388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
13845f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1385bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1386bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1387bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// existing call uses of the old function in the module, this adjusts them to
1388bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// call the new function directly.
1389bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
1390bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
1391bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
1392bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1393bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// run at -O0.
1394bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1395bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                      llvm::Function *NewFn) {
1396bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // If we're redefining a global as a function, don't transform it.
1397bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1398bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (OldFn == 0) return;
13991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14002acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *NewRetTy = NewFn->getReturnType();
14015f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Value*, 4> ArgList;
1402bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1403bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1404dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer       UI != E; ) {
1405bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1406dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1407dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
14088670cd3ea4dfbf86caacd270ec2441e9949bbb6aGabor Greif    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
140935db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif    llvm::CallSite CS(CI);
1410dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    if (!CI || !CS.isCallee(I)) continue;
14111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1412bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the return types don't match exactly, and if the call isn't dead, then
1413bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // we can't transform this call.
1414bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (CI->getType() != NewRetTy && !CI->use_empty())
1415bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
1416bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
141740f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get the attribute list.
141840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
141940f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::AttrListPtr AttrList = CI->getAttributes();
142040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
142140f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get any return attributes.
142240f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::Attributes RAttrs = AttrList.getRetAttributes();
142340f9c302f23a35611cd354f40b22b37f2c554a40John McCall
142440f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Add the return attributes.
142540f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (RAttrs)
142640f9c302f23a35611cd354f40b22b37f2c554a40John McCall      AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
142740f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1428bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the function was passed too few arguments, don't transform.  If extra
1429bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // arguments were passed, we silently drop them.  If any of the types
1430bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // mismatch, we don't transform.
1431bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    unsigned ArgNo = 0;
1432bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    bool DontTransform = false;
1433bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1434bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
143535db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif      if (CS.arg_size() == ArgNo ||
143635db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1437bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        DontTransform = true;
1438bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
1439bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
144040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
144140f9c302f23a35611cd354f40b22b37f2c554a40John McCall      // Add any parameter attributes.
144240f9c302f23a35611cd354f40b22b37f2c554a40John McCall      if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
144340f9c302f23a35611cd354f40b22b37f2c554a40John McCall        AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1444bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1445bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (DontTransform)
1446bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
14471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
144840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
144940f9c302f23a35611cd354f40b22b37f2c554a40John McCall      AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
145040f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1451bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
1452bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
14536ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
14544c7d9f1507d0f102bd4133bba63348636facd469Jay Foad    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1455bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.clear();
1456ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    if (!NewCall->getType()->isVoidTy())
1457bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      NewCall->takeName(CI);
145840f9c302f23a35611cd354f40b22b37f2c554a40John McCall    NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
145940f9c302f23a35611cd354f40b22b37f2c554a40John McCall                                                  AttrVec.end()));
1460ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    NewCall->setCallingConv(CI->getCallingConv());
1461bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1462bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
146300549fcec0490b2daf27543e532f94adbb186063Chris Lattner    if (!CI->use_empty())
146400549fcec0490b2daf27543e532f94adbb186063Chris Lattner      CI->replaceAllUsesWith(NewCall);
14653b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel
1466c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    // Copy debug location attached to CI.
1467c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    if (!CI->getDebugLoc().isUnknown())
1468c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner      NewCall->setDebugLoc(CI->getDebugLoc());
1469bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CI->eraseFromParent();
1470bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1471bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1472bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1473bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1474b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1475b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1476d26bc76c98006609002d9930f8840490e88ac5b5John McCall
14771f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  // Compute the function info and LLVM type.
1478d26bc76c98006609002d9930f8840490e88ac5b5John McCall  const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
14791f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  bool variadic = false;
14801f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
14811f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall    variadic = fpt->isVariadic();
14822acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
1483d26bc76c98006609002d9930f8840490e88ac5b5John McCall
14849fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
1485b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
14861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14870558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
14880558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
14890558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
14900558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
14910558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
14921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14940558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1495bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
14961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
149742745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
1498bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
14990558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
150034809507232bc4c3c4840c7d092c7440219fddafChris Lattner
150162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
150262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
150362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
150462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
150562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
150662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
1507f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // (e.g. "int f(int x)").  Move the old function aside so that it
1508f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // doesn't interfere with GetAddrOfFunction.
15095f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    OldFn->setName(StringRef());
1510b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
15111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1512bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If this is an implementation of a function without a prototype, try to
1513bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // replace any existing uses of the function (which may be calls) with uses
1514bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // of the new function
15159fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    if (D->getType()->isFunctionNoProtoType()) {
1516bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
15179fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
15189fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
15191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
152062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
1521bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
15221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      llvm::Constant *NewPtrForOldDecl =
15233c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1524bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1525bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
15261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
152762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
1528bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
15291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15300558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
1531bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
15321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1533112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // We need to set linkage and visibility on the function before
1534112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // generating code for it because various parts of IR generation
1535112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // want to propagate this information down (e.g. to local static
1536112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // declarations).
15370558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
15388b2423361648c39a7d8a3c5e8129e12006deac32John McCall  setFunctionLinkage(D, Fn);
1539bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1540112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
15410ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(Fn, D);
1542112c967bd5c862a0f5d7913aa06700c048807db8John McCall
1543d26bc76c98006609002d9930f8840490e88ac5b5John McCall  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
15446379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
15457c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
15467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
15471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
154840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1549219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
155040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1551219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
155277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
155377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, Fn);
1554bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1555bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1556f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1557f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
155840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  const AliasAttr *AA = D->getAttr<AliasAttr>();
1559bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
1560bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
15615f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
1562f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1563f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // If there is a definition in the module, then it wins over the alias.
1564f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // This is dubious, but allow it to be safe.  Just ignore the alias.
1565f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1566f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  if (Entry && !Entry->isDeclaration())
1567f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return;
15681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15692acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1570bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1571bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
1572bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
1573bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
1574bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
15751faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
15761faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
1577bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
1578f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
157996e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                                    llvm::PointerType::getUnqual(DeclTy), 0);
1580bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1581bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
15821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *GA =
1583bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
1584bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
1585bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
15861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1587bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
1588f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    assert(Entry->isDeclaration());
1589f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1590bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
1591bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
1592bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
1593bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
1594bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
1595bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
1596bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
1597f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    GA->takeName(Entry);
15981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15993c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1600bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
1601bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
1602f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else {
16039a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    GA->setName(MangledName);
1604bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
16051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16067c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
16077c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
16087c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
160940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<DLLExportAttr>()) {
16107c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
16117c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
161206a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis      if (FD->hasBody())
16137c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
16147c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
16157c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
16167c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
16171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (D->hasAttr<WeakAttr>() ||
161811e8ce7380856abee188b237c2600272df2ed09dRafael Espindola             D->hasAttr<WeakRefAttr>() ||
16190a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             D->isWeakImported()) {
16207c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
16217c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
16227c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
16237c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
1624bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
1625bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
16268dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
16272d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                                            ArrayRef<llvm::Type*> Tys) {
1628df983a8bcbbcea911b8dce283f044787df119d50Jay Foad  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
16298dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer                                         Tys);
16307acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
1631bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
16321d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
16331d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
16341d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         const StringLiteral *Literal,
163570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                         bool TargetIsLSB,
16361d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         bool &IsUTF16,
16371d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         unsigned &StringLength) {
16385f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef String = Literal->getString();
16392f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  unsigned NumBytes = String.size();
16401d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1641f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // Check for simple case.
1642f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  if (!Literal->containsNonAsciiOrNull()) {
1643f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    StringLength = NumBytes;
16442f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    return Map.GetOrCreateValue(String);
1645f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
1646f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
16471d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  // Otherwise, convert the UTF8 literals into a byte string.
16485f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<UTF16, 128> ToBuf(NumBytes);
16492f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  const UTF8 *FromPtr = (UTF8 *)String.data();
16501d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  UTF16 *ToPtr = &ToBuf[0];
16511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1652e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1653e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           &ToPtr, ToPtr + NumBytes,
1654e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           strictConversion);
16551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
165670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
16571d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
165870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
165970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // Render the UTF-16 string into a byte array and convert to the target byte
166070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // order.
166170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  //
166270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // FIXME: This isn't something we should need to do here.
166370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  llvm::SmallString<128> AsBytes;
166470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  AsBytes.reserve(StringLength * 2);
166570ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  for (unsigned i = 0; i != StringLength; ++i) {
166670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    unsigned short Val = ToBuf[i];
166770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    if (TargetIsLSB) {
166870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
166970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val >> 8);
167070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    } else {
167170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val >> 8);
167270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar      AsBytes.push_back(Val & 0xFF);
167370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar    }
167470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  }
1675434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  // Append one extra null character, the second is automatically added by our
1676434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  // caller.
1677434da48d0e35764f18b3fc96c75504746050b046Daniel Dunbar  AsBytes.push_back(0);
167870ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
16791d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  IsUTF16 = true;
16805f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
16811d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar}
16821d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1683cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanianstatic llvm::StringMapEntry<llvm::Constant*> &
1684cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz JahanianGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1685cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian		       const StringLiteral *Literal,
1686cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian		       unsigned &StringLength)
1687cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian{
16885f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner	StringRef String = Literal->getString();
1689cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian	StringLength = String.size();
1690cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian	return Map.GetOrCreateValue(String);
1691cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian}
1692cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian
16931d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarllvm::Constant *
16941d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
16951d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  unsigned StringLength = 0;
16961d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool isUTF16 = false;
16971d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringMapEntry<llvm::Constant*> &Entry =
16981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
169970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             getTargetData().isLittleEndian(),
170070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             isUTF16, StringLength);
17011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17021d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
17031d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return C;
17041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17050032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *Zero =
17060032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
17073e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
17081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17099d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // If we don't already have it, get __CFConstantStringClassReference.
1710c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
17112acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
171296e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    Ty = llvm::ArrayType::get(Ty, 0);
17131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *GV = CreateRuntimeVariable(Ty,
17149d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                                           "__CFConstantStringClassReference");
17153e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
17163e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
1717a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad      llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1718c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
17191eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1720e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
17213e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
17222acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::StructType *STy =
1723e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1724e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
17255add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  std::vector<llvm::Constant*> Fields(4);
172644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
1727c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
17285add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[0] = CFConstantStringClassRef;
17291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1730c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
17312acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
17321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
17335add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    llvm::ConstantInt::get(Ty, 0x07C8);
17345add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1735c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
17360032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1737a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
173895b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  llvm::GlobalValue::LinkageTypes Linkage;
1739278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner  bool isConstant;
1740a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
1741278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // FIXME: why do utf strings get "_" labels instead of "L" labels?
174295b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
1743278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1744278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // does make plain ascii ones writable.
1745278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    isConstant = true;
1746a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  } else {
1747584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1748584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // when using private linkage. It is not clear if this is a bug in ld
1749584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // or a reasonable new restriction.
1750dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1751278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    isConstant = !Features.WritableStrings;
1752a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
1753278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
17541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
1755278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1756278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner                             ".str");
1757b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  GV->setUnnamedAddr(true);
1758a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
17594da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
17604da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    GV->setAlignment(Align.getQuantity());
1761f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
1762f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1763f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
1764a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
1765a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
17665add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1767c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
1768c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
17695add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
17701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1771c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
177208e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  C = llvm::ConstantStruct::get(STy, Fields);
17731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
17741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                llvm::GlobalVariable::PrivateLinkage, C,
177595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                                "_unnamed_cfstring_");
1776bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
17778e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
17781d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  Entry.setValue(GV);
17791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17800c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
1781c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
178245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
178345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregorstatic RecordDecl *
178445c4ea75b235de94f44bf96843624e6a559e4c00Douglas GregorCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
178545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                 DeclContext *DC, IdentifierInfo *Id) {
178645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  SourceLocation Loc;
178745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (Ctx.getLangOptions().CPlusPlus)
178845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
178945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  else
179045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
179145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor}
179245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
179333e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanianllvm::Constant *
17944c73307c74764ba99e1379677fe92af72f676531Fariborz JahanianCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
17952bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  unsigned StringLength = 0;
17962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::StringMapEntry<llvm::Constant*> &Entry =
1797cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
17982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
17992bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (llvm::Constant *C = Entry.getValue())
18002bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    return C;
18012bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18022bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zero =
18032bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
18042bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zeros[] = { Zero, Zero };
18052bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
1806ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  // If we don't already have it, get _NSConstantStringClassReference.
18074c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  if (!ConstantStringClassRef) {
18084c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    std::string StringClass(getLangOptions().ObjCConstantStringClass);
18092acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
18104c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::Constant *GV;
18116f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    if (Features.ObjCNonFragileABI) {
181225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
181325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
181425dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "OBJC_CLASS_$_" + StringClass;
18156f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      GV = getObjCRuntime().GetClassGlobal(str);
18166f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Make sure the result is of the correct type.
18172acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
18186f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
18196f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian        llvm::ConstantExpr::getBitCast(GV, PTy);
18206f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    } else {
182125dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
182225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "_NSConstantStringClassReference"
182325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "_" + StringClass + "ClassReference";
18242acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
182525dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      GV = CreateRuntimeVariable(PTy, str);
18266f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Decay array -> ptr
18276f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
1828a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad        llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
18294c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    }
18302bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
183145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
183245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (!NSConstantStringType) {
183345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Construct the type for a constant NSString.
183445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
183545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                     Context.getTranslationUnitDecl(),
183645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                   &Context.Idents.get("__builtin_NSString"));
183745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->startDefinition();
183845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
183945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType FieldTypes[3];
184045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
184145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const int *isa;
184245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
184345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const char *str;
184445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
184545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // unsigned int length;
184645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[2] = Context.UnsignedIntTy;
184745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
184845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Create fields
184945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    for (unsigned i = 0; i < 3; ++i) {
185045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context, D,
185145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(),
185245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(), 0,
185345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
185445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*BitWidth=*/0,
185545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*Mutable=*/false,
185645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*HasInit=*/false);
185745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      Field->setAccess(AS_public);
185845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      D->addDecl(Field);
185945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    }
186045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
186145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->completeDefinition();
186245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType NSTy = Context.getTagDeclType(D);
186345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
186445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  }
18652bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18662bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  std::vector<llvm::Constant*> Fields(3);
18672bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18682bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // Class pointer.
18694c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  Fields[0] = ConstantStringClassRef;
18702bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18712bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String pointer.
18722bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
18732bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18742bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage;
18752bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isConstant;
1876cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  Linkage = llvm::GlobalValue::PrivateLinkage;
1877cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  isConstant = !Features.WritableStrings;
18782bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18792bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalVariable *GV =
18802bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
18812bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                           ".str");
1882803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola  GV->setUnnamedAddr(true);
1883cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1884cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  GV->setAlignment(Align.getQuantity());
1885a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
18862bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18872bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String length.
18882acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
18892bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
18902bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
18912bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // The struct.
189245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
18932bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
18942bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
18952bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                "_unnamed_nsstring_");
18962bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // FIXME. Fix section.
1897ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  if (const char *Sect =
1898ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian        Features.ObjCNonFragileABI
1899bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          ? getContext().getTargetInfo().getNSStringNonFragileABISection()
1900bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          : getContext().getTargetInfo().getNSStringSection())
19012bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setSection(Sect);
19022bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Entry.setValue(GV);
19032bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
19042bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  return GV;
190533e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian}
190633e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian
19070815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas GregorQualType CodeGenModule::getObjCFastEnumerationStateType() {
19080815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  if (ObjCFastEnumerationStateType.isNull()) {
19090815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
19100815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                     Context.getTranslationUnitDecl(),
19110815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                      &Context.Idents.get("__objcFastEnumerationState"));
19120815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->startDefinition();
19130815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
19140815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    QualType FieldTypes[] = {
19150815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.UnsignedLongTy,
19160815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.getObjCIdType()),
19170815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.UnsignedLongTy),
19180815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getConstantArrayType(Context.UnsignedLongTy,
19190815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                           llvm::APInt(32, 5), ArrayType::Normal, 0)
19200815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    };
19210815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
19220815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    for (size_t i = 0; i < 4; ++i) {
19230815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context,
19240815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           D,
19250815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(),
19260815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(), 0,
19270815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
19280815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*BitWidth=*/0,
19290815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*Mutable=*/false,
19300815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*HasInit=*/false);
19310815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Field->setAccess(AS_public);
19320815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      D->addDecl(Field);
19330815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    }
19340815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
19350815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->completeDefinition();
19360815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
19370815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  }
19380815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
19390815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  return ObjCFastEnumerationStateType;
19400815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor}
19410815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
19426143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetStringForStringLiteral - Return the appropriate bytes for a
19431e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar/// string literal, properly padded to match the literal type.
19446143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
19453b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck  const ASTContext &Context = getContext();
19461e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const ConstantArrayType *CAT =
19473b8037a8c6f462e51f75c82b3d7fe1b8dbcf06c0Ken Dyck    Context.getAsConstantArrayType(E->getType());
19481e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  assert(CAT && "String isn't pointer or array!");
19491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1950dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  // Resize the string to the right size.
19511e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  uint64_t RealLen = CAT->getSize().getZExtValue();
19521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19535cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  switch (E->getKind()) {
19545cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  case StringLiteral::Ascii:
19555cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  case StringLiteral::UTF8:
19565cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    break;
19575cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  case StringLiteral::Wide:
1958bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth();
19595cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    break;
19605cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  case StringLiteral::UTF16:
1961bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth();
19625cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    break;
19635cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  case StringLiteral::UTF32:
1964bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor    RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth();
19655cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor    break;
19665cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  }
19671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19682f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  std::string Str = E->getString().str();
19691e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  Str.resize(RealLen, '\0');
19701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19711e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  return Str;
19721e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar}
19731e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
19746143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
19756143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
19766143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
19776143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
19786143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // FIXME: This can be more efficient.
19797eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1980a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  CharUnits Align = getContext().getTypeAlignInChars(S->getType());
1981a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S),
1982a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                              /* GlobalName */ 0,
1983a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                              Align.getQuantity());
19845cee1195584fa8672253139c86e922daeda69b9eDouglas Gregor  if (S->isWide() || S->isUTF16() || S->isUTF32()) {
19857eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman    llvm::Type *DestTy =
19867eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
19877eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman    C = llvm::ConstantExpr::getBitCast(C, DestTy);
19887eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  }
19897eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  return C;
19906143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
19916143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
1992eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1993eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
1994eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
1995eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1996eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
1997eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1998a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
1999a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
2000eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
2001eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2002eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2003a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
2004a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCallstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
200545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
20065fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
2007a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             const char *GlobalName,
2008a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             unsigned Alignment) {
20096143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
20100032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C =
20110032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
20121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
201345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
20141257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  llvm::GlobalVariable *GV =
20151257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
20161257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             llvm::GlobalValue::PrivateLinkage,
20171257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             C, GlobalName);
2018a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  GV->setAlignment(Alignment);
20191257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  GV->setUnnamedAddr(true);
20201257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  return GV;
202145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
202245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
20236143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
20246143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
20256143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
20266143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
20276143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
20286143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
20296143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
20306143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
20315f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2032a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       const char *GlobalName,
2033a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       unsigned Alignment) {
20348e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  bool IsConstant = !Features.WritableStrings;
20358e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
20368e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
20378e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
203895b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GlobalName = ".str";
20398e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
20408e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
20418e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!IsConstant)
2042a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
20431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2044a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
20459de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    ConstantStringMap.GetOrCreateValue(Str);
204645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
2047a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2048a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    if (Alignment > GV->getAlignment()) {
2049a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      GV->setAlignment(Alignment);
2050a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    }
2051a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GV;
2052a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  }
205345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
205445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
2055a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
2056a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  Entry.setValue(GV);
2057a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GV;
205845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
20596143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
20606143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
20619de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer/// array containing the literal and a terminating '\0'
20626143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
20639de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2064a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        const char *GlobalName,
2065a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        unsigned Alignment) {
20665f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2067a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
20686143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
206941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2070af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
2071af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
20721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::EmitObjCPropertyImplementations(const
2073af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
20741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCImplementationDecl::propimpl_iterator
207517945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2076af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCPropertyImplDecl *PID = *i;
20771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2078af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
2079af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2080af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2081af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2082af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
2083af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // been overridden. Note that ::isSynthesized is not the method
2084af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
2085af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
2086af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
208717945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (!D->getInstanceMethod(PD->getGetterName()))
2088fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
2089fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2090af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
209117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis          !D->getInstanceMethod(PD->getSetterName()))
2092fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
2093fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2094af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
2095af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2096af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
2097af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2098e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCallstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
2099db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2100db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2101e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall       ivar; ivar = ivar->getNextIvar())
2102e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (ivar->getType().isDestructedType())
2103e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      return true;
2104e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2105e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return false;
2106e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
2107e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2108109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// EmitObjCIvarInitializations - Emit information for ivar initialization
2109109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// for an implementation.
2110109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanianvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2111e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2112e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (needsDestructMethod(D)) {
2113e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2114e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2115e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    ObjCMethodDecl *DTORMethod =
2116e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
211775cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             cxxSelector, getContext().VoidTy, 0, D,
211875cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isInstance=*/true, /*isVariadic=*/false,
211975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                          /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
212075cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isDefined=*/false, ObjCMethodDecl::Required);
2121e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    D->addInstanceMethod(DTORMethod);
2122e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2123f85e193739c953358c865005855253af4f68a497John McCall    D->setHasCXXStructors(true);
2124e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  }
2125e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2126e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // If the implementation doesn't have any ivar initializers, we don't need
2127e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // a .cxx_construct.
2128827bbcc8a9115782693b21030a45378abe5c1862David Chisnall  if (D->getNumIvarInitializers() == 0)
2129109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    return;
2130109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
2131e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2132e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2133109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // The constructor returns 'self'.
2134109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2135109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(),
2136109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(), cxxSelector,
2137109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                getContext().getObjCIdType(), 0,
213875cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                D, /*isInstance=*/true,
213975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isVariadic=*/false,
214075cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isSynthesized=*/true,
214175cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isImplicitlyDeclared=*/true,
214275cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isDefined=*/false,
2143109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                ObjCMethodDecl::Required);
2144109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  D->addInstanceMethod(CTORMethod);
2145109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2146f85e193739c953358c865005855253af4f68a497John McCall  D->setHasCXXStructors(true);
2147109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian}
2148109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
214991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
2150984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
215117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2152984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
2153984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
2154984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
2155984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
215691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
215791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2158f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2159f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
216091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
216191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
216291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
216391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
216417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
216591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson       I != E; ++I)
216691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
216791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
216891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
216941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
217041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
217141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
217241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
217341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
217441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
217541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
217641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
217716e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  // Ignore dependent declarations.
217816e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
217916e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    return;
21801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
218141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
2182293361afd4199c92aabff9267fddea890943c586Anders Carlsson  case Decl::CXXConversion:
21832b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
218441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
218516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    // Skip function templates
21868387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
21878387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
218816e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      return;
21891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2190555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<FunctionDecl>(D));
2191555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    break;
2192555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson
219341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
2194555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<VarDecl>(D));
219541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
219641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
219726fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // Indirect fields from global anonymous structs and unions can be
219826fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // ignored; only the actual variable requires IR gen support.
219926fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  case Decl::IndirectField:
220026fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall    break;
220126fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
220295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
220341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
2204984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
220541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
22069cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    // No code generation needed.
22079d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  case Decl::UsingShadow:
22089cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  case Decl::Using:
2209dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  case Decl::UsingDirective:
2210127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::ClassTemplate:
2211127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::FunctionTemplate:
22123e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  case Decl::TypeAliasTemplate:
2213018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  case Decl::NamespaceAlias:
22146a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor  case Decl::Block:
22159cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    break;
221695d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
22171fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    // Skip function templates
22188387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
22198387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
22201fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson      return;
22211fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
222295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
222395d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
222427ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
22258387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
22268387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      return;
222727ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
222827ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
222936674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
223036674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  case Decl::StaticAssert:
223136674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    // Nothing to do.
223236674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    break;
223336674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
223495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
22351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
223638e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
223741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCClass:
223841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCForwardProtocol:
2239b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
224041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2241000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian
2242baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  case Decl::ObjCCategory: {
2243baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2244baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    if (CD->IsClassExtension() && CD->hasSynthBitfield())
2245baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner      Context.ResetObjCLayout(CD->getClassInterface());
2246baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    break;
2247baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  }
2248285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
224941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCProtocol:
2250e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
225141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
225241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
225341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
2254af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
2255af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
2256e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
225741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
225841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2259af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
2260af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2261000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian    if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2262000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian      Context.ResetObjCLayout(OMD->getClassInterface());
2263af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
2264109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    EmitObjCIvarInitializations(OMD);
2265e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateClass(OMD);
226641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
22671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
226841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
226941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
227041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
22716fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (OMD->getBody())
227241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
227341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
227441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
22751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::ObjCCompatibleAlias:
2276305c658ebce84bb9833fc0e7675554656453b8e8Fariborz Jahanian    // compatibility-alias is a directive and has no code gen.
227741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
227841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
227991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
228091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
228141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
228241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
228341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
228441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
22855f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef AsmString = AD->getAsmString()->getString();
22861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
228741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
228841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
228941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
22909f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner    else if (*--S.end() == '\n')
22919f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner      getModule().setModuleInlineAsm(S + AsmString.str());
229241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
22938d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
229441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
229541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
22961eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
22971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  default:
2298f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // Make sure we handled everything we should, every other kind is a
2299f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2300f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // function. Need to recode Decl::Kind to do that easily.
230141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
230241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
230341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
2304744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2305744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Turns the given pointer into a constant.
2306744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2307744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                          const void *Ptr) {
2308744016dde06fcffd50931e94a98c850f8b12cd87John McCall  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
23092acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2310744016dde06fcffd50931e94a98c850f8b12cd87John McCall  return llvm::ConstantInt::get(i64, PtrInt);
2311744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2312744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2313744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2314744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::NamedMDNode *&GlobalMetadata,
2315744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   GlobalDecl D,
2316744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::GlobalValue *Addr) {
2317744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (!GlobalMetadata)
2318744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GlobalMetadata =
2319744016dde06fcffd50931e94a98c850f8b12cd87John McCall      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2320744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2321744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // TODO: should we report variant information for ctors/dtors?
2322744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::Value *Ops[] = {
2323744016dde06fcffd50931e94a98c850f8b12cd87John McCall    Addr,
2324744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2325744016dde06fcffd50931e94a98c850f8b12cd87John McCall  };
23266f141659cab11109d9931d92d0988f8850778de3Jay Foad  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2327744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2328744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2329744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes associating all the global values in the
2330744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// current module with the Decls they came from.  This is useful for
2331744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// projects using IR gen as a subroutine.
2332744016dde06fcffd50931e94a98c850f8b12cd87John McCall///
2333744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Since there's currently no way to associate an MDNode directly
2334744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with an llvm::GlobalValue, we create a global named metadata
2335744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with the name 'clang.global.decl.ptrs'.
2336744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenModule::EmitDeclMetadata() {
2337744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2338744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2339744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // StaticLocalDeclMap
23405f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2341744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2342744016dde06fcffd50931e94a98c850f8b12cd87John McCall       I != E; ++I) {
2343744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2344744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2345744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2346744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2347744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2348744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes for all the local variables in the current
2349744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// function.
2350744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenFunction::EmitDeclMetadata() {
2351744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (LocalDeclMap.empty()) return;
2352744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2353744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::LLVMContext &Context = getLLVMContext();
2354744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2355744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Find the unique metadata ID for this name.
2356744016dde06fcffd50931e94a98c850f8b12cd87John McCall  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2357744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2358744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2359744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2360744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2361744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2362744016dde06fcffd50931e94a98c850f8b12cd87John McCall    const Decl *D = I->first;
2363744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::Value *Addr = I->second;
2364744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2365744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2366744016dde06fcffd50931e94a98c850f8b12cd87John McCall      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
23676f141659cab11109d9931d92d0988f8850778de3Jay Foad      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2368744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2369744016dde06fcffd50931e94a98c850f8b12cd87John McCall      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2370744016dde06fcffd50931e94a98c850f8b12cd87John McCall      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2371744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2372744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2373744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2374673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
23753dc05418538c719fea48b906bfa4febe5296e126Nick Lewyckyvoid CodeGenModule::EmitCoverageFile() {
23763dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky  if (!getCodeGenOpts().CoverageFile.empty()) {
23775ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
23785ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
23795ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::LLVMContext &Ctx = TheModule.getContext();
23803dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky      llvm::MDString *CoverageFile =
23813dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
23825ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
23835ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *CU = CUNode->getOperand(i);
23843dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky        llvm::Value *node[] = { CoverageFile, CU };
23855ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
23865ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        GCov->addOperand(N);
23875ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      }
23885ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
23895ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  }
23905ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky}
2391