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"
196c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne#include "CGCUDARuntime.h"
204c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall#include "CGCXXABI.h"
21af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGObjCRuntime.h"
228c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne#include "CGOpenCLRuntime.h"
2382d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov#include "TargetInfo.h"
2406057cef0bcd7804e80f3ce2bbe352178396c715Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
255f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
26687cc4a850b59116efee061018f0d8df50728b82Ken Dyck#include "clang/AST/CharUnits.h"
27c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2821ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
29af896897f7485176f43d40c4adced7efb0fb2b06Douglas Gregor#include "clang/AST/DeclTemplate.h"
3014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne#include "clang/AST/Mangle.h"
311a5e0d7f18485e4fb958f96dcddff3e4486a4069Anders Carlsson#include "clang/AST/RecordLayout.h"
32a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola#include "clang/AST/RecursiveASTVisitor.h"
33bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola#include "clang/Basic/Builtins.h"
342c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/Basic/Diagnostic.h"
358bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
365f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
37e9b7d8ace8674585818990cff585daae7745bd88Steve Naroff#include "clang/Basic/ConvertUTF.h"
38ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman#include "llvm/CallingConv.h"
39bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner#include "llvm/Module.h"
405f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Intrinsics.h"
41d5b8902c0329d80a216803b58dc3b689349a0c11Chris Lattner#include "llvm/LLVMContext.h"
4219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl#include "llvm/ADT/APSInt.h"
436374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall#include "llvm/ADT/Triple.h"
44c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola#include "llvm/Target/Mangler.h"
4520ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov#include "llvm/Target/TargetData.h"
466ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif#include "llvm/Support/CallSite.h"
4778f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner#include "llvm/Support/ErrorHandling.h"
485f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
495f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
505f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
5177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougestatic const char AnnotationSection[] = "llvm.metadata";
5277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
53f16aa103d3afd42fbca2ab346f191bf745cec092John McCallstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
58f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  }
59f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
60f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  llvm_unreachable("invalid C++ ABI kind");
61f16aa103d3afd42fbca2ab346f191bf745cec092John McCall}
62f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
635f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
642811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
65468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall                             llvm::Module &M, const llvm::TargetData &TD,
66d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie                             DiagnosticsEngine &diags)
674e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
68468ec6c0266e48fccb26ce50d5b915c645bb3c7bJohn McCall    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
69f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    ABI(createCXXABI(*this)),
70de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    Types(*this),
713d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    TBAA(0),
726c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73b49bd27b334a6c4e3bf9d810a7d5b022578f1194Dan Gohman    DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74b49bd27b334a6c4e3bf9d810a7d5b022578f1194Dan Gohman    RRData(0), CFConstantStringClassRef(0),
756c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    ConstantStringClassRef(0), NSConstantStringType(0),
76673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    VMContext(M.getContext()),
77673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockObjectAssign(0), BlockObjectDispose(0),
79d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockDescriptorType(0), GenericBlockLiteralType(0) {
808b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner
818b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  // Initialize the type cache.
828b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  llvm::LLVMContext &LLVMContext = M.getContext();
838b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  VoidTy = llvm::Type::getVoidTy(LLVMContext);
848b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
858b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
868b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
878b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
888b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  FloatTy = llvm::Type::getFloatTy(LLVMContext);
898b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
908b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
918b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  PointerAlignInBytes =
928b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
938b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
948b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
958b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8PtrTy = Int8Ty->getPointerTo(0);
968b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
978b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner
984e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.ObjC1)
998c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createObjCRuntime();
1004e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.OpenCL)
1018c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createOpenCLRuntime();
1024e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CUDA)
1036c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    createCUDARuntime();
104e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
1053d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  // Enable TBAA unless it's suppressed.
1063d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
1074e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    TBAA = new CodeGenTBAA(Context, VMContext, getLangOpts(),
1080b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman                           ABI.getMangleContext());
1093d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
110e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // If debug info or coverage generation is enabled, create the CGDebugInfo
111e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // object.
112e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
113e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky      CodeGenOpts.EmitGcovNotes)
114e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky    DebugInfo = new CGDebugInfo(*this);
115d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
116d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  Block.GlobalUniqueCount = 0;
1175936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
1184e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (C.getLangOpts().ObjCAutoRefCount)
119f85e193739c953358c865005855253af4f68a497John McCall    ARCData = new ARCEntrypoints();
120f85e193739c953358c865005855253af4f68a497John McCall  RRData = new RREntrypoints();
1212b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
1222b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
1232b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
124e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  delete ObjCRuntime;
1258c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  delete OpenCLRuntime;
1266c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  delete CUDARuntime;
1270628b724ff68105dc88af00a39f859447f22981eTed Kremenek  delete TheTargetCodeGenInfo;
128f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  delete &ABI;
1294376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman  delete TBAA;
130815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
131f85e193739c953358c865005855253af4f68a497John McCall  delete ARCData;
132f85e193739c953358c865005855253af4f68a497John McCall  delete RRData;
133815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
134815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
1350d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnallvoid CodeGenModule::createObjCRuntime() {
1364e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!LangOpts.NeXTRuntime)
137e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateGNUObjCRuntime(*this);
1380d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall  else
139e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateMacObjCRuntime(*this);
1400d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall}
1410d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
1428c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbournevoid CodeGenModule::createOpenCLRuntime() {
1438c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  OpenCLRuntime = new CGOpenCLRuntime(*this);
1448c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne}
1458c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
1466c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbournevoid CodeGenModule::createCUDARuntime() {
1476c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  CUDARuntime = CreateNVCUDARuntime(*this);
1486c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne}
1496c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
150815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
15182227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
1526c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  EmitCXXGlobalInitFunc();
153efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar  EmitCXXGlobalDtorFunc();
154e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  if (ObjCRuntime)
155e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
156208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
1576bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
1586bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
15977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  EmitGlobalAnnotations();
1600269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
161744016dde06fcffd50931e94a98c850f8b12cd87John McCall
162b25938303de0976b9f189363d43033e5788e3d36John McCall  SimplifyPersonality();
163b25938303de0976b9f189363d43033e5788e3d36John McCall
164744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (getCodeGenOpts().EmitDeclMetadata)
165744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitDeclMetadata();
1665ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky
1675ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
1683dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    EmitCoverageFile();
169f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
170f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel  if (DebugInfo)
171f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel    DebugInfo->finalize();
172f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
173f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
174e80d56771736c85fd8365c394a6731923b17e91dDevang Patelvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
175e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  // Make sure that this type is translated.
176e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  Types.UpdateCompletedType(TD);
177e80d56771736c85fd8365c394a6731923b17e91dDevang Patel}
178e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
1793d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
1803d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!TBAA)
1813d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return 0;
1823d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  return TBAA->getTBAAInfo(QTy);
1833d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1843d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1858cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryanyllvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
1868cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany  if (!TBAA)
1878cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany    return 0;
1888cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany  return TBAA->getTBAAInfoForVTablePtr();
1898cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany}
1908cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany
1913d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
1923d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman                                        llvm::MDNode *TBAAInfo) {
1933d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
1943d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
1953d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
1966374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCallbool CodeGenModule::isTargetDarwin() const {
197bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  return getContext().getTargetInfo().getTriple().isOSDarwin();
1986374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall}
1996374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
2000f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruthvoid CodeGenModule::Error(SourceLocation loc, StringRef error) {
2010f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
20232096695c76033a6b0b1747c439f7378a11e8312John McCall  getDiags().Report(Context.getFullLoc(loc), diagID);
20332096695c76033a6b0b1747c439f7378a11e8312John McCall}
20432096695c76033a6b0b1747c439f7378a11e8312John McCall
205488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
2062c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
20790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
20890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
20990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
21090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
211d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
21256b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
2132c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
2140a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
2150a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
2162c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
21758c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
218488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
219c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
22090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
22190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
22290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
22390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
224d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
22556b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
226c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
2270a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
228c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
229c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
230bc8d40d85f3fa1e34569834916f18fecaa635152John McCallllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
231bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
232bc8d40d85f3fa1e34569834916f18fecaa635152John McCall}
233bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
2341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
2350ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson                                        const NamedDecl *D) const {
23604d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
237df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
2387e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2396ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
2407e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
2416ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
242af14603ca61757cf4361b583b45639a04c57e651John McCall  // Set visibility for definitions.
243af14603ca61757cf4361b583b45639a04c57e651John McCall  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
244c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
245c7c9058f4977ef4584d68718e23f34504b150ef4Fariborz Jahanian    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
2467cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
2477cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
248cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// Set the symbol visibility of type information (vtable and RTTI)
249cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// associated with the given type.
250cbfe50224b19119e759802bd0c1463269dffd09eJohn McCallvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
251cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                      const CXXRecordDecl *RD,
252fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson                                      TypeVisibilityKind TVK) const {
2530ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(GV, RD);
254cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
255279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (!CodeGenOpts.HiddenWeakVTables)
256279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    return;
257279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall
2589a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  // We never want to drop the visibility for RTTI names.
2599a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  if (TVK == TVK_ForRTTIName)
2609a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    return;
2619a86a137b0872bad25161fb3408a71d919638757Anders Carlsson
262cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We want to drop the visibility to hidden for weak type symbols.
263cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // This isn't possible if there might be unresolved references
264cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // elsewhere that rely on this symbol being visible.
265cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2667a536907da776bdc47a704e7cafd641e8150e653John McCall  // This should be kept roughly in sync with setThunkVisibility
2677a536907da776bdc47a704e7cafd641e8150e653John McCall  // in CGVTables.cpp.
2687a536907da776bdc47a704e7cafd641e8150e653John McCall
269cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Preconditions.
270f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
271cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
272cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
273cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
274cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Don't override an explicit visibility attribute.
2754421d2b341d041df44013769f23c306308bbab83Douglas Gregor  if (RD->getExplicitVisibility())
276cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
277cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
278cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  switch (RD->getTemplateSpecializationKind()) {
279cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We have to disable the optimization if this is an EI definition
280cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // because there might be EI declarations in other shared objects.
281cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDefinition:
282cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDeclaration:
283cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
284cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2857a536907da776bdc47a704e7cafd641e8150e653John McCall  // Every use of a non-template class's type information has to emit it.
286cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_Undeclared:
287cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
288cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
2897a536907da776bdc47a704e7cafd641e8150e653John McCall  // In theory, implicit instantiations can ignore the possibility of
2907a536907da776bdc47a704e7cafd641e8150e653John McCall  // an explicit instantiation declaration because there necessarily
2917a536907da776bdc47a704e7cafd641e8150e653John McCall  // must be an EI definition somewhere with default visibility.  In
2927a536907da776bdc47a704e7cafd641e8150e653John McCall  // practice, it's possible to have an explicit instantiation for
2937a536907da776bdc47a704e7cafd641e8150e653John McCall  // an arbitrary template class, and linkers aren't necessarily able
2947a536907da776bdc47a704e7cafd641e8150e653John McCall  // to deal with mixed-visibility symbols.
2957a536907da776bdc47a704e7cafd641e8150e653John McCall  case TSK_ExplicitSpecialization:
296cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ImplicitInstantiation:
297279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    if (!CodeGenOpts.HiddenWeakTemplateVTables)
2987a536907da776bdc47a704e7cafd641e8150e653John McCall      return;
299cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
300cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  }
301cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
302cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // If there's a key function, there may be translation units
303cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // that don't have the key function's definition.  But ignore
304cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // this if we're emitting RTTI under -fno-rtti.
3054e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
306cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    if (Context.getKeyFunction(RD))
307cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      return;
308fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  }
309cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
310cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Otherwise, drop the visibility to hidden.
311cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
312b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  GV->setUnnamedAddr(true);
313cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall}
314cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3155f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerStringRef CodeGenModule::getMangledName(GlobalDecl GD) {
316793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
317793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3185f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
319793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (!Str.empty())
320793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
321793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3224c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
323793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    IdentifierInfo *II = ND->getIdentifier();
324793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(II && "Attempt to mangle unnamed decl.");
325793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
326793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Str = II->getName();
327793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
328793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
329793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
330f7ccbad5d9949e7ddd1cbef43d482553b811e026Dylan Noblesmith  SmallString<256> Buffer;
331c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer);
332793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
333c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
334793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
335c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
336793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
337c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleBlock(BD, Out);
338793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else
339c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleName(ND, Out);
340793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
341793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // Allocate space for the mangled name.
342c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  Out.flush();
343793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  size_t Length = Buffer.size();
344793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  char *Name = MangledNamesAllocator.Allocate<char>(Length);
345793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  std::copy(Buffer.begin(), Buffer.end(), Name);
346793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3475f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  Str = StringRef(Name, Length);
348793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
349793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return Str;
350793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
351793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
35214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbournevoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
35314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne                                        const BlockDecl *BD) {
35414110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  MangleContext &MangleCtx = getCXXABI().getMangleContext();
35514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  const Decl *D = GD.getDecl();
356c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer.getBuffer());
35714110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  if (D == 0)
358c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleGlobalBlock(BD, Out);
35914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
360c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
36114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
362c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
36314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else
364c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
3659a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson}
3669a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson
3675f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
368f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return getModule().getNamedValue(Name);
3695f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
3705f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
3716d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
3726d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
3736bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
37449988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3756bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
3766d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
3776d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
3786bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
3796bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
3806bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
38149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
3826bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
3836bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
3846bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3856bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
3866bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
3870774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
38896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
3896bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3906bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
391c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::StructType *CtorStructTy =
3928b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner    llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
3936bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
3946bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
3950b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  SmallVector<llvm::Constant*, 8> Ctors;
3966bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
3970b2397132efe74ee11c1b371dd9033820c54240fChris Lattner    llvm::Constant *S[] = {
3980b2397132efe74ee11c1b371dd9033820c54240fChris Lattner      llvm::ConstantInt::get(Int32Ty, I->second, false),
3990b2397132efe74ee11c1b371dd9033820c54240fChris Lattner      llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
4000b2397132efe74ee11c1b371dd9033820c54240fChris Lattner    };
40108e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
4026bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
4036bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4046bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
40596e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
4061c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    new llvm::GlobalVariable(TheModule, AT, false,
407572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
4087db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(AT, Ctors),
4091c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             GlobalName);
4106d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
4116d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
4126d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
413d46f98573ba104eda102dd3224b2dca69f1c6336John McCallllvm::GlobalValue::LinkageTypes
414d46f98573ba104eda102dd3224b2dca69f1c6336John McCallCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
41590e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
4167c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
417f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_Internal)
418d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::InternalLinkage;
419f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
420f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<DLLExportAttr>())
421d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::DLLExportLinkage;
422f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
423f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<WeakAttr>())
424d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::WeakAnyLinkage;
425f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
426f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C99 mode, 'inline' functions are guaranteed to have a strong
427f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition somewhere else, so we can use available_externally linkage.
428f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_C99Inline)
429fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian    return llvm::Function::AvailableExternallyLinkage;
4305584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
4315584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Note that Apple's kernel linker doesn't support symbol
4325584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // coalescing, so we need to avoid linkonce and weak linkages there.
4335584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Normally, this means we just map to internal, but for explicit
4345584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // instantiations we'll map to external.
4355584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
436f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C++, the compiler has to emit a definition in every translation unit
437f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // that references the function.  We should use linkonce_odr because
438f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // a) if all references in this translation unit are optimized away, we
439f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // don't need to codegen it.  b) if the function persists, it needs to be
440f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // merged with other definitions. c) C++ has the ODR, so we know the
441f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition is dependable.
442f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
4434e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    return !Context.getLangOpts().AppleKext
444142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::LinkOnceODRLinkage
445142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
446f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
447f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // An explicit instantiation of a template has weak linkage, since
448f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // explicit instantiations can occur in multiple translation units
449f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // and must all be equivalent. However, we are not allowed to
450f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // throw away these explicit instantiations.
451f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_ExplicitTemplateInstantiation)
4524e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    return !Context.getLangOpts().AppleKext
453142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::WeakODRLinkage
4545584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall             : llvm::Function::ExternalLinkage;
455f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
456f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // Otherwise, we have strong external linkage.
457f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  assert(Linkage == GVA_StrongExternal);
458f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  return llvm::Function::ExternalLinkage;
459d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
460d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
461d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
462d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// SetFunctionDefinitionAttributes - Set attributes for a global.
463d46f98573ba104eda102dd3224b2dca69f1c6336John McCall///
464d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// FIXME: This is currently only done for aliases and functions, but not for
465d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// variables (these details are set in EmitGlobalVarDefinition for variables).
466d46f98573ba104eda102dd3224b2dca69f1c6336John McCallvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
467d46f98573ba104eda102dd3224b2dca69f1c6336John McCall                                                    llvm::GlobalValue *GV) {
4687c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
469d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
470d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
4717dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
4721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              const CGFunctionInfo &Info,
4737dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
474ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  unsigned CallingConv;
475761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
476ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList, CallingConv);
477761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
478ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar                                          AttributeList.size()));
479ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
480f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
481f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
482d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// Determines whether the language options require us to model
483d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// unwind exceptions.  We treat -fexceptions as mandating this
484d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// except under the fragile ObjC ABI with only ObjC exceptions
485d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enabled.  This means, for example, that C with -fexceptions
486d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enables this.
4874e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikiestatic bool hasUnwindExceptions(const LangOptions &LangOpts) {
488d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If exceptions are completely disabled, obviously this is false.
4894e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!LangOpts.Exceptions) return false;
490d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
491d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If C++ exceptions are enabled, this is true.
4924e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CXXExceptions) return true;
493d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
494d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If ObjC exceptions are enabled, this depends on the ABI.
4954e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.ObjCExceptions) {
4964e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (!LangOpts.ObjCNonFragileABI) return false;
497d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  }
498d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
499d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  return true;
500d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall}
501d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
5027c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
5037c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
504abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola  if (CodeGenOpts.UnwindTables)
505abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola    F->setHasUWTable();
506abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola
5074e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!hasUnwindExceptions(LangOpts))
5081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->addFnAttr(llvm::Attribute::NoUnwind);
509af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
5102873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<NakedAttr>()) {
5112873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    // Naked implies noinline: we should not be inlining such functions.
512dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar    F->addFnAttr(llvm::Attribute::Naked);
5132873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    F->addFnAttr(llvm::Attribute::NoInline);
5142873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  }
515dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar
5161feade8e520be483293dbf55eb57a51720899589Mike Stump  if (D->hasAttr<NoInlineAttr>())
51781ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson    F->addFnAttr(llvm::Attribute::NoInline);
518f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
5192873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  // (noinline wins over always_inline, and we can't specify both in IR)
5202873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<AlwaysInlineAttr>() &&
5212873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman      !F->hasFnAttr(llvm::Attribute::NoInline))
5222873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    F->addFnAttr(llvm::Attribute::AlwaysInline);
5232873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman
524c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
525c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    F->setUnnamedAddr(true);
526c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
5274e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
528fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtect);
5294e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
530fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson    F->addFnAttr(llvm::Attribute::StackProtectReq);
531fd015353a3c4f528216276f25df5b4d464d7a0cdAnders Carlsson
5324e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.AddressSanitizer) {
53389651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko    // When AddressSanitizer is enabled, set AddressSafety attribute
53489651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko    // unless __attribute__((no_address_safety_analysis)) is used.
53589651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko    if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
53689651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko      F->addFnAttr(llvm::Attribute::AddressSafety);
53789651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko  }
53889651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko
539cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
540cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  if (alignment)
541cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    F->setAlignment(alignment);
542cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt
543fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  // C++ ABI requires 2-byte alignment for member functions.
544bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
545bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump    F->setAlignment(2);
546f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
547f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
5481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::SetCommonAttributes(const Decl *D,
5497c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
550934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
551934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson    setGlobalVisibility(GV, ND);
5521fb0caaa7bef765b85972274e3b434af2572c141John McCall  else
5531fb0caaa7bef765b85972274e3b434af2572c141John McCall    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
5547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
55540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<UsedAttr>())
5567c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
5577c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
55840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
5597c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
56082d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov
56182d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
5627c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
5637c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5640e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
5650e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
5660e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
5670e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
5680e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
5697c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5707c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
5717c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
5720e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
573f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
574f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
575b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
576c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          llvm::Function *F,
577c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          bool IsIncompleteFunction) {
5780ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  if (unsigned IID = F->getIntrinsicID()) {
5790ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // If this is an intrinsic function, set the function's attributes
5800ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // to the intrinsic's attributes.
5810ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
5820ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    return;
5830ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  }
5840ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
585b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
586b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
587c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  if (!IsIncompleteFunction)
588de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
5891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5907c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
5917c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
5921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
59340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (FD->hasAttr<DLLImportAttr>()) {
5947c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
5951eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (FD->hasAttr<WeakAttr>() ||
5960a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             FD->isWeakImported()) {
5977c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
5981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // separate linkage types for this.
5997c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
6007c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
6011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->setLinkage(llvm::Function::ExternalLinkage);
602af14603ca61757cf4361b583b45639a04c57e651John McCall
603af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
604af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
605af14603ca61757cf4361b583b45639a04c57e651John McCall      F->setVisibility(GetLLVMVisibility(LV.visibility()));
606af14603ca61757cf4361b583b45639a04c57e651John McCall    }
6077c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
6087c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
60940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
6107c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
611219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
612219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
6130269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
6141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!GV->isDeclaration() &&
6150269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
61635f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
6170269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
6180269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6190269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
6200269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
621ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  if (LLVMUsed.empty())
6220269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
6230269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
62435f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
6250b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  SmallVector<llvm::Constant*, 8> UsedArray;
62635f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
62735f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
6281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    UsedArray[i] =
6291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
6300b2397132efe74ee11c1b371dd9033820c54240fChris Lattner                                    Int8PtrTy);
63135f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
6321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
633c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  if (UsedArray.empty())
634c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    return;
6350b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
6361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
6381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), ATy, false,
6390269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
6407db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(ATy, UsedArray),
6411c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             "llvm.used");
6420269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6430269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
6440269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
6450269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
6460269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
64767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
64867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
649dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  // for a static function, iterate until no changes are made.
650bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
651046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
652046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    if (!DeferredVTables.empty()) {
653046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      const CXXRecordDecl *RD = DeferredVTables.back();
654046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      DeferredVTables.pop_back();
655046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson      getVTables().GenerateClassData(getVTableLinkage(RD), RD);
656bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola      continue;
657bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    }
658bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
6592a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
66067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
66167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
662c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // Check to see if we've already emitted this.  This is necessary
663c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // for a couple of reasons: first, decls can end up in the
664c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // deferred-decls queue multiple times, and second, decls can end
665c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // up with definitions in unusual ways (e.g. by an extern inline
666c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // function acquiring a strong function redefinition).  Just
667c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // ignore these cases.
668c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    //
669c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // TODO: That said, looking this up multiple times is very wasteful.
6705f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = getMangledName(D);
671f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
67267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
6731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
67467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
67567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
6761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
677c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
678c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // purposes an alias counts as a definition.
679c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (isa<llvm::GlobalAlias>(CGRef))
680c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      continue;
681c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
68267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
68367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
68467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
6855f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
6865f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
68777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::EmitGlobalAnnotations() {
68877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (Annotations.empty())
68977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return;
69077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
69177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Create a new global variable for the ConstantStruct in the Module.
69277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
69377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations[0]->getType(), Annotations.size()), Annotations);
69477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
69577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
69677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    "llvm.global.annotations");
69777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
69877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
69977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
70077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
70177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
70277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (i != AnnotationStrings.end())
70377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return i->second;
70477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
70577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Not found yet, create a new global.
70694010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
70777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
70877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
70977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
71077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setUnnamedAddr(true);
71177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  AnnotationStrings[Str] = gv;
71277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return gv;
71377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
71477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
71577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
71677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
71777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
71877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (PLoc.isValid())
71977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return EmitAnnotationString(PLoc.getFilename());
72077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return EmitAnnotationString(SM.getBufferName(Loc));
72177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
72277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
72377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
72477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
72577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(L);
72677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
72777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    SM.getExpansionLineNumber(L);
72877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return llvm::ConstantInt::get(Int32Ty, LineNo);
72977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
73077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
7311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
7328bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
73377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                                SourceLocation L) {
73477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the globals for file name, annotation, and the line number.
73577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
73677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *UnitGV = EmitAnnotationUnit(L),
73777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *LineNoCst = EmitAnnotationLineNo(L);
7388bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
73957d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
7408bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
74177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
74277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
74377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
74477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    LineNoCst
7458bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
746c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  return llvm::ConstantStruct::getAnon(Fields);
7478bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
7488bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
74977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
75077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         llvm::GlobalValue *GV) {
75177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
75277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the struct elements for these annotations.
75377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  for (specific_attr_iterator<AnnotateAttr>
75477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ai = D->specific_attr_begin<AnnotateAttr>(),
75577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
75677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
75777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
75877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
759a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidisbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
76090e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  // Never defer when EmitAllDecls is specified.
7614e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.EmitAllDecls)
762a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    return false;
7630b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor
7644ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis  return !getContext().DeclMustBeEmitted(Global);
76573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
76673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
7676a836706c40a31c716952b74785102c90fd6afa7Rafael Espindolallvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
7686a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const AliasAttr *AA = VD->getAttr<AliasAttr>();
7696a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  assert(AA && "No alias?");
7706a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7712acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
7726a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7736a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // See if there is already something with the target's name in the module.
774f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
7756a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7766a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  llvm::Constant *Aliasee;
7776a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (isa<llvm::FunctionType>(DeclTy))
7781faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
7791faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
7806a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  else
781f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
7826a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                    llvm::PointerType::getUnqual(DeclTy), 0);
7836a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (!Entry) {
7846a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
7856a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    F->setLinkage(llvm::Function::ExternalWeakLinkage);
7866a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    WeakRefReferences.insert(F);
7876a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  }
7886a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
7896a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  return Aliasee;
7906a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola}
7916a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
792b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
7934a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
7941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7956a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // Weak references don't produce any output by themselves.
7966a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (Global->hasAttr<WeakRefAttr>())
7976a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    return;
7986a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
799bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
800bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
80140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Global->hasAttr<AliasAttr>())
802f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return EmitAliasDefinition(GD);
803219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
804d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  // If this is CUDA, be selective about which declarations we emit.
8054e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CUDA) {
806d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    if (CodeGenOpts.CUDAIsDevice) {
807d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDADeviceAttr>() &&
808d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAGlobalAttr>() &&
809d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAConstantAttr>() &&
810d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDASharedAttr>())
811d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
812d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    } else {
813d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDAHostAttr>() && (
814d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDADeviceAttr>() ||
815d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDAConstantAttr>() ||
816d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDASharedAttr>()))
817d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
818d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    }
819d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  }
820d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne
82167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
8225e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
82373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
824dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    if (!FD->doesThisDeclarationHaveABody()) {
825dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
826dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        return;
827dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
828dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      const FunctionDecl *InlineDefinition = 0;
829dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      FD->getBody(InlineDefinition);
830dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
8315f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      StringRef MangledName = getMangledName(GD);
8327e42392eb2ea29ddeb6d125417fb4c17d847b5e0Benjamin Kramer      DeferredDecls.erase(MangledName);
833dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      EmitGlobalDefinition(InlineDefinition);
83473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
835dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    }
8360269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
8370269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
838bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
839bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
840a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
84173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
8424c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
8434c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
84467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
84567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
8464357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (!MayDeferGeneration(Global)) {
8474357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Emit the definition if it can't be deferred.
8484357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    EmitGlobalDefinition(GD);
849bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
850bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
851bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
852bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // If we're deferring emission of a C++ variable with an
853bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // initializer, remember the order in which it appeared in the file.
8544e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
855bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      cast<VarDecl>(Global)->hasInit()) {
856bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
857bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    CXXGlobalInits.push_back(0);
858bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  }
8594357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
8604357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // If the value has already been used, add it directly to the
8614357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // DeferredDeclsToEmit list.
8625f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
8634357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (GetGlobalValue(MangledName))
8644357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDeclsToEmit.push_back(GD);
8654357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  else {
8664357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Otherwise, remember that we saw a deferred decl with this name.  The
8674357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // first use of the mangled name will cause it to move into
8684357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // DeferredDeclsToEmit.
8694357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDecls[MangledName] = GD;
8704357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  }
8714c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
8724c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
873a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolanamespace {
874a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  struct FunctionIsDirectlyRecursive :
875a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
876a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    const StringRef Name;
877bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    const Builtin::Context &BI;
878a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool Result;
879bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
880bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      Name(N), BI(C), Result(false) {
881a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
882a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
883a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
884a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool TraverseCallExpr(CallExpr *E) {
885bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      const FunctionDecl *FD = E->getDirectCallee();
886bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!FD)
887a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
888bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
889bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (Attr && Name == Attr->getLabel()) {
890bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        Result = true;
891bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        return false;
892bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      }
893bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      unsigned BuiltinID = FD->getBuiltinID();
894bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!BuiltinID)
895a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
896f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      StringRef BuiltinName = BI.GetName(BuiltinID);
897f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      if (BuiltinName.startswith("__builtin_") &&
898f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
899a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        Result = true;
900a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return false;
901a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      }
902a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      return true;
903a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
904a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  };
905a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
906a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
907bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// isTriviallyRecursive - Check if this function calls another
908bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// decl that, because of the asm attribute or the other decl being a builtin,
909bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// ends up pointing to itself.
910a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
911bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael EspindolaCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
912bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  StringRef Name;
913bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
91422afaccd9ab77d46106e94c47907d955a014ae3fNick Lewycky    // asm labels are a special kind of mangling we have to support.
915bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
916bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    if (!Attr)
917bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      return false;
918bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = Attr->getLabel();
919bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  } else {
920bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = FD->getName();
921bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  }
922a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
923bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
924bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
925a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  return Walker.Result;
926a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
927a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
928a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
929a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael EspindolaCodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
930a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
931a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
932cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola  if (CodeGenOpts.OptimizationLevel == 0 &&
933cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola      !F->hasAttr<AlwaysInlineAttr>())
934a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return false;
935a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // PR9614. Avoid cases where the source code is lying to us. An available
936a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // externally function should have an equivalent function somewhere else,
937a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // but a function that calls itself is clearly not equivalent to the real
938a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // implementation.
939a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // This happens in glibc's btowc and in some configure checks.
940bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  return !isTriviallyRecursive(F);
941a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
942a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
943b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
9444a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
9451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
946cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
9478e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 Context.getSourceManager(),
9488e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 "Generating code for declaration");
9498e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson
95044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
95144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // At -O0, don't generate IR for functions with available_externally
95244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // linkage.
953a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    if (!shouldEmitFunction(Function))
95444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      return;
95544eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
95644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
9577dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // Make sure to emit the definition(s) before we emit the thunks.
9587dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // This is necessary for the generation of certain thunks.
9597dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
9607dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXConstructor(CD, GD.getCtorType());
9617dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
9627dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXDestructor(DD, GD.getDtorType());
9637dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else
9647dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitGlobalFunctionDefinition(GD);
9657dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman
96644eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (Method->isVirtual())
96744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getVTables().EmitThunks(GD);
9687270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
9697dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      return;
97044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    }
971b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
972b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalFunctionDefinition(GD);
97344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  }
974b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
975b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
976b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalVarDefinition(VD);
9774357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
978b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
979bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
980bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
98174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
98274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
98374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
98474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
98574391b48b4791cded373683a3baf67314f358d50Chris Lattner///
98674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
98774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
988f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
9895f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
9902acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                       llvm::Type *Ty,
991f85e193739c953358c865005855253af4f68a497John McCall                                       GlobalDecl D, bool ForVTable,
992f85e193739c953358c865005855253af4f68a497John McCall                                       llvm::Attributes ExtraAttrs) {
9930558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
994f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
9950558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
9966a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
9976a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
9986a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (FD && !FD->hasAttr<WeakAttr>())
9997270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
10006a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10016a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
10026a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
10036a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10040558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
10050558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
10061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10070558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
10089cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
10090558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
10101eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1011654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // This function doesn't have a complete type (for example, the return
1012654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // type is an incomplete struct). Use a fake type instead, and make
1013654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // sure not to try to set attributes.
1014654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  bool IsIncompleteFunction = false;
1015784f21121a6c9418ebd86baa6814e36e1176c410John McCall
10162acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *FTy;
1017784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (isa<llvm::FunctionType>(Ty)) {
1018784f21121a6c9418ebd86baa6814e36e1176c410John McCall    FTy = cast<llvm::FunctionType>(Ty);
1019784f21121a6c9418ebd86baa6814e36e1176c410John McCall  } else {
10200774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    FTy = llvm::FunctionType::get(VoidTy, false);
1021654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    IsIncompleteFunction = true;
1022654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
1023bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
1024784f21121a6c9418ebd86baa6814e36e1176c410John McCall  llvm::Function *F = llvm::Function::Create(FTy,
1025654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                             llvm::Function::ExternalLinkage,
1026f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                             MangledName, &getModule());
1027f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  assert(F->getName() == MangledName && "name was uniqued!");
1028654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (D.getDecl())
1029b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetFunctionAttributes(D, F, IsIncompleteFunction);
1030f85e193739c953358c865005855253af4f68a497John McCall  if (ExtraAttrs != llvm::Attribute::None)
1031f85e193739c953358c865005855253af4f68a497John McCall    F->addFnAttr(ExtraAttrs);
1032654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
103367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
103467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
103567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1036f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
103767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
103867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
103967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
104067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
104167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
1042bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
1043bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // Otherwise, there are cases we have to worry about where we're
1044bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // using a declaration for which we must emit a definition but where
1045bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // we might not find a top-level definition:
1046bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - member functions defined inline in their classes
1047bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - friend functions defined inline in some class
1048bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - special member functions with implicit definitions
1049bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // If we ever change our AST traversal to walk into class methods,
1050bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // this will be unnecessary.
10511faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  //
10521faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // We also don't emit a definition for a function if it's going to be an entry
10531faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // in a vtable, unless it's already marked as used.
10544e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1055bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    // Look for a declaration that's lexically in a record.
1056bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1057bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    do {
1058bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
10591faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        if (FD->isImplicit() && !ForVTable) {
1060bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1061a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1062bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
106310620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt        } else if (FD->doesThisDeclarationHaveABody()) {
1064a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1065bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
1066bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        }
10677b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      }
1068ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor      FD = FD->getPreviousDecl();
1069bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    } while (FD);
107067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
10711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1072784f21121a6c9418ebd86baa6814e36e1176c410John McCall  // Make sure the result is of the requested type.
1073784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (!IsIncompleteFunction) {
1074784f21121a6c9418ebd86baa6814e36e1176c410John McCall    assert(F->getType()->getElementType() == Ty);
1075784f21121a6c9418ebd86baa6814e36e1176c410John McCall    return F;
1076784f21121a6c9418ebd86baa6814e36e1176c410John McCall  }
1077784f21121a6c9418ebd86baa6814e36e1176c410John McCall
10789cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1079784f21121a6c9418ebd86baa6814e36e1176c410John McCall  return llvm::ConstantExpr::getBitCast(F, PTy);
10800558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
10810558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
108274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
108374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
108474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
1085b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
10862acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                 llvm::Type *Ty,
10871faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 bool ForVTable) {
108874391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
108974391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
10904a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1091bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
10925f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
10931faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
109474391b48b4791cded373683a3baf67314f358d50Chris Lattner}
109577ba708819285931932ecd33691a672bb59d221aEli Friedman
109674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
109774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
109874391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
10992acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
11005f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name,
1101f85e193739c953358c865005855253af4f68a497John McCall                                     llvm::Attributes ExtraAttrs) {
1102f85e193739c953358c865005855253af4f68a497John McCall  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1103f85e193739c953358c865005855253af4f68a497John McCall                                 ExtraAttrs);
110474391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1105bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1106a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// isTypeConstant - Determine whether an object of this type can be emitted
1107a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// as a constant.
1108a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith///
1109a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// If ExcludeCtor is true, the duration when the object's constructor runs
1110a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// will not be considered. The caller will need to verify that the object is
1111a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// not written to during its construction.
1112a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smithbool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1113a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
111420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
1115a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
11164e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Context.getLangOpts().CPlusPlus) {
1117a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    if (const CXXRecordDecl *Record
1118a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith          = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1119a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith      return ExcludeCtor && !Record->hasMutableFields() &&
1120a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith             Record->hasTrivialDestructor();
112120e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  }
1122a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
112320e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  return true;
112420e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman}
112520e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman
112674391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
112774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
112874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
112974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
113074391b48b4791cded373683a3baf67314f358d50Chris Lattner///
113174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
113274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
1133f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
11345f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
11352acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                     llvm::PointerType *Ty,
1136c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     const VarDecl *D,
1137c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     bool UnnamedAddr) {
11383c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
1139f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
114099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
11416a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    if (WeakRefReferences.count(Entry)) {
11426a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (D && !D->hasAttr<WeakAttr>())
11437270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
11446a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
11456a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      WeakRefReferences.erase(Entry);
11466a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
11476a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1148c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola    if (UnnamedAddr)
1149c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      Entry->setUnnamedAddr(true);
1150c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola
115174391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
1152570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
11531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
115499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
11553c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, Ty);
115699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
11571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
115867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
115967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
116067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1161f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
116267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
116367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
116467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
116567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
116667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
116767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
11681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
11691eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
11701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
117199b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
1172f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                             0, MangledName, 0,
117356ebe5082da7411fb37479e230b52735f77cff35Eli Friedman                             false, Ty->getAddressSpace());
117449988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
117599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
117674391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
1177f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // FIXME: This code is overly simple and should be merged with other global
1178f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // handling.
1179a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    GV->setConstant(isTypeConstant(D->getType(), false));
118049988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
1181110e8e56af30363072c140285961592b0107f789John McCall    // Set linkage and visibility in case we never see a definition.
1182af14603ca61757cf4361b583b45639a04c57e651John McCall    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1183af14603ca61757cf4361b583b45639a04c57e651John McCall    if (LV.linkage() != ExternalLinkage) {
118415e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      // Don't set internal linkage on declarations.
1185110e8e56af30363072c140285961592b0107f789John McCall    } else {
1186110e8e56af30363072c140285961592b0107f789John McCall      if (D->hasAttr<DLLImportAttr>())
1187110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
11880a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1189110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1190110e8e56af30363072c140285961592b0107f789John McCall
1191af14603ca61757cf4361b583b45639a04c57e651John McCall      // Set visibility on a declaration only if it's explicit.
1192af14603ca61757cf4361b583b45639a04c57e651John McCall      if (LV.visibilityExplicit())
1193af14603ca61757cf4361b583b45639a04c57e651John McCall        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1194110e8e56af30363072c140285961592b0107f789John McCall    }
119556ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
119656ebe5082da7411fb37479e230b52735f77cff35Eli Friedman    GV->setThreadLocal(D->isThreadSpecified());
119774391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
11981eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1199f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GV;
120074391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1201eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
1202eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
12033bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlssonllvm::GlobalVariable *
12045f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
12052acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                      llvm::Type *Ty,
12063bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
12073bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
12083bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *OldGV = 0;
12093bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12103bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12113bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (GV) {
12123bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Check if the variable has the right type.
12133bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (GV->getType()->getElementType() == Ty)
12143bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      return GV;
12153bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12163bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Because C++ name mangling, the only way we can end up with an already
12173bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
121896eaf2992b5955d1470fc9cce7a96e7e1e3b4ea7Anders Carlsson      assert(GV->isDeclaration() && "Declaration has wrong type!");
12193bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV = GV;
12203bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
12213bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12223bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a new variable.
12233bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
12243bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                Linkage, 0, Name);
12253bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12263bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (OldGV) {
12273bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Replace occurrences of the old variable if needed.
12283bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    GV->takeName(OldGV);
12293bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12303bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (!OldGV->use_empty()) {
12313bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::Constant *NewPtrForOldDecl =
12323bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
12333bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
12343bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
12353bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12363bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV->eraseFromParent();
12373bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
12383bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
12393bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  return GV;
12403bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson}
12413bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
124274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
124374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
12440ff258b933fe385425bf2a85429bf46376d338f1Eric Christopher/// then it will be created with the specified type instead of whatever the
124574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
124674391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
12472acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                  llvm::Type *Ty) {
124874391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
124974391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
125074391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
125174391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
12521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12532acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::PointerType *PTy =
1254207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1255f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
12565f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(D);
1257f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
125874391b48b4791cded373683a3baf67314f358d50Chris Lattner}
12593f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
126074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
126174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
126274391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
12632acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
12645f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name) {
12651de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1266c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                               true);
1267bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1268bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
126903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
127003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
127103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
12727520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
12737520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
12747520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
12757520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
12765f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef MangledName = getMangledName(D);
1277f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    if (!GetGlobalValue(MangledName)) {
1278555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      DeferredDecls[MangledName] = D;
127903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
12807520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
12817520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
12827520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
12837520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
128403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
128503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
128603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
12876fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregorvoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
12886fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor  if (DefinitionRequired)
12896fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor    getVTables().GenerateClassData(getVTableLinkage(Class), Class);
12906fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor}
12916fb745bdf1ff1e32caf07e42093a7920726892c1Douglas Gregor
12924b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregorllvm::GlobalVariable::LinkageTypes
1293046c294a43024874ff35656c6e785b64e72f1f36Anders CarlssonCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1294cb5d2d0647fdab2e36c85b417e03bf18916ce10cEli Friedman  if (RD->getLinkage() != ExternalLinkage)
1295dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    return llvm::GlobalVariable::InternalLinkage;
1296dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
1297dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  if (const CXXMethodDecl *KeyFunction
1298dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor                                    = RD->getASTContext().getKeyFunction(RD)) {
1299dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // If this class has a key function, use that to determine the linkage of
1300dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // the vtable.
13014b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    const FunctionDecl *Def = 0;
130206a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis    if (KeyFunction->hasBody(Def))
13034b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      KeyFunction = cast<CXXMethodDecl>(Def);
1304dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
13054b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    switch (KeyFunction->getTemplateSpecializationKind()) {
13064b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_Undeclared:
13074b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitSpecialization:
13086d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // When compiling with optimizations turned on, we emit all vtables,
13096d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // even if the key function is not defined in the current translation
13106d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        // unit. If this is the case, use available_externally linkage.
13116d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson        if (!Def && CodeGenOpts.OptimizationLevel)
13126d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson          return llvm::GlobalVariable::AvailableExternallyLinkage;
13136d7f8473cd6e967b3676948894ce72472102f9cbAnders Carlsson
13144b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        if (KeyFunction->isInlined())
13154e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie          return !Context.getLangOpts().AppleKext ?
1316142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::GlobalVariable::LinkOnceODRLinkage :
1317142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                   llvm::Function::InternalLinkage;
13184b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13194b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        return llvm::GlobalVariable::ExternalLinkage;
13204b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13214b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ImplicitInstantiation:
13224e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        return !Context.getLangOpts().AppleKext ?
1323142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1324142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1325f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
13264b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDefinition:
13274e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        return !Context.getLangOpts().AppleKext ?
1328142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::WeakODRLinkage :
1329142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
1330f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson
13314b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor      case TSK_ExplicitInstantiationDeclaration:
13324b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // FIXME: Use available_externally linkage. However, this currently
13334b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        // breaks LLVM's build due to undefined symbols.
13344b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
13354e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        return !Context.getLangOpts().AppleKext ?
1336142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::GlobalVariable::LinkOnceODRLinkage :
1337142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian                 llvm::Function::InternalLinkage;
13384b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor    }
1339dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  }
1340dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor
13414e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Context.getLangOpts().AppleKext)
134253bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::Function::InternalLinkage;
134353bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian
1344dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  switch (RD->getTemplateSpecializationKind()) {
1345dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_Undeclared:
1346dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ExplicitSpecialization:
1347dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor  case TSK_ImplicitInstantiation:
1348dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // FIXME: Use available_externally linkage. However, this currently
1349dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    // breaks LLVM's build due to undefined symbols.
1350dffb8010a130733f1b55acf0af01deb0a2e083d3Douglas Gregor    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1351142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDeclaration:
135253bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian    return llvm::GlobalVariable::LinkOnceODRLinkage;
1353142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian
1354142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian  case TSK_ExplicitInstantiationDefinition:
135553bad4e98ed5e765df4231099bf1c737582908bfFariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
13564b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor  }
13573026348bd4c13a0f83b59839f64065e0fcbea253David Blaikie
13583026348bd4c13a0f83b59839f64065e0fcbea253David Blaikie  llvm_unreachable("Invalid TemplateSpecializationKind!");
13594b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor}
13604b0f21c0f8bed0e2a7dc62d73be64e7e277d6c9aDouglas Gregor
13612acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
136206f486ecd05bd6788da97c39164c1903a084c26dKen Dyck    return Context.toCharUnitsFromBits(
136306f486ecd05bd6788da97c39164c1903a084c26dKen Dyck      TheTargetData.getTypeStoreSizeInBits(Ty));
1364687cc4a850b59116efee061018f0d8df50728b82Ken Dyck}
1365687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
136619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redlllvm::Constant *
136719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian RedlCodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
136819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                       const Expr *rawInit) {
136919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
137019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (const ExprWithCleanups *withCleanups =
137119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl          dyn_cast<ExprWithCleanups>(rawInit)) {
137219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    cleanups = withCleanups->getObjects();
137319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    rawInit = withCleanups->getSubExpr();
137419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
137519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
137619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
137719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!init || !init->initializesStdInitializerList() ||
137819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl      init->getNumInits() == 0)
137919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
138019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
138119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ASTContext &ctx = getContext();
138219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  unsigned numInits = init->getNumInits();
1383062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // FIXME: This check is here because we would otherwise silently miscompile
1384062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // nested global std::initializer_lists. Better would be to have a real
1385062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // implementation.
1386062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  for (unsigned i = 0; i < numInits; ++i) {
1387062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1388062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    if (inner && inner->initializesStdInitializerList()) {
1389062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl      ErrorUnsupported(inner, "nested global std::initializer_list");
1390062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl      return 0;
1391062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    }
1392062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  }
1393062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl
1394062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // Synthesize a fake VarDecl for the array and initialize that.
139519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType elementType = init->getInit(0)->getType();
139619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
139719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
139819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                ArrayType::Normal, 0);
139919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
140019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
140119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
140219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                              arrayType, D->getLocation());
140319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
140419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                          D->getDeclContext()),
140519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          D->getLocStart(), D->getLocation(),
140619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          name, arrayType, sourceInfo,
140719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          SC_Static, SC_Static);
140819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
140919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Now clone the InitListExpr to initialize the array instead.
141019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Incredible hack: we want to use the existing InitListExpr here, so we need
141119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // to tell it that it no longer initializes a std::initializer_list.
141219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
141319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                    const_cast<InitListExpr*>(init)->getInits(),
141419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                   init->getNumInits(),
141519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                   init->getRBraceLoc());
141619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  arrayInit->setType(arrayType);
141719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
141819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!cleanups.empty())
141919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
142019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
142119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  backingArray->setInit(arrayInit);
142219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
142319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Emit the definition of the array.
142419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  EmitGlobalVarDefinition(backingArray);
142519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
142619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Inspect the initializer list to validate it and determine its type.
142719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // FIXME: doing this every time is probably inefficient; caching would be nice
142819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
142919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  RecordDecl::field_iterator field = record->field_begin();
143019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (field == record->field_end()) {
143119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
143219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
143319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
143419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType elementPtr = ctx.getPointerType(elementType.withConst());
143519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Start pointer.
143619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!ctx.hasSameType(field->getType(), elementPtr)) {
143719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
143819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
143919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
144019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ++field;
144119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (field == record->field_end()) {
144219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
144319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
144419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
144519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  bool isStartEnd = false;
144619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (ctx.hasSameType(field->getType(), elementPtr)) {
144719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // End pointer.
144819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    isStartEnd = true;
144919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
145019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
145119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
145219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
145319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
145419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Now build an APValue representing the std::initializer_list.
145519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue initListValue(APValue::UninitStruct(), 0, 2);
145619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue &startField = initListValue.getStructField(0);
145719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue::LValuePathEntry startOffsetPathEntry;
145819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  startOffsetPathEntry.ArrayIndex = 0;
145919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  startField = APValue(APValue::LValueBase(backingArray),
146019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       CharUnits::fromQuantity(0),
146119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       llvm::makeArrayRef(startOffsetPathEntry),
146219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       /*IsOnePastTheEnd=*/false, 0);
146319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
146419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (isStartEnd) {
146519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue &endField = initListValue.getStructField(1);
146619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue::LValuePathEntry endOffsetPathEntry;
146719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    endOffsetPathEntry.ArrayIndex = numInits;
146819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    endField = APValue(APValue::LValueBase(backingArray),
146919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       ctx.getTypeSizeInChars(elementType) * numInits,
147019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       llvm::makeArrayRef(endOffsetPathEntry),
147119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       /*IsOnePastTheEnd=*/true, 0);
147219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  } else {
147319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue &sizeField = initListValue.getStructField(1);
147419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    sizeField = APValue(llvm::APSInt(numElements));
147519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
147619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
147719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Emit the constant for the initializer_list.
1478a3ca41f0c2bd1c4a752df88b283332f3b757d21eRichard Smith  llvm::Constant *llvmInit =
1479a3ca41f0c2bd1c4a752df88b283332f3b757d21eRichard Smith      EmitConstantValueForMemory(initListValue, D->getType());
148019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  assert(llvmInit && "failed to initialize as constant");
148119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  return llvmInit;
148219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl}
148319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
1484bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
14858f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
148677ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
14877ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
14887ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  bool NeedsGlobalCtor = false;
14897ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
14901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14912d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const VarDecl *InitDecl;
14922d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
149319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
14943bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson  if (!InitExpr) {
1495cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
149603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
149703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
149803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
149903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
150003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
150103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
150203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
150303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
150403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1505b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    Init = EmitNullConstant(D->getType());
150677ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
150719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // If this is a std::initializer_list, emit the special initializer.
150819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
150919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // An empty init list will perform zero-initialization, which happens
151019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // to be exactly what we want.
151119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // FIXME: It does so in a global constructor, which is *not* what we
151219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // want.
151319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
151419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    if (!Init)
151519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl      Init = EmitConstantInit(*InitDecl);
15166e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
15173bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson      QualType T = InitExpr->getType();
1518c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor      if (D->getType()->isReferenceType())
1519c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor        T = D->getType();
15202d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith
15214e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus) {
152289ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = EmitNullConstant(T);
15237ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith        NeedsGlobalCtor = true;
152489ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      } else {
152589ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        ErrorUnsupported(D, "static initializer");
152689ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
152789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      }
1528bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    } else {
1529bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // We don't need an initializer, so remove the entry for the delayed
15307ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith      // initializer position (just in case this entry was delayed) if we
15317ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith      // also don't need to register a destructor.
15324e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1533bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall        DelayedCXXInitPosition.erase(D);
15346e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
15358f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
15368e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
15372acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type* InitType = Init->getType();
1538570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
15391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1540570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
1541570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
15429d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
15439d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           // all zero index gep.
15449d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1545570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
1546570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
15471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1548570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
1549570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
15501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1551570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
1552570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
1553570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
1554570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
1555570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
1556570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
1557570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
1558570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
1559570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
1560570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
1561570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
1562207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      GV->getType()->getAddressSpace() !=
1563207f4d8543529221932af82836016a2ef066c917Peter Collingbourne        getContext().getTargetAddressSpace(ASTTy)) {
15641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1565f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Move the old entry aside so that we'll create a new one.
15665f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    Entry->setName(StringRef());
1567232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
1568570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
1569570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
15700558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
157177ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
15721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *NewPtrForOldDecl =
15733c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1574570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
157577ba708819285931932ecd33691a672bb59d221aEli Friedman
157677ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
1577570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
157877ba708819285931932ecd33691a672bb59d221aEli Friedman  }
157977ba708819285931932ecd33691a672bb59d221aEli Friedman
158077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
158177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, GV);
15828bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
158388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
1584e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1585e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // If it is safe to mark the global 'constant', do so now.
1586a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1587a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith                  isTypeConstant(D->getType(), true));
15881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15898b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1590a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
159188a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
1592354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage =
1593354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GetLLVMLinkageVarDefinition(D, GV);
1594354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  GV->setLinkage(Linkage);
1595354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1596354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    // common vars aren't constant even if declared const.
1597354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GV->setConstant(false);
1598354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1599354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  SetCommonAttributes(D, GV);
1600354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
16013030eb82593097502469a8b3fc26112c79c75605John McCall  // Emit the initializer function if necessary.
16027ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  if (NeedsGlobalCtor || NeedsGlobalDtor)
16037ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
16043030eb82593097502469a8b3fc26112c79c75605John McCall
1605354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // Emit global variable debug information.
160673fb35003aad027492e661a3749e921b5d1ecaf9Eric Christopher  if (CGDebugInfo *DI = getModuleDebugInfo())
1607354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    DI->EmitGlobalVariable(GV, D);
1608354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian}
1609354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1610354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianllvm::GlobalValue::LinkageTypes
1611354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz JahanianCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1612354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                           llvm::GlobalVariable *GV) {
161390e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1614a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  if (Linkage == GVA_Internal)
1615354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::InternalLinkage;
161640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLImportAttr>())
1617354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLImportLinkage;
161840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLExportAttr>())
1619354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLExportLinkage;
1620e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1621e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (GV->isConstant())
1622354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
1623e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    else
1624354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakAnyLinkage;
16258f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor  } else if (Linkage == GVA_TemplateInstantiation ||
16268f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor             Linkage == GVA_ExplicitTemplateInstantiation)
162799ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return llvm::GlobalVariable::WeakODRLinkage;
16284e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (!getLangOpts().CPlusPlus &&
1629a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1630a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher             D->getAttr<CommonAttr>()) &&
1631309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
1632ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1633ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<WeakImportAttr>()) {
163491f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher    // Thread local vars aren't considered common linkage.
1635354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::GlobalVariable::CommonLinkage;
1636686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
1637354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return llvm::GlobalVariable::ExternalLinkage;
163888a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
16395f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1640bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1641bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1642bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// existing call uses of the old function in the module, this adjusts them to
1643bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// call the new function directly.
1644bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner///
1645bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// This is not just a cleanup: the always_inline pass requires direct calls to
1646bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// functions to be able to inline them.  If there is a bitcast in the way, it
1647bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1648bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner/// run at -O0.
1649bdb0132722082886558f31eccdba06ae1852c0eeChris Lattnerstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1650bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner                                                      llvm::Function *NewFn) {
1651bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  // If we're redefining a global as a function, don't transform it.
1652bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1653bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  if (OldFn == 0) return;
16541eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
16552acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *NewRetTy = NewFn->getReturnType();
16565f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<llvm::Value*, 4> ArgList;
1657bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1658bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1659dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer       UI != E; ) {
1660bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1661dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1662dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
16638670cd3ea4dfbf86caacd270ec2441e9949bbb6aGabor Greif    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
166435db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif    llvm::CallSite CS(CI);
1665dbf02bccc9fc1115cb7dd45c84df77252d68f220Benjamin Kramer    if (!CI || !CS.isCallee(I)) continue;
16661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1667bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the return types don't match exactly, and if the call isn't dead, then
1668bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // we can't transform this call.
1669bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (CI->getType() != NewRetTy && !CI->use_empty())
1670bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
1671bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
167240f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get the attribute list.
167340f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
167440f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::AttrListPtr AttrList = CI->getAttributes();
167540f9c302f23a35611cd354f40b22b37f2c554a40John McCall
167640f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Get any return attributes.
167740f9c302f23a35611cd354f40b22b37f2c554a40John McCall    llvm::Attributes RAttrs = AttrList.getRetAttributes();
167840f9c302f23a35611cd354f40b22b37f2c554a40John McCall
167940f9c302f23a35611cd354f40b22b37f2c554a40John McCall    // Add the return attributes.
168040f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (RAttrs)
168140f9c302f23a35611cd354f40b22b37f2c554a40John McCall      AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
168240f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1683bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If the function was passed too few arguments, don't transform.  If extra
1684bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // arguments were passed, we silently drop them.  If any of the types
1685bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // mismatch, we don't transform.
1686bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    unsigned ArgNo = 0;
1687bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    bool DontTransform = false;
1688bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1689bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
169035db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif      if (CS.arg_size() == ArgNo ||
169135db3b9aad1829a1279b9e213ddee36395314a0bGabor Greif          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1692bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        DontTransform = true;
1693bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
1694bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
169540f9c302f23a35611cd354f40b22b37f2c554a40John McCall
169640f9c302f23a35611cd354f40b22b37f2c554a40John McCall      // Add any parameter attributes.
169740f9c302f23a35611cd354f40b22b37f2c554a40John McCall      if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
169840f9c302f23a35611cd354f40b22b37f2c554a40John McCall        AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1699bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1700bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (DontTransform)
1701bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
17021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
170340f9c302f23a35611cd354f40b22b37f2c554a40John McCall    if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
170440f9c302f23a35611cd354f40b22b37f2c554a40John McCall      AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
170540f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1706bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
1707bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
17086ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
17094c7d9f1507d0f102bd4133bba63348636facd469Jay Foad    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1710bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    ArgList.clear();
1711ffbb15e54a6dc120087003d1e42448b8705bd58aBenjamin Kramer    if (!NewCall->getType()->isVoidTy())
1712bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      NewCall->takeName(CI);
171340f9c302f23a35611cd354f40b22b37f2c554a40John McCall    NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
171440f9c302f23a35611cd354f40b22b37f2c554a40John McCall                                                  AttrVec.end()));
1715ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar    NewCall->setCallingConv(CI->getCallingConv());
1716bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1717bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
171800549fcec0490b2daf27543e532f94adbb186063Chris Lattner    if (!CI->use_empty())
171900549fcec0490b2daf27543e532f94adbb186063Chris Lattner      CI->replaceAllUsesWith(NewCall);
17203b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel
1721c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    // Copy debug location attached to CI.
1722c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    if (!CI->getDebugLoc().isUnknown())
1723c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner      NewCall->setDebugLoc(CI->getDebugLoc());
1724bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    CI->eraseFromParent();
1725bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1726bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1727bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1728025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindolavoid CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1729025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1730025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  // If we have a definition, this might be a deferred decl. If the
1731025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  // instantiation is explicit, make sure we emit it at the end.
1732025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1733025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola    GetAddrOfGlobalVar(VD);
1734234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola}
1735bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1736b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1737b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1738d26bc76c98006609002d9930f8840490e88ac5b5John McCall
17391f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  // Compute the function info and LLVM type.
1740de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1741de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1742d26bc76c98006609002d9930f8840490e88ac5b5John McCall
17439fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
1744b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
17451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17460558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
17470558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
17480558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
17490558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
17500558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
17511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17530558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1754bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
17551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
175642745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
1757bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
17580558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
175934809507232bc4c3c4840c7d092c7440219fddafChris Lattner
176062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
176162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
176262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
176362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
176462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
176562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
1766f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // (e.g. "int f(int x)").  Move the old function aside so that it
1767f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // doesn't interfere with GetAddrOfFunction.
17685f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    OldFn->setName(StringRef());
1769b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
17701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1771bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // If this is an implementation of a function without a prototype, try to
1772bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // replace any existing uses of the function (which may be calls) with uses
1773bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // of the new function
17749fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    if (D->getType()->isFunctionNoProtoType()) {
1775bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
17769fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
17779fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
17781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
177962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
1780bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
17811eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      llvm::Constant *NewPtrForOldDecl =
17823c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1783bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1784bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
17851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
178662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
1787bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
17881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17890558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
1790bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
17911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1792112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // We need to set linkage and visibility on the function before
1793112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // generating code for it because various parts of IR generation
1794112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // want to propagate this information down (e.g. to local static
1795112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // declarations).
17960558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
17978b2423361648c39a7d8a3c5e8129e12006deac32John McCall  setFunctionLinkage(D, Fn);
1798bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1799112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
18000ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(Fn, D);
1801112c967bd5c862a0f5d7913aa06700c048807db8John McCall
1802d26bc76c98006609002d9930f8840490e88ac5b5John McCall  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
18036379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
18047c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
18057c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
18061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
180740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1808219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
180940b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1810219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
181177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
181277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, Fn);
1813bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1814bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1815f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1816f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
181740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  const AliasAttr *AA = D->getAttr<AliasAttr>();
1818bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
1819bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
18205f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
1821f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1822f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // If there is a definition in the module, then it wins over the alias.
1823f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // This is dubious, but allow it to be safe.  Just ignore the alias.
1824f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1825f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  if (Entry && !Entry->isDeclaration())
1826f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return;
18271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18282acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1829bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1830bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
1831bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
1832bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
1833bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
18341faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
18351faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
1836bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
1837f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
183896e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                                    llvm::PointerType::getUnqual(DeclTy), 0);
1839bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
1840bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
18411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *GA =
1842bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
1843bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
1844bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
18451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1846bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
1847f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    assert(Entry->isDeclaration());
1848f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
1849bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
1850bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
1851bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
1852bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
1853bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
1854bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
1855bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
1856f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    GA->takeName(Entry);
18571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18583c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1859bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
1860bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
1861f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else {
18629a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    GA->setName(MangledName);
1863bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
18641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18657c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
18667c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
18677c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
186840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<DLLExportAttr>()) {
18697c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
18707c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
187106a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis      if (FD->hasBody())
18727c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
18737c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
18747c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
18757c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
18761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (D->hasAttr<WeakAttr>() ||
187711e8ce7380856abee188b237c2600272df2ed09dRafael Espindola             D->hasAttr<WeakRefAttr>() ||
18780a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             D->isWeakImported()) {
18797c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
18807c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
18817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
18827c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
1883bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
1884bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
18858dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
18862d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                                            ArrayRef<llvm::Type*> Tys) {
1887df983a8bcbbcea911b8dce283f044787df119d50Jay Foad  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
18888dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer                                         Tys);
18897acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
1890bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
18911d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
18921d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
18931d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         const StringLiteral *Literal,
189470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                         bool TargetIsLSB,
18951d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         bool &IsUTF16,
18961d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         unsigned &StringLength) {
18975f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef String = Literal->getString();
18982f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  unsigned NumBytes = String.size();
18991d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1900f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // Check for simple case.
1901f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  if (!Literal->containsNonAsciiOrNull()) {
1902f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    StringLength = NumBytes;
19032f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    return Map.GetOrCreateValue(String);
1904f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
1905f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
190684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // Otherwise, convert the UTF8 literals into a string of shorts.
190784392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  IsUTF16 = true;
190884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
190984392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
19102f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  const UTF8 *FromPtr = (UTF8 *)String.data();
19111d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  UTF16 *ToPtr = &ToBuf[0];
19121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1913e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1914e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           &ToPtr, ToPtr + NumBytes,
1915e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           strictConversion);
19161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
191770ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
19181d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
191970ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
192084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // Add an explicit null.
192184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  *ToPtr = 0;
192284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  return Map.
192384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
192484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling                               (StringLength + 1) * 2));
19251d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar}
19261d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
1927cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanianstatic llvm::StringMapEntry<llvm::Constant*> &
1928cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz JahanianGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
19298322c23956c4dea057a930753f23ff6467353e55Bill Wendling                       const StringLiteral *Literal,
19308322c23956c4dea057a930753f23ff6467353e55Bill Wendling                       unsigned &StringLength) {
19318322c23956c4dea057a930753f23ff6467353e55Bill Wendling  StringRef String = Literal->getString();
19328322c23956c4dea057a930753f23ff6467353e55Bill Wendling  StringLength = String.size();
19338322c23956c4dea057a930753f23ff6467353e55Bill Wendling  return Map.GetOrCreateValue(String);
1934cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian}
1935cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian
19361d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarllvm::Constant *
19371d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
19381d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  unsigned StringLength = 0;
19391d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool isUTF16 = false;
19401d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringMapEntry<llvm::Constant*> &Entry =
19411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
194270ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             getTargetData().isLittleEndian(),
194370ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             isUTF16, StringLength);
19441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19451d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
19461d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return C;
19471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19488b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
19493e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
19501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19519d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // If we don't already have it, get __CFConstantStringClassReference.
1952c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
19532acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
195496e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    Ty = llvm::ArrayType::get(Ty, 0);
19551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *GV = CreateRuntimeVariable(Ty,
19569d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                                           "__CFConstantStringClassReference");
19573e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
19583e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
1959a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad      llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1960c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
19611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1962e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
19633e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
19642acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::StructType *STy =
1965e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1966e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
19671d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[4];
196844b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
1969c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
19705add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[0] = CFConstantStringClassRef;
19711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1972c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
19732acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
19741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
19755add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    llvm::ConstantInt::get(Ty, 0x07C8);
19765add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
1977c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
197884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  llvm::Constant *C = 0;
197984392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  if (isUTF16) {
198084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    ArrayRef<uint16_t> Arr =
198184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling      llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
198284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling                                   Entry.getKey().size() / 2);
198384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    C = llvm::ConstantDataArray::get(VMContext, Arr);
198484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  } else {
198584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
198684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  }
1987a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
198895b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  llvm::GlobalValue::LinkageTypes Linkage;
19891bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  if (isUTF16)
1990278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // FIXME: why do utf strings get "_" labels instead of "L" labels?
199195b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
19921bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  else
1993584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1994584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // when using private linkage. It is not clear if this is a bug in ld
1995584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // or a reasonable new restriction.
1996dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1997278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
19981bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // Note: -fwritable-strings doesn't make the backing store strings of
19991bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // CFStrings writable. (See <rdar://problem/10657500>)
20001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
20011bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
20021bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling                             Linkage, C, ".str");
2003b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  GV->setUnnamedAddr(true);
2004a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
20054da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
20064da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    GV->setAlignment(Align.getQuantity());
2007f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
2008f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2009f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
2010a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
201184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
201284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // String.
2013a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
20145add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
201584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  if (isUTF16)
201684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    // Cast the UTF16 string to the correct type.
201784392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
201884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
2019c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
2020c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
20215add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
20221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2023c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
202408e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  C = llvm::ConstantStruct::get(STy, Fields);
20251eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
20261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                llvm::GlobalVariable::PrivateLinkage, C,
202795b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                                "_unnamed_cfstring_");
2028bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
20298e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
20301d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  Entry.setValue(GV);
20311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20320c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
2033c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
203445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
203545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregorstatic RecordDecl *
203645c4ea75b235de94f44bf96843624e6a559e4c00Douglas GregorCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
203745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                 DeclContext *DC, IdentifierInfo *Id) {
203845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  SourceLocation Loc;
20394e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Ctx.getLangOpts().CPlusPlus)
204045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
204145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  else
204245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
204345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor}
204445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
204533e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanianllvm::Constant *
20464c73307c74764ba99e1379677fe92af72f676531Fariborz JahanianCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
20472bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  unsigned StringLength = 0;
20482bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::StringMapEntry<llvm::Constant*> &Entry =
2049cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
20502bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
20512bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (llvm::Constant *C = Entry.getValue())
20522bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    return C;
20532bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
2054812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
20552bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zeros[] = { Zero, Zero };
20562bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
2057ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  // If we don't already have it, get _NSConstantStringClassReference.
20584c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  if (!ConstantStringClassRef) {
20594e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    std::string StringClass(getLangOpts().ObjCConstantStringClass);
20602acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
20614c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::Constant *GV;
20624e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (LangOpts.ObjCNonFragileABI) {
206325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
206425dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
206525dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "OBJC_CLASS_$_" + StringClass;
20666f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      GV = getObjCRuntime().GetClassGlobal(str);
20676f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Make sure the result is of the correct type.
20682acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
20696f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
20706f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian        llvm::ConstantExpr::getBitCast(GV, PTy);
20716f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    } else {
207225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
207325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "_NSConstantStringClassReference"
207425dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "_" + StringClass + "ClassReference";
20752acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
207625dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      GV = CreateRuntimeVariable(PTy, str);
20776f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Decay array -> ptr
20786f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
2079a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad        llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
20804c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    }
20812bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
208245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
208345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (!NSConstantStringType) {
208445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Construct the type for a constant NSString.
208545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
208645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                     Context.getTranslationUnitDecl(),
208745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                   &Context.Idents.get("__builtin_NSString"));
208845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->startDefinition();
208945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
209045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType FieldTypes[3];
209145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
209245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const int *isa;
209345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
209445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const char *str;
209545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
209645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // unsigned int length;
209745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[2] = Context.UnsignedIntTy;
209845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
209945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Create fields
210045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    for (unsigned i = 0; i < 3; ++i) {
210145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context, D,
210245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(),
210345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(), 0,
210445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
210545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*BitWidth=*/0,
210645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*Mutable=*/false,
210745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*HasInit=*/false);
210845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      Field->setAccess(AS_public);
210945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      D->addDecl(Field);
211045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    }
211145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
211245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->completeDefinition();
211345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType NSTy = Context.getTagDeclType(D);
211445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
211545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  }
21162bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21171d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[3];
21182bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21192bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // Class pointer.
21204c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  Fields[0] = ConstantStringClassRef;
21212bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21222bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String pointer.
212394010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Constant *C =
212494010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
21252bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21262bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage;
21272bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isConstant;
2128cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  Linkage = llvm::GlobalValue::PrivateLinkage;
21294e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  isConstant = !LangOpts.WritableStrings;
21302bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21312bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalVariable *GV =
21322bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
21332bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                           ".str");
2134803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola  GV->setUnnamedAddr(true);
2135cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2136cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  GV->setAlignment(Align.getQuantity());
2137a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
21382bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21392bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String length.
21402acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
21412bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
21422bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21432bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // The struct.
214445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
21452bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
21462bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
21472bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                "_unnamed_nsstring_");
21482bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // FIXME. Fix section.
2149ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  if (const char *Sect =
21504e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie        LangOpts.ObjCNonFragileABI
2151bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2152bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          : getContext().getTargetInfo().getNSStringSection())
21532bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setSection(Sect);
21542bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Entry.setValue(GV);
21552bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
21562bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  return GV;
215733e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian}
215833e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian
21590815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas GregorQualType CodeGenModule::getObjCFastEnumerationStateType() {
21600815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  if (ObjCFastEnumerationStateType.isNull()) {
21610815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
21620815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                     Context.getTranslationUnitDecl(),
21630815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                      &Context.Idents.get("__objcFastEnumerationState"));
21640815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->startDefinition();
21650815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
21660815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    QualType FieldTypes[] = {
21670815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.UnsignedLongTy,
21680815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.getObjCIdType()),
21690815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.UnsignedLongTy),
21700815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getConstantArrayType(Context.UnsignedLongTy,
21710815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                           llvm::APInt(32, 5), ArrayType::Normal, 0)
21720815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    };
21730815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
21740815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    for (size_t i = 0; i < 4; ++i) {
21750815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context,
21760815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           D,
21770815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(),
21780815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(), 0,
21790815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
21800815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*BitWidth=*/0,
21810815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*Mutable=*/false,
21820815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*HasInit=*/false);
21830815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Field->setAccess(AS_public);
21840815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      D->addDecl(Field);
21850815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    }
21860815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
21870815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->completeDefinition();
21880815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
21890815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  }
21900815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
21910815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  return ObjCFastEnumerationStateType;
21920815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor}
21930815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
219464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedmanllvm::Constant *
219564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli FriedmanCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
219664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  assert(!E->getType()->isPointerType() && "Strings are always arrays");
219764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
219864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // Don't emit it as the address of the string, emit the string data itself
219964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // as an inline array.
2200812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  if (E->getCharByteWidth() == 1) {
2201812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    SmallString<64> Str(E->getString());
2202812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner
2203812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    // Resize the string to the right size, which is indicated by its type.
2204812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2205812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    Str.resize(CAT->getSize().getZExtValue());
2206812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    return llvm::ConstantDataArray::getString(VMContext, Str, false);
2207812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  }
220894010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner
220994010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::ArrayType *AType =
221094010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
221194010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Type *ElemTy = AType->getElementType();
221294010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  unsigned NumElements = AType->getNumElements();
2213d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2214d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  // Wide strings have either 2-byte or 4-byte elements.
2215d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  if (ElemTy->getPrimitiveSizeInBits() == 16) {
2216d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    SmallVector<uint16_t, 32> Elements;
2217d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.reserve(NumElements);
2218d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2219d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2220d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner      Elements.push_back(E->getCodeUnit(i));
2221d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.resize(NumElements);
2222d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    return llvm::ConstantDataArray::get(VMContext, Elements);
222394010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  }
222494010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner
2225d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  assert(ElemTy->getPrimitiveSizeInBits() == 32);
2226d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  SmallVector<uint32_t, 32> Elements;
2227d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  Elements.reserve(NumElements);
2228d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2229d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2230d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.push_back(E->getCodeUnit(i));
2231d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  Elements.resize(NumElements);
2232d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  return llvm::ConstantDataArray::get(VMContext, Elements);
223364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman}
223464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
22356143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
22366143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
22376143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
22386143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2239a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  CharUnits Align = getContext().getTypeAlignInChars(S->getType());
224064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (S->isAscii() || S->isUTF8()) {
2241812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    SmallString<64> Str(S->getString());
2242812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner
2243812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    // Resize the string to the right size, which is indicated by its type.
2244812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2245812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    Str.resize(CAT->getSize().getZExtValue());
2246812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
22477eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  }
224864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
2249812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  // FIXME: the following does not memoize wide strings.
225064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
225164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::GlobalVariable *GV =
225264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    new llvm::GlobalVariable(getModule(),C->getType(),
22534e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie                             !LangOpts.WritableStrings,
225464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             llvm::GlobalValue::PrivateLinkage,
225564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             C,".str");
22567d6a7c004361c45a463874a58da28d9f3c35f2e6Seth Cantrell
225764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setAlignment(Align.getQuantity());
225864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setUnnamedAddr(true);
225964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  return GV;
22606143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
22616143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
2262eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2263eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
2264eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
2265eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2266eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
2267eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2268a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
2269a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
2270eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
2271eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2272eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2273a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
2274a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCallstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
227545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
22765fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
2277a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             const char *GlobalName,
2278a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             unsigned Alignment) {
22796143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
22800032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C =
228194010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
22821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
228345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
22841257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  llvm::GlobalVariable *GV =
22851257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
22861257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             llvm::GlobalValue::PrivateLinkage,
22871257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             C, GlobalName);
2288a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  GV->setAlignment(Alignment);
22891257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  GV->setUnnamedAddr(true);
22901257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  return GV;
229145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
229245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
22936143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
22946143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
22956143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
22966143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
22976143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
22986143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
22996143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
23006143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
23015f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2302a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       const char *GlobalName,
2303a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       unsigned Alignment) {
23048e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
23058e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
230695b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GlobalName = ".str";
23078e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
23088e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
23094e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.WritableStrings)
2310a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
23111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2312a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
23139de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    ConstantStringMap.GetOrCreateValue(Str);
231445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
2315a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2316a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    if (Alignment > GV->getAlignment()) {
2317a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      GV->setAlignment(Alignment);
2318a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    }
2319a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GV;
2320a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  }
232145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
232245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
2323812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2324812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner                                                   Alignment);
2325a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  Entry.setValue(GV);
2326a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GV;
232745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
23286143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
23296143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
23309de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer/// array containing the literal and a terminating '\0'
23316143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
23329de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2333a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        const char *GlobalName,
2334a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        unsigned Alignment) {
23355f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2336a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
23376143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
233841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2339af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
2340af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
23411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::EmitObjCPropertyImplementations(const
2342af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
23431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCImplementationDecl::propimpl_iterator
234417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2345af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCPropertyImplDecl *PID = *i;
23461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2347af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
2348af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2349af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2350af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2351af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
2352af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // been overridden. Note that ::isSynthesized is not the method
2353af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
2354af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
2355af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
235617945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (!D->getInstanceMethod(PD->getGetterName()))
2357fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
2358fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2359af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
236017945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis          !D->getInstanceMethod(PD->getSetterName()))
2361fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
2362fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2363af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
2364af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2365af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
2366af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2367e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCallstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
2368db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2369db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2370e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall       ivar; ivar = ivar->getNextIvar())
2371e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (ivar->getType().isDestructedType())
2372e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      return true;
2373e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2374e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return false;
2375e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
2376e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2377109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// EmitObjCIvarInitializations - Emit information for ivar initialization
2378109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// for an implementation.
2379109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanianvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2380e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2381e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (needsDestructMethod(D)) {
2382e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2383e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2384e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    ObjCMethodDecl *DTORMethod =
2385e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
238675cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             cxxSelector, getContext().VoidTy, 0, D,
238775cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isInstance=*/true, /*isVariadic=*/false,
238875cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                          /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
238975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isDefined=*/false, ObjCMethodDecl::Required);
2390e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    D->addInstanceMethod(DTORMethod);
2391e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2392f85e193739c953358c865005855253af4f68a497John McCall    D->setHasCXXStructors(true);
2393e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  }
2394e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2395e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // If the implementation doesn't have any ivar initializers, we don't need
2396e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // a .cxx_construct.
2397827bbcc8a9115782693b21030a45378abe5c1862David Chisnall  if (D->getNumIvarInitializers() == 0)
2398109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    return;
2399109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
2400e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2401e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2402109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // The constructor returns 'self'.
2403109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2404109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(),
240511d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                D->getLocation(),
240611d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                cxxSelector,
2407109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                getContext().getObjCIdType(), 0,
240875cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                D, /*isInstance=*/true,
240975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isVariadic=*/false,
241075cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isSynthesized=*/true,
241175cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isImplicitlyDeclared=*/true,
241275cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isDefined=*/false,
2413109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                ObjCMethodDecl::Required);
2414109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  D->addInstanceMethod(CTORMethod);
2415109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2416f85e193739c953358c865005855253af4f68a497John McCall  D->setHasCXXStructors(true);
2417109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian}
2418109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
241991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
2420984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
242117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2422984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
2423984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
2424984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
2425984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
242691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
242791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2428f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2429f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
243091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
243191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
243291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
243391e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
243417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
243591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson       I != E; ++I)
243691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
243791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
243891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
243941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
244041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
244141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
244241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
244341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
244441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
244541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
244641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
244716e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  // Ignore dependent declarations.
244816e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
244916e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    return;
24501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
245141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
2452293361afd4199c92aabff9267fddea890943c586Anders Carlsson  case Decl::CXXConversion:
24532b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
245441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
245516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    // Skip function templates
24568387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
24578387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
245816e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      return;
24591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2460555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<FunctionDecl>(D));
2461555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    break;
2462555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson
246341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
2464555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<VarDecl>(D));
246541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
246641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
246726fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // Indirect fields from global anonymous structs and unions can be
246826fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // ignored; only the actual variable requires IR gen support.
246926fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  case Decl::IndirectField:
247026fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall    break;
247126fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
247295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
247341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
2474984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
247541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
24769cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    // No code generation needed.
24779d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  case Decl::UsingShadow:
24789cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  case Decl::Using:
2479dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  case Decl::UsingDirective:
2480127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::ClassTemplate:
2481127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::FunctionTemplate:
24823e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  case Decl::TypeAliasTemplate:
2483018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  case Decl::NamespaceAlias:
24846a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor  case Decl::Block:
248515de72cf580840c61e5704c2f8a2b56f9d0638e1Douglas Gregor  case Decl::Import:
24869cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    break;
248795d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
24881fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    // Skip function templates
24898387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
24908387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
24911fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson      return;
24921fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
249395d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
249495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
249527ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
24968387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
24978387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      return;
249827ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
249927ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
250036674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
250136674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  case Decl::StaticAssert:
250236674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    // Nothing to do.
250336674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    break;
250436674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
250595d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
25061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
250738e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
2508b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
250941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2510000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian
2511baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  case Decl::ObjCCategory: {
2512baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2513baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    if (CD->IsClassExtension() && CD->hasSynthBitfield())
2514baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner      Context.ResetObjCLayout(CD->getClassInterface());
2515baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner    break;
2516baf101d1f96b4e41c9f2797875329840514f54f1Chris Lattner  }
2517285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
2518bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  case Decl::ObjCProtocol: {
2519bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2520bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    if (Proto->isThisDeclarationADefinition())
2521bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor      ObjCRuntime->GenerateProtocol(Proto);
252241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2523bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  }
2524bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor
252541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
2526af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
2527af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
2528e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
252941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
253041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2531af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
2532af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
25334e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2534000835d0b04345c0014c603fe6339b3bc154050eFariborz Jahanian      Context.ResetObjCLayout(OMD->getClassInterface());
2535af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
2536109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    EmitObjCIvarInitializations(OMD);
2537e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateClass(OMD);
2538be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher    // Emit global variable debug information.
2539be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher    if (CGDebugInfo *DI = getModuleDebugInfo())
2540be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher      DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()),
2541be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher				   OMD->getLocation());
2542be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher
254341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
25441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
254541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
254641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
254741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
25486fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (OMD->getBody())
254941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
255041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
255141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
25521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::ObjCCompatibleAlias:
255329254f4dd114fe2dd5c4e7a261ebea941973ad3dDavid Chisnall    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
255441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
255541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
255691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
255791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
255841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
255941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
256041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
256141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
25625f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef AsmString = AD->getAsmString()->getString();
25631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
256441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
256541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
256641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
25679f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner    else if (*--S.end() == '\n')
25689f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner      getModule().setModuleInlineAsm(S + AsmString.str());
256941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
25708d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
257141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
257241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
25731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
25741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  default:
2575f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // Make sure we handled everything we should, every other kind is a
2576f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2577f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // function. Need to recode Decl::Kind to do that easily.
257841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
257941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
258041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
2581744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2582744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Turns the given pointer into a constant.
2583744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2584744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                          const void *Ptr) {
2585744016dde06fcffd50931e94a98c850f8b12cd87John McCall  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
25862acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2587744016dde06fcffd50931e94a98c850f8b12cd87John McCall  return llvm::ConstantInt::get(i64, PtrInt);
2588744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2589744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2590744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2591744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::NamedMDNode *&GlobalMetadata,
2592744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   GlobalDecl D,
2593744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::GlobalValue *Addr) {
2594744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (!GlobalMetadata)
2595744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GlobalMetadata =
2596744016dde06fcffd50931e94a98c850f8b12cd87John McCall      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2597744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2598744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // TODO: should we report variant information for ctors/dtors?
2599744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::Value *Ops[] = {
2600744016dde06fcffd50931e94a98c850f8b12cd87John McCall    Addr,
2601744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2602744016dde06fcffd50931e94a98c850f8b12cd87John McCall  };
26036f141659cab11109d9931d92d0988f8850778de3Jay Foad  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2604744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2605744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2606744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes associating all the global values in the
2607744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// current module with the Decls they came from.  This is useful for
2608744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// projects using IR gen as a subroutine.
2609744016dde06fcffd50931e94a98c850f8b12cd87John McCall///
2610744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Since there's currently no way to associate an MDNode directly
2611744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with an llvm::GlobalValue, we create a global named metadata
2612744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with the name 'clang.global.decl.ptrs'.
2613744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenModule::EmitDeclMetadata() {
2614744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2615744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2616744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // StaticLocalDeclMap
26175f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2618744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2619744016dde06fcffd50931e94a98c850f8b12cd87John McCall       I != E; ++I) {
2620744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2621744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2622744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2623744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2624744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2625744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes for all the local variables in the current
2626744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// function.
2627744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenFunction::EmitDeclMetadata() {
2628744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (LocalDeclMap.empty()) return;
2629744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2630744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::LLVMContext &Context = getLLVMContext();
2631744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2632744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Find the unique metadata ID for this name.
2633744016dde06fcffd50931e94a98c850f8b12cd87John McCall  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2634744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2635744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2636744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2637744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2638744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2639744016dde06fcffd50931e94a98c850f8b12cd87John McCall    const Decl *D = I->first;
2640744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::Value *Addr = I->second;
2641744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2642744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2643744016dde06fcffd50931e94a98c850f8b12cd87John McCall      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
26446f141659cab11109d9931d92d0988f8850778de3Jay Foad      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2645744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2646744016dde06fcffd50931e94a98c850f8b12cd87John McCall      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2647744016dde06fcffd50931e94a98c850f8b12cd87John McCall      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2648744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2649744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2650744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2651673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
26523dc05418538c719fea48b906bfa4febe5296e126Nick Lewyckyvoid CodeGenModule::EmitCoverageFile() {
26533dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky  if (!getCodeGenOpts().CoverageFile.empty()) {
26545ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
26555ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
26565ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::LLVMContext &Ctx = TheModule.getContext();
26573dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky      llvm::MDString *CoverageFile =
26583dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
26595ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
26605ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *CU = CUNode->getOperand(i);
26613dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky        llvm::Value *node[] = { CoverageFile, CU };
26625ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
26635ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        GCov->addOperand(N);
26645ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      }
26655ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
26665ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  }
26675ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky}
2668