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"
156c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne#include "CGCUDARuntime.h"
164c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall#include "CGCXXABI.h"
1755fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CGCall.h"
1855fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CGDebugInfo.h"
19af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGObjCRuntime.h"
208c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne#include "CGOpenCLRuntime.h"
2155fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CodeGenFunction.h"
2255fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CodeGenTBAA.h"
2382d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov#include "TargetInfo.h"
245f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
25687cc4a850b59116efee061018f0d8df50728b82Ken Dyck#include "clang/AST/CharUnits.h"
2621ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
2755fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/AST/DeclObjC.h"
28af896897f7485176f43d40c4adced7efb0fb2b06Douglas Gregor#include "clang/AST/DeclTemplate.h"
2914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne#include "clang/AST/Mangle.h"
301a5e0d7f18485e4fb958f96dcddff3e4486a4069Anders Carlsson#include "clang/AST/RecordLayout.h"
31a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola#include "clang/AST/RecursiveASTVisitor.h"
32bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola#include "clang/Basic/Builtins.h"
333f6f51e28231f65de9c2dd150a2d757b2162cfa3Jordan Rose#include "clang/Basic/CharInfo.h"
342c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/Basic/Diagnostic.h"
35b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor#include "clang/Basic/Module.h"
368bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
375f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
38e1092dfee2bbcc2243421c553bca488880324280Bill Wendling#include "clang/Basic/TargetOptions.h"
3955fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
4019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl#include "llvm/ADT/APSInt.h"
416374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall#include "llvm/ADT/Triple.h"
423b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/CallingConv.h"
433b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/DataLayout.h"
443b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/Intrinsics.h"
453b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/LLVMContext.h"
463b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/Module.h"
476ba728d9687b2617793f5afd410650a8d6c71080Gabor Greif#include "llvm/Support/CallSite.h"
48cb5620c9b213f4bd323912159fdddda35e258a14Dmitri Gribenko#include "llvm/Support/ConvertUTF.h"
4978f7ece00e2ddfb64d4ed72a7be770b5b9b805e3Chris Lattner#include "llvm/Support/ErrorHandling.h"
5055fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "llvm/Target/Mangler.h"
51cb5620c9b213f4bd323912159fdddda35e258a14Dmitri Gribenko
525f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
545f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
5577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougestatic const char AnnotationSection[] = "llvm.metadata";
5677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
57f16aa103d3afd42fbca2ab346f191bf745cec092John McCallstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
58b8b2c9da87e7d70a1679db026f40548b3192b705John McCall  switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
59c264e16a42b3f6c36521857a29ea0949d9781c22Tim Northover  case TargetCXXABI::GenericAArch64:
6096fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall  case TargetCXXABI::GenericARM:
6196fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall  case TargetCXXABI::iOS:
6296fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall  case TargetCXXABI::GenericItanium:
6396fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall    return *CreateItaniumCXXABI(CGM);
6496fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall  case TargetCXXABI::Microsoft:
6596fcde0b8ed8bdf99d326312ca7be6447b0fe5fcJohn McCall    return *CreateMicrosoftCXXABI(CGM);
66f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  }
67f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
68f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  llvm_unreachable("invalid C++ ABI kind");
69f16aa103d3afd42fbca2ab346f191bf745cec092John McCall}
70f16aa103d3afd42fbca2ab346f191bf745cec092John McCall
715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
722811ccf48d6d898c42cc4cfad37abedb36236d20Chandler CarruthCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
73e1092dfee2bbcc2243421c553bca488880324280Bill Wendling                             const TargetOptions &TO, llvm::Module &M,
74e1092dfee2bbcc2243421c553bca488880324280Bill Wendling                             const llvm::DataLayout &TD,
75d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie                             DiagnosticsEngine &diags)
76e1092dfee2bbcc2243421c553bca488880324280Bill Wendling  : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TargetOpts(TO),
77e1092dfee2bbcc2243421c553bca488880324280Bill Wendling    TheModule(M), TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
78f16aa103d3afd42fbca2ab346f191bf745cec092John McCall    ABI(createCXXABI(*this)),
79de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    Types(*this),
803d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    TBAA(0),
816c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
82b49bd27b334a6c4e3bf9d810a7d5b022578f1194Dan Gohman    DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
83b49bd27b334a6c4e3bf9d810a7d5b022578f1194Dan Gohman    RRData(0), CFConstantStringClassRef(0),
846c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    ConstantStringClassRef(0), NSConstantStringType(0),
85673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    VMContext(M.getContext()),
86673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
87d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall    BlockObjectAssign(0), BlockObjectDispose(0),
884f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz    BlockDescriptorType(0), GenericBlockLiteralType(0),
894f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz    SanitizerBlacklist(CGO.SanitizerBlacklistFile),
904f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz    SanOpts(SanitizerBlacklist.isIn(M) ?
914f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz            SanitizerOptions::Disabled : LangOpts.Sanitize) {
924f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz
938b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  // Initialize the type cache.
948b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  llvm::LLVMContext &LLVMContext = M.getContext();
958b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  VoidTy = llvm::Type::getVoidTy(LLVMContext);
968b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
978b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
988b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
998b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1008b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  FloatTy = llvm::Type::getFloatTy(LLVMContext);
1018b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
1028b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
1038b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  PointerAlignInBytes =
1048b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1058b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1068b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
1078b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8PtrTy = Int8Ty->getPointerTo(0);
1088b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1098b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner
110bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
111bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall
1124e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.ObjC1)
1138c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createObjCRuntime();
1144e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.OpenCL)
1158c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    createOpenCLRuntime();
1164e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CUDA)
1176c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne    createCUDARuntime();
118e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
119c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany  // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
1204f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz  if (SanOpts.Thread ||
121c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany      (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
122c9fe6056e4ce8ffad1ef439fca3318a5faf1c075Kostya Serebryany    TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
1230b5c4fc2ae3b503c2b1f354bf52b718aa50a6aeeDan Gohman                           ABI.getMangleContext());
1243d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
125e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // If debug info or coverage generation is enabled, create the CGDebugInfo
126e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky  // object.
1274cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor  if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
1283a70cd6e1cc414856e41ce5509aa61c89bf472dcAlexey Samsonov      CodeGenOpts.EmitGcovArcs ||
129e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky      CodeGenOpts.EmitGcovNotes)
130e8ba8d78a258ec992d3521eebdae8324db777b14Nick Lewycky    DebugInfo = new CGDebugInfo(*this);
131d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall
132d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall  Block.GlobalUniqueCount = 0;
1335936e33bf74dd6bf126ceee0f6169a2593d03a69John McCall
1344e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (C.getLangOpts().ObjCAutoRefCount)
135f85e193739c953358c865005855253af4f68a497John McCall    ARCData = new ARCEntrypoints();
136f85e193739c953358c865005855253af4f68a497John McCall  RRData = new RREntrypoints();
1372b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
1382b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
1392b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
140e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  delete ObjCRuntime;
1418c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  delete OpenCLRuntime;
1426c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  delete CUDARuntime;
1430628b724ff68105dc88af00a39f859447f22981eTed Kremenek  delete TheTargetCodeGenInfo;
144f16aa103d3afd42fbca2ab346f191bf745cec092John McCall  delete &ABI;
1454376c85fb0ac9e7fd779d246efc77e1169179138Dan Gohman  delete TBAA;
146815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
147f85e193739c953358c865005855253af4f68a497John McCall  delete ARCData;
148f85e193739c953358c865005855253af4f68a497John McCall  delete RRData;
149815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
150815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
1510d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnallvoid CodeGenModule::createObjCRuntime() {
152260611a32535c851237926bfcf78869b13c07d5bJohn McCall  // This is just isGNUFamily(), but we want to force implementors of
153260611a32535c851237926bfcf78869b13c07d5bJohn McCall  // new ABIs to decide how best to do this.
154260611a32535c851237926bfcf78869b13c07d5bJohn McCall  switch (LangOpts.ObjCRuntime.getKind()) {
15511d3f4cc27e6b923fc32481dc1bb5ec46c7d1f4bDavid Chisnall  case ObjCRuntime::GNUstep:
15611d3f4cc27e6b923fc32481dc1bb5ec46c7d1f4bDavid Chisnall  case ObjCRuntime::GCC:
157f7226fbe677a9c7578fa0613491ed15c6dc6a5e1John McCall  case ObjCRuntime::ObjFW:
158e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateGNUObjCRuntime(*this);
159260611a32535c851237926bfcf78869b13c07d5bJohn McCall    return;
160260611a32535c851237926bfcf78869b13c07d5bJohn McCall
161260611a32535c851237926bfcf78869b13c07d5bJohn McCall  case ObjCRuntime::FragileMacOSX:
162260611a32535c851237926bfcf78869b13c07d5bJohn McCall  case ObjCRuntime::MacOSX:
163260611a32535c851237926bfcf78869b13c07d5bJohn McCall  case ObjCRuntime::iOS:
164e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime = CreateMacObjCRuntime(*this);
165260611a32535c851237926bfcf78869b13c07d5bJohn McCall    return;
166260611a32535c851237926bfcf78869b13c07d5bJohn McCall  }
167260611a32535c851237926bfcf78869b13c07d5bJohn McCall  llvm_unreachable("bad runtime kind");
1680d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall}
1690d13f6fdbdd6f06e2449b8834dda53334abd399aDavid Chisnall
1708c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbournevoid CodeGenModule::createOpenCLRuntime() {
1718c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne  OpenCLRuntime = new CGOpenCLRuntime(*this);
1728c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne}
1738c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne
1746c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbournevoid CodeGenModule::createCUDARuntime() {
1756c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne  CUDARuntime = CreateNVCUDARuntime(*this);
1766c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne}
1776c0aa5ff6e6253db0f993053599e2a52b5b93b2dPeter Collingbourne
178815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
17982227ff4eb665bbf41720ebdc0dc9215a86ba838Chris Lattner  EmitDeferred();
1806c6bda3b0b1d8adaac2ba3f4da7056e9f1eef52eEli Friedman  EmitCXXGlobalInitFunc();
181efb0fa9e11f75af51744a6159530ef7cc8efa24aDaniel Dunbar  EmitCXXGlobalDtorFunc();
182e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne  if (ObjCRuntime)
183e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
184208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
1856bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
1866bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
18777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  EmitGlobalAnnotations();
1880269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
189f43b7214e812ddca74a6213608c69c960e067956Douglas Gregor
190f43b7214e812ddca74a6213608c69c960e067956Douglas Gregor  if (CodeGenOpts.ModulesAutolink) {
191f43b7214e812ddca74a6213608c69c960e067956Douglas Gregor    EmitModuleLinkOptions();
192f43b7214e812ddca74a6213608c69c960e067956Douglas Gregor  }
1935d75ea72d6eee3df0c6acdb282145dc4cc3a9a1bDouglas Gregor
194b25938303de0976b9f189363d43033e5788e3d36John McCall  SimplifyPersonality();
195b25938303de0976b9f189363d43033e5788e3d36John McCall
196744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (getCodeGenOpts().EmitDeclMetadata)
197744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitDeclMetadata();
1985ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky
1995ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
2003dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky    EmitCoverageFile();
201f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel
202f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel  if (DebugInfo)
203f391dbe39dca85f2a2c6ea558811dacc571c223eDevang Patel    DebugInfo->finalize();
204f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
205f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
206e80d56771736c85fd8365c394a6731923b17e91dDevang Patelvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
207e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  // Make sure that this type is translated.
208e80d56771736c85fd8365c394a6731923b17e91dDevang Patel  Types.UpdateCompletedType(TD);
209e80d56771736c85fd8365c394a6731923b17e91dDevang Patel}
210e80d56771736c85fd8365c394a6731923b17e91dDevang Patel
2113d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
2123d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  if (!TBAA)
2133d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman    return 0;
2143d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  return TBAA->getTBAAInfo(QTy);
2153d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
2163d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
2178cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryanyllvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
2188cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany  if (!TBAA)
2198cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany    return 0;
2208cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany  return TBAA->getTBAAInfoForVTablePtr();
2218cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany}
2228cb4a070d491ddd671b049110cc8d0accb08b905Kostya Serebryany
223b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohmanllvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
224b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman  if (!TBAA)
225b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman    return 0;
226b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman  return TBAA->getTBAAStructInfo(QTy);
227b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman}
228b22c7dc707cf3770ff3b5e5f11f11fd0aaa06d9bDan Gohman
2293d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohmanvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
2303d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman                                        llvm::MDNode *TBAAInfo) {
2313d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
2323d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman}
2333d5aff5d3036b0ff09d114857cd2276134b3d8c9Dan Gohman
2346374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCallbool CodeGenModule::isTargetDarwin() const {
235bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  return getContext().getTargetInfo().getTriple().isOSDarwin();
2366374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall}
2376374c3307e2d73348f7b8cc73eeeb0998ad0ac94John McCall
2380f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruthvoid CodeGenModule::Error(SourceLocation loc, StringRef error) {
2390f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
24032096695c76033a6b0b1747c439f7378a11e8312John McCall  getDiags().Report(Context.getFullLoc(loc), diagID);
24132096695c76033a6b0b1747c439f7378a11e8312John McCall}
24232096695c76033a6b0b1747c439f7378a11e8312John McCall
243488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
2442c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
24590df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
24690df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
24790df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
24890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
249d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
25056b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
2512c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
2520a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
2530a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
2542c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
25558c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
256488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
257c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
25890df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
25990df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
26090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
26190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
262d6471f7c1921c7802804ce3ff6fe9768310f72b9David Blaikie  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
26356b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
264c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
2650a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
266c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
267c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
268bc8d40d85f3fa1e34569834916f18fecaa635152John McCallllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
269bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
270bc8d40d85f3fa1e34569834916f18fecaa635152John McCall}
271bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
2721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
2730ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson                                        const NamedDecl *D) const {
27404d4078425614bf9fd58d606335c1f5f74ee7fa4Daniel Dunbar  // Internal definitions always have default visibility.
275df102fcb978588d5edbc661fb5da0b6922f9ab1cChris Lattner  if (GV->hasLocalLinkage()) {
2767e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
2776ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar    return;
2787e714cd931fa3a90bfd728318a92485aa3e95748Daniel Dunbar  }
2796ab187a49a42de6d351248d8a6e0206e39743a0cDaniel Dunbar
280af14603ca61757cf4361b583b45639a04c57e651John McCall  // Set visibility for definitions.
2812beda12c3fbaa9125831b7f818680978c596b205Rafael Espindola  LinkageInfo LV = D->getLinkageAndVisibility();
282f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola  if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
283f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola    GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
2847cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian}
2857cd2e93125e2f3b6ca01b24ed0c3fd7e94683fd9Fariborz Jahanian
286de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborgstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
287de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
288de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
289de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
290de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
291de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
292de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg}
293de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
294de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborgstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
295de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    CodeGenOptions::TLSModel M) {
296de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  switch (M) {
297de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::GeneralDynamicTLSModel:
298de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::GeneralDynamicTLSModel;
299de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::LocalDynamicTLSModel:
300de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::LocalDynamicTLSModel;
301de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::InitialExecTLSModel:
302de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::InitialExecTLSModel;
303de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  case CodeGenOptions::LocalExecTLSModel:
304de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    return llvm::GlobalVariable::LocalExecTLSModel;
305de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  }
306de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  llvm_unreachable("Invalid TLS model!");
307de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg}
308de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
309de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborgvoid CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
310de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg                               const VarDecl &D) const {
311de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
312de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
313de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  llvm::GlobalVariable::ThreadLocalMode TLM;
3144cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor  TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
315de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
316de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  // Override the TLS model if it is explicitly specified.
317de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  if (D.hasAttr<TLSModelAttr>()) {
318de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
319de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    TLM = GetLLVMTLSModel(Attr->getModel());
320de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  }
321de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
322de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg  GV->setThreadLocalMode(TLM);
323de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg}
324de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
325cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// Set the symbol visibility of type information (vtable and RTTI)
326cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall/// associated with the given type.
327cbfe50224b19119e759802bd0c1463269dffd09eJohn McCallvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
328cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall                                      const CXXRecordDecl *RD,
329fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson                                      TypeVisibilityKind TVK) const {
3300ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(GV, RD);
331cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
332279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall  if (!CodeGenOpts.HiddenWeakVTables)
333279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall    return;
334279b5eb6910d64a293e9c0e2887a05c65d8737d7John McCall
3359a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  // We never want to drop the visibility for RTTI names.
3369a86a137b0872bad25161fb3408a71d919638757Anders Carlsson  if (TVK == TVK_ForRTTIName)
3379a86a137b0872bad25161fb3408a71d919638757Anders Carlsson    return;
3389a86a137b0872bad25161fb3408a71d919638757Anders Carlsson
339cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We want to drop the visibility to hidden for weak type symbols.
340cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // This isn't possible if there might be unresolved references
341cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // elsewhere that rely on this symbol being visible.
342cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3437a536907da776bdc47a704e7cafd641e8150e653John McCall  // This should be kept roughly in sync with setThunkVisibility
3447a536907da776bdc47a704e7cafd641e8150e653John McCall  // in CGVTables.cpp.
3457a536907da776bdc47a704e7cafd641e8150e653John McCall
346cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Preconditions.
347f502d93b0ea970bfbd897e657f8d940a20984de2Anders Carlsson  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
348cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
349cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
350cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
351cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Don't override an explicit visibility attribute.
352d4c3d66be70ae2d0bd828329022dc428cc277a1cJohn McCall  if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
353cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
354cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
355cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  switch (RD->getTemplateSpecializationKind()) {
356cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // We have to disable the optimization if this is an EI definition
357cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // because there might be EI declarations in other shared objects.
358cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDefinition:
359cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ExplicitInstantiationDeclaration:
360cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    return;
361cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3627a536907da776bdc47a704e7cafd641e8150e653John McCall  // Every use of a non-template class's type information has to emit it.
363cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_Undeclared:
364cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall    break;
365cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3667a536907da776bdc47a704e7cafd641e8150e653John McCall  // In theory, implicit instantiations can ignore the possibility of
3677a536907da776bdc47a704e7cafd641e8150e653John McCall  // an explicit instantiation declaration because there necessarily
3687a536907da776bdc47a704e7cafd641e8150e653John McCall  // must be an EI definition somewhere with default visibility.  In
3697a536907da776bdc47a704e7cafd641e8150e653John McCall  // practice, it's possible to have an explicit instantiation for
3707a536907da776bdc47a704e7cafd641e8150e653John McCall  // an arbitrary template class, and linkers aren't necessarily able
3717a536907da776bdc47a704e7cafd641e8150e653John McCall  // to deal with mixed-visibility symbols.
3727a536907da776bdc47a704e7cafd641e8150e653John McCall  case TSK_ExplicitSpecialization:
373cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  case TSK_ImplicitInstantiation:
374aafd111afa6acd50fe4bec6c41add02ecf556535Douglas Gregor    return;
375cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  }
376cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
377cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // If there's a key function, there may be translation units
378cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // that don't have the key function's definition.  But ignore
379cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // this if we're emitting RTTI under -fno-rtti.
3804e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
381d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall    // FIXME: what should we do if we "lose" the key function during
382d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall    // the emission of the file?
383d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall    if (Context.getCurrentKeyFunction(RD))
384cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall      return;
385fa2e99f72f9bfe2270ea8caf76d0eef11c45259fAnders Carlsson  }
386cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
387cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  // Otherwise, drop the visibility to hidden.
388cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
389b1c65ff108de47a89585ad37874bd6cb232664cdRafael Espindola  GV->setUnnamedAddr(true);
390cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall}
391cbfe50224b19119e759802bd0c1463269dffd09eJohn McCall
3925f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerStringRef CodeGenModule::getMangledName(GlobalDecl GD) {
393793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
394793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3955f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
396793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (!Str.empty())
397793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
398793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
3994c40d98ab7acf5f27fa89b17bd8fc0ef7683df37John McCall  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
400793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    IdentifierInfo *II = ND->getIdentifier();
401793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    assert(II && "Attempt to mangle unnamed decl.");
402793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
403793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    Str = II->getName();
404793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson    return Str;
405793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  }
406793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
407f7ccbad5d9949e7ddd1cbef43d482553b811e026Dylan Noblesmith  SmallString<256> Buffer;
408c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer);
409793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
410c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
411793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
412c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
413793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
4144904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    getCXXABI().getMangleContext().mangleBlock(BD, Out,
4154904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
416793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  else
417c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    getCXXABI().getMangleContext().mangleName(ND, Out);
418793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
419793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  // Allocate space for the mangled name.
420c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  Out.flush();
421793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  size_t Length = Buffer.size();
422793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  char *Name = MangledNamesAllocator.Allocate<char>(Length);
423793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  std::copy(Buffer.begin(), Buffer.end(), Name);
424793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
4255f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  Str = StringRef(Name, Length);
426793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
427793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson  return Str;
428793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson}
429793a990774826a0c20b0da66cec0991badfb8b63Anders Carlsson
43014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbournevoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
43114110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne                                        const BlockDecl *BD) {
43214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  MangleContext &MangleCtx = getCXXABI().getMangleContext();
43314110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  const Decl *D = GD.getDecl();
434c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola  llvm::raw_svector_ostream Out(Buffer.getBuffer());
43514110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  if (D == 0)
4364904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    MangleCtx.mangleGlobalBlock(BD,
4374904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
43814110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
439c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
44014110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
441c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
44214110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne  else
443c4850c2aa4c281a352e228aafc51fb1e30dcad02Rafael Espindola    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
4449a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson}
4459a8822bb154b792cdb18fe4cfb34480ca0ec7661Anders Carlsson
4465f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
447f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return getModule().getNamedValue(Name);
4485f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
4495f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
4506d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
4516d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
4526bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
45349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
4546bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
4556d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
4566d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
4576bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
4586bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
4596bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
46049988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
4616bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
4626bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
4636bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4646bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
4656bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
4660774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
46796e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
4686bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4696bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
470c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  llvm::StructType *CtorStructTy =
4718b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner    llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
4726bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4736bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
4740b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  SmallVector<llvm::Constant*, 8> Ctors;
4756bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
4760b2397132efe74ee11c1b371dd9033820c54240fChris Lattner    llvm::Constant *S[] = {
4770b2397132efe74ee11c1b371dd9033820c54240fChris Lattner      llvm::ConstantInt::get(Int32Ty, I->second, false),
4780b2397132efe74ee11c1b371dd9033820c54240fChris Lattner      llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
4790b2397132efe74ee11c1b371dd9033820c54240fChris Lattner    };
48008e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
4816bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
4826bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
4836bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
48496e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
4851c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson    new llvm::GlobalVariable(TheModule, AT, false,
486572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
4877db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(AT, Ctors),
4881c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             GlobalName);
4896d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
4906d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
4916d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
492d46f98573ba104eda102dd3224b2dca69f1c6336John McCallllvm::GlobalValue::LinkageTypes
493d46f98573ba104eda102dd3224b2dca69f1c6336John McCallCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
49490e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
4957c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
496f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_Internal)
497d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::InternalLinkage;
498f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
499f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<DLLExportAttr>())
500d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::DLLExportLinkage;
501f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
502f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (D->hasAttr<WeakAttr>())
503d46f98573ba104eda102dd3224b2dca69f1c6336John McCall    return llvm::Function::WeakAnyLinkage;
504f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
505f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C99 mode, 'inline' functions are guaranteed to have a strong
506f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition somewhere else, so we can use available_externally linkage.
507f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_C99Inline)
508fd0f89d3d7e4220327abdec1cb115474d70219dcFariborz Jahanian    return llvm::Function::AvailableExternallyLinkage;
5095584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
5105584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Note that Apple's kernel linker doesn't support symbol
5115584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // coalescing, so we need to avoid linkonce and weak linkages there.
5125584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // Normally, this means we just map to internal, but for explicit
5135584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall  // instantiations we'll map to external.
5145584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall
515f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // In C++, the compiler has to emit a definition in every translation unit
516f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // that references the function.  We should use linkonce_odr because
517f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // a) if all references in this translation unit are optimized away, we
518f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // don't need to codegen it.  b) if the function persists, it needs to be
519f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // merged with other definitions. c) C++ has the ODR, so we know the
520f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // definition is dependable.
521f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
5224e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    return !Context.getLangOpts().AppleKext
523142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::LinkOnceODRLinkage
524142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             : llvm::Function::InternalLinkage;
525f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
526f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // An explicit instantiation of a template has weak linkage, since
527f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // explicit instantiations can occur in multiple translation units
528f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // and must all be equivalent. However, we are not allowed to
529f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // throw away these explicit instantiations.
530f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  if (Linkage == GVA_ExplicitTemplateInstantiation)
5314e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    return !Context.getLangOpts().AppleKext
532142f9e99018a85105cee570133c111a52f2053ecFariborz Jahanian             ? llvm::Function::WeakODRLinkage
5335584d91c938384b57563edbca5c2d4f1c66ff02aJohn McCall             : llvm::Function::ExternalLinkage;
534f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner
535f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  // Otherwise, we have strong external linkage.
536f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  assert(Linkage == GVA_StrongExternal);
537f815306571385e2892e079a409f1b5b11f5e5cbbChris Lattner  return llvm::Function::ExternalLinkage;
538d46f98573ba104eda102dd3224b2dca69f1c6336John McCall}
539d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
540d46f98573ba104eda102dd3224b2dca69f1c6336John McCall
541d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// SetFunctionDefinitionAttributes - Set attributes for a global.
542d46f98573ba104eda102dd3224b2dca69f1c6336John McCall///
543d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// FIXME: This is currently only done for aliases and functions, but not for
544d46f98573ba104eda102dd3224b2dca69f1c6336John McCall/// variables (these details are set in EmitGlobalVarDefinition for variables).
545d46f98573ba104eda102dd3224b2dca69f1c6336John McCallvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
546d46f98573ba104eda102dd3224b2dca69f1c6336John McCall                                                    llvm::GlobalValue *GV) {
5477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GV);
548d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
549d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
5507dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
5511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                              const CGFunctionInfo &Info,
5527dbd8197040313d796282d4af06eccdf8a17319cDaniel Dunbar                                              llvm::Function *F) {
553ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  unsigned CallingConv;
554761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
55594236e7393d5cd4acbc5f0b503d23bbe78d9aeecBill Wendling  ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
556785b778203a474c6e4b9e17ae91cd2a358868877Bill Wendling  F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
557ca6408c3176783f0b29da4679a08512aa05f0c73Daniel Dunbar  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
558f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
559f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
560d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// Determines whether the language options require us to model
561d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// unwind exceptions.  We treat -fexceptions as mandating this
562d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// except under the fragile ObjC ABI with only ObjC exceptions
563d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enabled.  This means, for example, that C with -fexceptions
564d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall/// enables this.
5654e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikiestatic bool hasUnwindExceptions(const LangOptions &LangOpts) {
566d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If exceptions are completely disabled, obviously this is false.
5674e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!LangOpts.Exceptions) return false;
568d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
569d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If C++ exceptions are enabled, this is true.
5704e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CXXExceptions) return true;
571d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
572d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  // If ObjC exceptions are enabled, this depends on the ABI.
5734e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.ObjCExceptions) {
57411d3f4cc27e6b923fc32481dc1bb5ec46c7d1f4bDavid Chisnall    return LangOpts.ObjCRuntime.hasUnwindExceptions();
575d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  }
576d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
577d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall  return true;
578d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall}
579d1e40d5389a4382cbebc97d54792f41ee0414af4John McCall
5807c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbarvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
5817c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                                           llvm::Function *F) {
582abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola  if (CodeGenOpts.UnwindTables)
583abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola    F->setHasUWTable();
584abca5a1b3e74e644e297c7590b46ab73a6bb476aRafael Espindola
5854e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (!hasUnwindExceptions(LangOpts))
58672390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::NoUnwind);
587af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
5882873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  if (D->hasAttr<NakedAttr>()) {
5892873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman    // Naked implies noinline: we should not be inlining such functions.
59072390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::Naked);
59172390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::NoInline);
5922873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  }
593dd0cb22bd62e1e835327f478a2dbf0b8fa439713Daniel Dunbar
5941feade8e520be483293dbf55eb57a51720899589Mike Stump  if (D->hasAttr<NoInlineAttr>())
59572390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::NoInline);
596f55314dce992fd60816ba337ad151a2fb7c42239Mike Stump
5972873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman  // (noinline wins over always_inline, and we can't specify both in IR)
598adc6cbf5b502f1b58078455ab4fca66c7daac239Michael J. Spencer  if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
59901ad954459c9bdd21e55290859643e334e9c70f4Bill Wendling      !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
60001ad954459c9bdd21e55290859643e334e9c70f4Bill Wendling                                       llvm::Attribute::NoInline))
60172390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::AlwaysInline);
6022873aee1774a2ae731d6cc5c5ee05ba82780dc98Eli Friedman
603ee409a916e9b97ed6bc2f48d8d6aac6b8b773d7bBenjamin Kramer  // FIXME: Communicate hot and cold attributes to LLVM more directly.
604ee409a916e9b97ed6bc2f48d8d6aac6b8b773d7bBenjamin Kramer  if (D->hasAttr<ColdAttr>())
60572390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::OptimizeForSize);
606ee409a916e9b97ed6bc2f48d8d6aac6b8b773d7bBenjamin Kramer
607aee56faf90c04a75d9c432a92a8fdd2c875559a7Quentin Colombet  if (D->hasAttr<MinSizeAttr>())
60872390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::MinSize);
609aee56faf90c04a75d9c432a92a8fdd2c875559a7Quentin Colombet
610c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
611c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola    F->setUnnamedAddr(true);
612c5f657fe308f22243f674fc1dfbe24915944d8bfRafael Espindola
613ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
614ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith    if (MD->isVirtual())
615ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith      F->setUnnamedAddr(true);
616ef4d5ced04bf0b3d987e6b0e931f43125492f50cRichard Smith
6174e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
61872390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::StackProtect);
6194e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
62072390b39c545426023ec104afe8706395d732badBill Wendling    F->addFnAttr(llvm::Attribute::StackProtectReq);
6214f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz
6227e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov  // Add sanitizer attributes if function is not blacklisted.
6237e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov  if (!SanitizerBlacklist.isIn(*F)) {
6247e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    // When AddressSanitizer is enabled, set SanitizeAddress attribute
6257e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    // unless __attribute__((no_sanitize_address)) is used.
6267e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
6277e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov      F->addFnAttr(llvm::Attribute::SanitizeAddress);
6287e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
6297e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
6307e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov      F->addFnAttr(llvm::Attribute::SanitizeThread);
6317e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    }
6327e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
6337e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov    if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
6347e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov      F->addFnAttr(llvm::Attribute::SanitizeMemory);
6357e73f94c104070cf03c6f711a10f1928a550193fAlexey Samsonov  }
63689651eaf4170168cac2f34f2738e3d58fc38bbf1Alexander Potapenko
637cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
638cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt  if (alignment)
639cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt    F->setAlignment(alignment);
640cf807c4dfdb23e8fa3f400e0b24ef5b79db7a530Sean Hunt
641fb51ddfafcd5f8536d0312b3daa3c0b74b90ab5bMike Stump  // C++ ABI requires 2-byte alignment for member functions.
642bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
643bd6dbd19781cefd5b5ff9750c8bf86e6c341a68cMike Stump    F->setAlignment(2);
644f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
645f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
6461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::SetCommonAttributes(const Decl *D,
6477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar                                        llvm::GlobalValue *GV) {
648934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
649934176f27552141b5ad113cb3603ffb14906c570Anders Carlsson    setGlobalVisibility(GV, ND);
6501fb0caaa7bef765b85972274e3b434af2572c141John McCall  else
6511fb0caaa7bef765b85972274e3b434af2572c141John McCall    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
6527c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
65340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<UsedAttr>())
6547c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    AddUsedGlobal(GV);
6557c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
65640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
6577c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GV->setSection(SA->getName());
65882d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov
65982d0a418c8699fc6f4a9417457ffe93d43bba1c1Anton Korobeynikov  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
6607c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar}
6617c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
6620e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbarvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
6630e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  llvm::Function *F,
6640e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar                                                  const CGFunctionInfo &FI) {
6650e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributes(D, FI, F);
6660e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, F);
6677c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
6687c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  F->setLinkage(llvm::Function::InternalLinkage);
6697c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
6700e4f40e1bbc4dce16bbb9870300a435419f1b3d5Daniel Dunbar  SetCommonAttributes(D, F);
671f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
672f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
673b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlssonvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
674c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          llvm::Function *F,
675c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman                                          bool IsIncompleteFunction) {
6760ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  if (unsigned IID = F->getIntrinsicID()) {
6770ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // If this is an intrinsic function, set the function's attributes
6780ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    // to the intrinsic's attributes.
67950e6b18f99c45b31e6216ab221f6b3911b24fa1fBill Wendling    F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
68050e6b18f99c45b31e6216ab221f6b3911b24fa1fBill Wendling                                                    (llvm::Intrinsic::ID)IID));
6810ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne    return;
6820ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne  }
6830ac2cf4d28e1ed92508b27a3d9e28fc8db2a390bPeter Collingbourne
684b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
685b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson
686c6c14d1cd68afcd90d097715296377f15be45210Eli Friedman  if (!IsIncompleteFunction)
687de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
6881eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6897c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Only a few attributes are set on declarations; these may later be
6907c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // overridden by a definition.
6911eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
69240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (FD->hasAttr<DLLImportAttr>()) {
6937c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::DLLImportLinkage);
6941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (FD->hasAttr<WeakAttr>() ||
6950a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             FD->isWeakImported()) {
6967c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    // "extern_weak" is overloaded in LLVM; we probably should have
6971eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // separate linkage types for this.
6987c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setLinkage(llvm::Function::ExternalWeakLinkage);
6997c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  } else {
7001eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    F->setLinkage(llvm::Function::ExternalLinkage);
701af14603ca61757cf4361b583b45639a04c57e651John McCall
7022beda12c3fbaa9125831b7f818680978c596b205Rafael Espindola    LinkageInfo LV = FD->getLinkageAndVisibility();
703f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola    if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
704f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola      F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
705af14603ca61757cf4361b583b45639a04c57e651John McCall    }
7067c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
7077c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
70840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
7097c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    F->setSection(SA->getName());
710219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
711219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
7120269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
7131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  assert(!GV->isDeclaration() &&
7140269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
71535f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  LLVMUsed.push_back(GV);
7160269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
7170269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
7180269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
7190269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
720ad64e024bd18cf25dcfa44e049004371838decd8Chris Lattner  if (LLVMUsed.empty())
7210269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
7220269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
72335f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  // Convert LLVMUsed to what ConstantArray needs.
7240b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  SmallVector<llvm::Constant*, 8> UsedArray;
72535f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  UsedArray.resize(LLVMUsed.size());
72635f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
7271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    UsedArray[i] =
7281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
7290b2397132efe74ee11c1b371dd9033820c54240fChris Lattner                                    Int8PtrTy);
73035f38a2c22d68c22e2dbe8e9ee84c120c8f327bbChris Lattner  }
7311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
732c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian  if (UsedArray.empty())
733c38e9affd4519ea199af22419c8c794973cc4b23Fariborz Jahanian    return;
7340b2397132efe74ee11c1b371dd9033820c54240fChris Lattner  llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
7351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
7361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
7371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), ATy, false,
7380269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
7397db6d838aad4083fe86d7bf703a75fe6e8a17856Owen Anderson                             llvm::ConstantArray::get(ATy, UsedArray),
7401c431b323d776362490bbf7cc796b74fedaf19f2Owen Anderson                             "llvm.used");
7410269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
7420269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
7430269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
7440269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
745858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor/// \brief Add link options implied by the given module, including modules
746858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor/// it depends on, using a postorder walk.
747858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregorstatic void addLinkOptionsPostorder(llvm::LLVMContext &Context,
748858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor                                    Module *Mod,
749f9d03c15e8642d4bd3686b8c8e8269242a0f37c6Daniel Dunbar                                    SmallVectorImpl<llvm::Value *> &Metadata,
750858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor                                    llvm::SmallPtrSet<Module *, 16> &Visited) {
751858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Import this module's parent.
752858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  if (Mod->Parent && Visited.insert(Mod->Parent)) {
753858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
754858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  }
755858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
756858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Import this module's dependencies.
757858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  for (unsigned I = Mod->Imports.size(); I > 0; --I) {
758858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    if (Visited.insert(Mod->Imports[I-1]))
759858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
760858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  }
761858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
762858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Add linker options to link against the libraries/frameworks
763858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // described by this module.
764858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
765858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
766858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // We need to know more about the linker to know how to encode these
767858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // options propertly.
768858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
769858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // Link against a framework.
770858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    if (Mod->LinkLibraries[I-1].IsFramework) {
771858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      llvm::Value *Args[2] = {
772858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor        llvm::MDString::get(Context, "-framework"),
773858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor        llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
774858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      };
775858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
776858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      Metadata.push_back(llvm::MDNode::get(Context, Args));
777858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      continue;
778858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    }
779858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
780858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // Link against a library.
781858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    llvm::Value *OptString
782858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    = llvm::MDString::get(Context,
783858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor                          "-l" + Mod->LinkLibraries[I-1].Library);
784858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    Metadata.push_back(llvm::MDNode::get(Context, OptString));
785858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  }
786858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor}
787858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
788858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregorvoid CodeGenModule::EmitModuleLinkOptions() {
789858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Collect the set of all of the modules we want to visit to emit link
790858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // options, which is essentially the imported modules and all of their
791858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // non-explicit child modules.
792858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  llvm::SetVector<clang::Module *> LinkModules;
793858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  llvm::SmallPtrSet<clang::Module *, 16> Visited;
794858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  SmallVector<clang::Module *, 16> Stack;
795858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
796858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Seed the stack with imported modules.
797858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
798858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor                                               MEnd = ImportedModules.end();
799858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor       M != MEnd; ++M) {
800858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    if (Visited.insert(*M))
801858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      Stack.push_back(*M);
802858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  }
803858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
804858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Find all of the modules to import, making a little effort to prune
805858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // non-leaf modules.
806858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  while (!Stack.empty()) {
807858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    clang::Module *Mod = Stack.back();
808858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    Stack.pop_back();
809858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
810858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    bool AnyChildren = false;
811858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
812858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // Visit the submodules of this module.
813858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
814858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor                                        SubEnd = Mod->submodule_end();
815858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor         Sub != SubEnd; ++Sub) {
816858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      // Skip explicit children; they need to be explicitly imported to be
817858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      // linked against.
818858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      if ((*Sub)->IsExplicit)
819858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor        continue;
820858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
821858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      if (Visited.insert(*Sub)) {
822858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor        Stack.push_back(*Sub);
823858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor        AnyChildren = true;
824858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      }
825858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    }
826858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
827858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // We didn't find any children, so add this module to the list of
828858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    // modules to link against.
829858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    if (!AnyChildren) {
830858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      LinkModules.insert(Mod);
831858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    }
832858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  }
833858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
834858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // Add link options for all of the imported modules in reverse topological
835858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  // order.
836f9d03c15e8642d4bd3686b8c8e8269242a0f37c6Daniel Dunbar  SmallVector<llvm::Value *, 16> MetadataArgs;
837858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  Visited.clear();
838858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
839858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor                                               MEnd = LinkModules.end();
840858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor       M != MEnd; ++M) {
841858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    if (Visited.insert(*M))
842858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor      addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
843858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor  }
844f9d03c15e8642d4bd3686b8c8e8269242a0f37c6Daniel Dunbar  std::reverse(MetadataArgs.begin(), MetadataArgs.end());
845858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
846f9d03c15e8642d4bd3686b8c8e8269242a0f37c6Daniel Dunbar  // Add the linker options metadata flag.
847f9d03c15e8642d4bd3686b8c8e8269242a0f37c6Daniel Dunbar  getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
848f9d03c15e8642d4bd3686b8c8e8269242a0f37c6Daniel Dunbar                            llvm::MDNode::get(getLLVMContext(), MetadataArgs));
849858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor}
850858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor
8510269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
85267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Emit code for any potentially referenced deferred decls.  Since a
85367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // previously unused static decl may become used during the generation of code
854dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky  // for a static function, iterate until no changes are made.
855bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
856d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall  while (true) {
857046c294a43024874ff35656c6e785b64e72f1f36Anders Carlsson    if (!DeferredVTables.empty()) {
858d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall      EmitDeferredVTables();
859d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall
860d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall      // Emitting a v-table doesn't directly cause more v-tables to
861d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall      // become deferred, although it can cause functions to be
862d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall      // emitted that then need those v-tables.
863d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall      assert(DeferredVTables.empty());
864bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola    }
865bbf58bb1b8dd8c5e0f07547a6c20ffd55385fcf6Rafael Espindola
866d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall    // Stop if we're out of both deferred v-tables and deferred declarations.
867d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall    if (DeferredDeclsToEmit.empty()) break;
868d5617eeafc93209a26b9f88276c88cf997c3a0a7John McCall
8692a131fbca2a51085dc083b8c56a2d4ced3cf1413Anders Carlsson    GlobalDecl D = DeferredDeclsToEmit.back();
87067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.pop_back();
87167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner
872c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // Check to see if we've already emitted this.  This is necessary
873c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // for a couple of reasons: first, decls can end up in the
874c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // deferred-decls queue multiple times, and second, decls can end
875c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // up with definitions in unusual ways (e.g. by an extern inline
876c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // function acquiring a strong function redefinition).  Just
877c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // ignore these cases.
878c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    //
879c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // TODO: That said, looking this up multiple times is very wasteful.
8805f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = getMangledName(D);
881f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
88267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    assert(CGRef && "Deferred decl wasn't referenced?");
8831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
88467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    if (!CGRef->isDeclaration())
88567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner      continue;
8861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
887c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
888c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    // purposes an alias counts as a definition.
889c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall    if (isa<llvm::GlobalAlias>(CGRef))
890c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall      continue;
891c76702cc80c1ef8a94d82b62ddcb4ed4f67d5b8cJohn McCall
89267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Otherwise, emit the definition and move on to the next one.
89367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    EmitGlobalDefinition(D);
89467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
8955f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
8965f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
89777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::EmitGlobalAnnotations() {
89877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (Annotations.empty())
89977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return;
90077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
90177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Create a new global variable for the ConstantStruct in the Module.
90277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
90377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations[0]->getType(), Annotations.size()), Annotations);
90477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
90577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
90677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    "llvm.global.annotations");
90777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
90877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
90977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
910cfa88f893915ceb8ae4ce2f17c46c24a4d67502fDmitri Gribenkollvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
91177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
91277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (i != AnnotationStrings.end())
91377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return i->second;
91477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
91577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Not found yet, create a new global.
91694010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
91777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
91877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
91977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setSection(AnnotationSection);
92077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  gv->setUnnamedAddr(true);
92177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  AnnotationStrings[Str] = gv;
92277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return gv;
92377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
92477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
92577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
92677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
92777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
92877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (PLoc.isValid())
92977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    return EmitAnnotationString(PLoc.getFilename());
93077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return EmitAnnotationString(SM.getBufferName(Loc));
93177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
93277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
93377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougellvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
93477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  SourceManager &SM = getContext().getSourceManager();
93577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  PresumedLoc PLoc = SM.getPresumedLoc(L);
93677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
93777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    SM.getExpansionLineNumber(L);
93877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  return llvm::ConstantInt::get(Int32Ty, LineNo);
93977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
94077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
9411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
9428bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
94377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                                SourceLocation L) {
94477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the globals for file name, annotation, and the line number.
94577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
94677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *UnitGV = EmitAnnotationUnit(L),
94777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                 *LineNoCst = EmitAnnotationLineNo(L);
9488bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
94957d5cee133495bc21d1abdbce45ab05a79274a23Daniel Dunbar  // Create the ConstantStruct for the global annotation.
9508bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
95177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
95277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
95377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
95477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    LineNoCst
9558bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
956c5cbb909e8a27deb8f1a2b6b7bf56a96051af81aChris Lattner  return llvm::ConstantStruct::getAnon(Fields);
9578bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
9588bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
95977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerougevoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
96077f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge                                         llvm::GlobalValue *GV) {
96177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
96277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  // Get the struct elements for these annotations.
96377f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  for (specific_attr_iterator<AnnotateAttr>
96477f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ai = D->specific_attr_begin<AnnotateAttr>(),
96577f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
96677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
96777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge}
96877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
969a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidisbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
97090e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  // Never defer when EmitAllDecls is specified.
9714e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.EmitAllDecls)
972a6d6af308bfc9b72467b432a045a9fc6673e3821Argyrios Kyrtzidis    return false;
9730b6bc8bd7a1d2a7d7478d13d78cff94cacad61fcDouglas Gregor
9744ac7c0bb39696e92fd220118fedc484c09a69870Argyrios Kyrtzidis  return !getContext().DeclMustBeEmitted(Global);
97573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
97673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
977c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weberllvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
978c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    const CXXUuidofExpr* E) {
979c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Sema has verified that IIDSource has a __declspec(uuid()), and that its
980c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // well-formed.
981c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  StringRef Uuid;
982c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  if (E->isTypeOperand())
983c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
984c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  else {
985c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    // Special case: __uuidof(0) means an all-zero GUID.
986c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Expr *Op = E->getExprOperand();
987c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
988c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber      Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
989c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    else
990c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber      Uuid = "00000000-0000-0000-0000-000000000000";
991c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  }
992c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  std::string Name = "__uuid_" + Uuid.str();
993c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
994c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Look for an existing global.
995c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
996c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    return GV;
997c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
998c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
999c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  assert(Init && "failed to initialize as constant");
1000c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
1001c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
1002c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // first field is declared as "long", which for many targets is 8 bytes.
1003c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Those architectures are not supported. (With the MS abi, long is always 4
1004c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // bytes.)
1005c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::Type *GuidType = getTypes().ConvertType(E->getType());
1006c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  if (Init->getType() != GuidType) {
1007c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    DiagnosticsEngine &Diags = getDiags();
1008c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1009c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber        "__uuidof codegen is not supported on this architecture");
1010c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
1011c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    Init = llvm::UndefValue::get(GuidType);
1012c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  }
1013c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
1014c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
1015c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber      /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
1016c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  GV->setUnnamedAddr(true);
1017c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  return GV;
1018c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber}
1019c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
10206a836706c40a31c716952b74785102c90fd6afa7Rafael Espindolallvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
10216a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  const AliasAttr *AA = VD->getAttr<AliasAttr>();
10226a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  assert(AA && "No alias?");
10236a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10242acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
10256a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10266a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // See if there is already something with the target's name in the module.
1027f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
10284695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  if (Entry) {
10294695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger    unsigned AS = getContext().getTargetAddressSpace(VD->getType());
10304695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger    return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
10314695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  }
10326a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10336a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  llvm::Constant *Aliasee;
10346a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (isa<llvm::FunctionType>(DeclTy))
1035c857ce8b08397ed778928b8a000732ca90da2a8cAlex Rosenberg    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1036c857ce8b08397ed778928b8a000732ca90da2a8cAlex Rosenberg                                      GlobalDecl(cast<FunctionDecl>(VD)),
10371faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
10386a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  else
1039f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
10406a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola                                    llvm::PointerType::getUnqual(DeclTy), 0);
10414695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger
10424695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
10434695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  F->setLinkage(llvm::Function::ExternalWeakLinkage);
10444695f91f4302a90ae462cd64dda59b34c3dad821Joerg Sonnenberger  WeakRefReferences.insert(F);
10456a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
10466a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  return Aliasee;
10476a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola}
10486a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1049b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
10504a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
10511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
10526a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  // Weak references don't produce any output by themselves.
10536a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola  if (Global->hasAttr<WeakRefAttr>())
10546a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    return;
10556a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1056bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // If this is an alias definition (which otherwise looks like a declaration)
1057bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // emit it now.
105840b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (Global->hasAttr<AliasAttr>())
1059f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return EmitAliasDefinition(GD);
1060219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
1061d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  // If this is CUDA, be selective about which declarations we emit.
10624e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.CUDA) {
1063d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    if (CodeGenOpts.CUDAIsDevice) {
1064d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDADeviceAttr>() &&
1065d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAGlobalAttr>() &&
1066d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDAConstantAttr>() &&
1067d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne          !Global->hasAttr<CUDASharedAttr>())
1068d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
1069d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    } else {
1070d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne      if (!Global->hasAttr<CUDAHostAttr>() && (
1071d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDADeviceAttr>() ||
1072d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDAConstantAttr>() ||
1073d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne            Global->hasAttr<CUDASharedAttr>()))
1074d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne        return;
1075d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne    }
1076d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne  }
1077d51e43af0b3a6897b971f316c4de2035ec82d1f2Peter Collingbourne
107867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Ignore declarations, they will be emitted on their first use.
10795e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
108073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
1081dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    if (!FD->doesThisDeclarationHaveABody()) {
1082dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1083dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky        return;
1084dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
1085dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      const FunctionDecl *InlineDefinition = 0;
1086dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      FD->getBody(InlineDefinition);
1087dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky
10885f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner      StringRef MangledName = getMangledName(GD);
10897e42392eb2ea29ddeb6d125417fb4c17d847b5e0Benjamin Kramer      DeferredDecls.erase(MangledName);
1090dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky      EmitGlobalDefinition(InlineDefinition);
109173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
1092dce67a70a86db8758c926a76fdd980f5369d5746Nick Lewycky    }
10930269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
10940269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
1095bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1096bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1097a9a55c063e9e59c6ab0a6d7a21302660f7bde9f9Douglas Gregor    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
109873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
10994c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
11004c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
110167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // Defer code generation when possible if this is a static definition, inline
110267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // function etc.  These we only want to emit if they are used.
11034357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (!MayDeferGeneration(Global)) {
11044357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Emit the definition if it can't be deferred.
11054357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    EmitGlobalDefinition(GD);
1106bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
1107bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
1108bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
1109bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // If we're deferring emission of a C++ variable with an
1110bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  // initializer, remember the order in which it appeared in the file.
11114e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1112bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      cast<VarDecl>(Global)->hasInit()) {
1113bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1114bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    CXXGlobalInits.push_back(0);
1115bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall  }
11164357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
11174357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // If the value has already been used, add it directly to the
11184357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  // DeferredDeclsToEmit list.
11195f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
11204357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  if (GetGlobalValue(MangledName))
11214357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDeclsToEmit.push_back(GD);
11224357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  else {
11234357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // Otherwise, remember that we saw a deferred decl with this name.  The
11244357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // first use of the mangled name will cause it to move into
11254357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    // DeferredDeclsToEmit.
11264357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner    DeferredDecls[MangledName] = GD;
11274357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner  }
11284c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
11294c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
1130a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolanamespace {
1131a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  struct FunctionIsDirectlyRecursive :
1132a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1133a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    const StringRef Name;
1134bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    const Builtin::Context &BI;
1135a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool Result;
1136bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1137bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      Name(N), BI(C), Result(false) {
1138a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
1139a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1140a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1141a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    bool TraverseCallExpr(CallExpr *E) {
1142bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      const FunctionDecl *FD = E->getDirectCallee();
1143bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!FD)
1144a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
1145bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1146bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (Attr && Name == Attr->getLabel()) {
1147bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        Result = true;
1148bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola        return false;
1149bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      }
1150bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      unsigned BuiltinID = FD->getBuiltinID();
1151bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      if (!BuiltinID)
1152a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return true;
1153f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      StringRef BuiltinName = BI.GetName(BuiltinID);
1154f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky      if (BuiltinName.startswith("__builtin_") &&
1155f6b56374e4e5b9f0078efac5ed4918c3a04296f7Nick Lewycky          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1156a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        Result = true;
1157a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola        return false;
1158a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      }
1159a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola      return true;
1160a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    }
1161a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  };
1162a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
1163a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1164bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// isTriviallyRecursive - Check if this function calls another
1165bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// decl that, because of the asm attribute or the other decl being a builtin,
1166bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola// ends up pointing to itself.
1167a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
1168bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael EspindolaCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1169bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  StringRef Name;
1170bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
117122afaccd9ab77d46106e94c47907d955a014ae3fNick Lewycky    // asm labels are a special kind of mangling we have to support.
1172bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1173bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    if (!Attr)
1174bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola      return false;
1175bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = Attr->getLabel();
1176bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  } else {
1177bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola    Name = FD->getName();
1178bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  }
1179a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1180bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1181bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1182a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  return Walker.Result;
1183a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
1184a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1185a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindolabool
1186a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael EspindolaCodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1187a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1188a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return true;
1189cc4889f72ec68319969ba51e214d9940eb9327e5Rafael Espindola  if (CodeGenOpts.OptimizationLevel == 0 &&
1190adc6cbf5b502f1b58078455ab4fca66c7daac239Michael J. Spencer      !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1191a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    return false;
1192a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // PR9614. Avoid cases where the source code is lying to us. An available
1193a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // externally function should have an equivalent function somewhere else,
1194a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // but a function that calls itself is clearly not equivalent to the real
1195a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // implementation.
1196a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola  // This happens in glibc's btowc and in some configure checks.
1197bcf6b98247bd3ac76c5edf706b1087a8d32c0320Rafael Espindola  return !isTriviallyRecursive(F);
1198a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola}
1199a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola
1200b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
12014a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
12021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1203cb421fa690da545b58a720abe5f1c49b166dbde7Dan Gohman  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
12048e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 Context.getSourceManager(),
12058e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson                                 "Generating code for declaration");
12068e2efcc267ed12dc435782288b7f9a4a1bc56c72Anders Carlsson
120744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
120844eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // At -O0, don't generate IR for functions with available_externally
120944eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    // linkage.
1210a411d2f1ed4598a7a96a7befe07a9d9ee1a6efdeRafael Espindola    if (!shouldEmitFunction(Function))
121144eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      return;
121244eac33ae12df384f3f002102f919f603bee330fDouglas Gregor
121344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12147dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // Make sure to emit the definition(s) before we emit the thunks.
12157dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      // This is necessary for the generation of certain thunks.
12167dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
12177dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXConstructor(CD, GD.getCtorType());
12187dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
12197dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitCXXDestructor(DD, GD.getDtorType());
12207dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      else
12217dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman        EmitGlobalFunctionDefinition(GD);
12227dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman
122344eac33ae12df384f3f002102f919f603bee330fDouglas Gregor      if (Method->isVirtual())
122444eac33ae12df384f3f002102f919f603bee330fDouglas Gregor        getVTables().EmitThunks(GD);
12257270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson
12267dcdf5ba9324a9577461eae302e88fdd52e310c5Eli Friedman      return;
122744eac33ae12df384f3f002102f919f603bee330fDouglas Gregor    }
1228b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
1229b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalFunctionDefinition(GD);
123044eac33ae12df384f3f002102f919f603bee330fDouglas Gregor  }
1231b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner
1232b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1233b5e8156ebd6accd27daeaae6971597c45d5e5139Chris Lattner    return EmitGlobalVarDefinition(VD);
12344357a8291d759f6f9c36d3edeee8476d3eaf0804Chris Lattner
1235b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1236bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1237bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
123874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
123974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// module, create and return an llvm Function with the specified type. If there
124074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
124174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
124274391b48b4791cded373683a3baf67314f358d50Chris Lattner///
124374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
124474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the function when it is first created.
1245f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
12465f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
12472acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                       llvm::Type *Ty,
1248f85e193739c953358c865005855253af4f68a497John McCall                                       GlobalDecl D, bool ForVTable,
1249c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling                                       llvm::AttributeSet ExtraAttrs) {
12500558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Lookup the entry, lazily creating it if necessary.
1251f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
12520558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (Entry) {
1253d48bcb2f4dedf8e7b654cb017968b3d7b6663a57Benjamin Kramer    if (WeakRefReferences.erase(Entry)) {
12546a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
12556a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (FD && !FD->hasAttr<WeakAttr>())
12567270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
12576a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
12586a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
12590558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    if (Entry->getType()->getElementType() == Ty)
12600558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner      return Entry;
12611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
12620558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    // Make sure the result is of the correct type.
12639cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
12640558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
12651eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1266654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // This function doesn't have a complete type (for example, the return
1267654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // type is an incomplete struct). Use a fake type instead, and make
1268654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  // sure not to try to set attributes.
1269654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  bool IsIncompleteFunction = false;
1270784f21121a6c9418ebd86baa6814e36e1176c410John McCall
12712acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::FunctionType *FTy;
1272784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (isa<llvm::FunctionType>(Ty)) {
1273784f21121a6c9418ebd86baa6814e36e1176c410John McCall    FTy = cast<llvm::FunctionType>(Ty);
1274784f21121a6c9418ebd86baa6814e36e1176c410John McCall  } else {
12750774cb84719f2aea3016493a2bbd9a02aa3e0541John McCall    FTy = llvm::FunctionType::get(VoidTy, false);
1276654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman    IsIncompleteFunction = true;
1277654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  }
1278bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
1279784f21121a6c9418ebd86baa6814e36e1176c410John McCall  llvm::Function *F = llvm::Function::Create(FTy,
1280654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman                                             llvm::Function::ExternalLinkage,
1281f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                                             MangledName, &getModule());
1282f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  assert(F->getName() == MangledName && "name was uniqued!");
1283654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman  if (D.getDecl())
1284b2bcf1c176b200b36f371e189ce22f93c86cdf45Anders Carlsson    SetFunctionAttributes(D, F, IsIncompleteFunction);
1285c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling  if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1286c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling    llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1287909b6ded6be68a5740d98b478454fa55ea817ad6Bill Wendling    F->addAttributes(llvm::AttributeSet::FunctionIndex,
1288909b6ded6be68a5740d98b478454fa55ea817ad6Bill Wendling                     llvm::AttributeSet::get(VMContext,
1289909b6ded6be68a5740d98b478454fa55ea817ad6Bill Wendling                                             llvm::AttributeSet::FunctionIndex,
1290909b6ded6be68a5740d98b478454fa55ea817ad6Bill Wendling                                             B));
1291909b6ded6be68a5740d98b478454fa55ea817ad6Bill Wendling  }
1292654ad40f27d684e8f3eddbc990247a6dbea5ddedEli Friedman
129367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
129467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
129567b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1296f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
129767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
129867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
129967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
130067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
130167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
1302bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall
1303bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // Otherwise, there are cases we have to worry about where we're
1304bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // using a declaration for which we must emit a definition but where
1305bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // we might not find a top-level definition:
1306bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - member functions defined inline in their classes
1307bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - friend functions defined inline in some class
1308bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  //   - special member functions with implicit definitions
1309bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // If we ever change our AST traversal to walk into class methods,
1310bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall  // this will be unnecessary.
13111faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  //
13121faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // We also don't emit a definition for a function if it's going to be an entry
13131faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  // in a vtable, unless it's already marked as used.
13144e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1315bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    // Look for a declaration that's lexically in a record.
1316bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1317b135f0f2d893121ed2cc46d4d6c5bd5ab87d872fEli Friedman    FD = FD->getMostRecentDecl();
1318bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    do {
1319bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
13201faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson        if (FD->isImplicit() && !ForVTable) {
1321bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1322a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1323bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
132410620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt        } else if (FD->doesThisDeclarationHaveABody()) {
1325a29bf41b8f49578207ce36f6b21ff9bb7ee77babDouglas Gregor          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1326bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall          break;
1327bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall        }
13287b9a5aa7c0d76f577699d25ce6afe21ecccb60b7Rafael Espindola      }
1329ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor      FD = FD->getPreviousDecl();
1330bfdcdc8e26097c9dbb4c40d78296f6ccc3e6684cJohn McCall    } while (FD);
133167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
13321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1333784f21121a6c9418ebd86baa6814e36e1176c410John McCall  // Make sure the result is of the requested type.
1334784f21121a6c9418ebd86baa6814e36e1176c410John McCall  if (!IsIncompleteFunction) {
1335784f21121a6c9418ebd86baa6814e36e1176c410John McCall    assert(F->getType()->getElementType() == Ty);
1336784f21121a6c9418ebd86baa6814e36e1176c410John McCall    return F;
1337784f21121a6c9418ebd86baa6814e36e1176c410John McCall  }
1338784f21121a6c9418ebd86baa6814e36e1176c410John McCall
13399cbe4f0ba01ec304e1e3d071c071f7bca33631c0Chris Lattner  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1340784f21121a6c9418ebd86baa6814e36e1176c410John McCall  return llvm::ConstantExpr::getBitCast(F, PTy);
13410558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner}
13420558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
134374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfFunction - Return the address of the given function.  If Ty is
134474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// non-null, then this function will use the specified type if it has to
134574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create it (this occurs when we see a definition of the function).
1346b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
13472acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                 llvm::Type *Ty,
13481faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                                 bool ForVTable) {
134974391b48b4791cded373683a3baf67314f358d50Chris Lattner  // If there was no specific requested type, just convert it now.
135074391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (!Ty)
13514a6835e650ff24e19ce08a3bd347c0ad186777fdAnders Carlsson    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1352bcaedaed309ce453a992fdeef4a4c908cc7d9dfbChris Lattner
13535f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
13541faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
135574391b48b4791cded373683a3baf67314f358d50Chris Lattner}
135677ba708819285931932ecd33691a672bb59d221aEli Friedman
135774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeFunction - Create a new runtime function with the specified
135874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// type and name.
135974391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
13602acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
13615f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name,
1362c4c62fd78a4728c9e4d4df14911a2ced9bdd2031Bill Wendling                                     llvm::AttributeSet ExtraAttrs) {
1363bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  llvm::Constant *C
1364bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall    = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1365bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall                              ExtraAttrs);
1366bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1367bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall    if (F->empty())
1368bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall      F->setCallingConv(getRuntimeCC());
1369bd7370a78604e9a20d698bfe328c1e43f12a0613John McCall  return C;
137074391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1371bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1372a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// isTypeConstant - Determine whether an object of this type can be emitted
1373a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// as a constant.
1374a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith///
1375a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// If ExcludeCtor is true, the duration when the object's constructor runs
1376a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// will not be considered. The caller will need to verify that the object is
1377a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith/// not written to during its construction.
1378a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smithbool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1379a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
138020e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman    return false;
1381a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
13824e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Context.getLangOpts().CPlusPlus) {
1383a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    if (const CXXRecordDecl *Record
1384a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith          = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1385a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith      return ExcludeCtor && !Record->hasMutableFields() &&
1386a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith             Record->hasTrivialDestructor();
138720e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  }
1388a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
138920e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman  return true;
139020e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman}
139120e098b7e7fda6bed1d67441b56cce77cd3aa918Eli Friedman
139274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
139374391b48b4791cded373683a3baf67314f358d50Chris Lattner/// create and return an llvm GlobalVariable with the specified type.  If there
139474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// is something in the module with the specified name, return it potentially
139574391b48b4791cded373683a3baf67314f358d50Chris Lattner/// bitcasted to the right type.
139674391b48b4791cded373683a3baf67314f358d50Chris Lattner///
139774391b48b4791cded373683a3baf67314f358d50Chris Lattner/// If D is non-null, it specifies a decl that correspond to this.  This is used
139874391b48b4791cded373683a3baf67314f358d50Chris Lattner/// to set the attributes on the global when it is first created.
1399f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallllvm::Constant *
14005f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
14012acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                     llvm::PointerType *Ty,
1402c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     const VarDecl *D,
1403c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                                     bool UnnamedAddr) {
14043c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
1405f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
140699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
1407d48bcb2f4dedf8e7b654cb017968b3d7b6663a57Benjamin Kramer    if (WeakRefReferences.erase(Entry)) {
14086a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola      if (D && !D->hasAttr<WeakAttr>())
14097270ee4cd4794281c09dfb6931a98bbb2581ef02Anders Carlsson        Entry->setLinkage(llvm::Function::ExternalLinkage);
14106a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola    }
14116a836706c40a31c716952b74785102c90fd6afa7Rafael Espindola
1412c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola    if (UnnamedAddr)
1413c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola      Entry->setUnnamedAddr(true);
1414c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola
141574391b48b4791cded373683a3baf67314f358d50Chris Lattner    if (Entry->getType() == Ty)
1416570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      return Entry;
14171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
141899b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
14193c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    return llvm::ConstantExpr::getBitCast(Entry, Ty);
142099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
14211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
142267b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // This is the first use or definition of a mangled name.  If there is a
142367b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // deferred decl with this name, remember that we need to emit it at the end
142467b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  // of the file.
1425f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
142667b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  if (DDI != DeferredDecls.end()) {
142767b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
142867b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    // list, and remove it from DeferredDecls (since we don't need it anymore).
142967b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDeclsToEmit.push_back(DDI->second);
143067b00520c8f5b48fad722b790d87fea6be764efeChris Lattner    DeferredDecls.erase(DDI);
143167b00520c8f5b48fad722b790d87fea6be764efeChris Lattner  }
14321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14334dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
14341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
14351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
143699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
1437f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall                             0, MangledName, 0,
14385e2d5dec7736f6f9292d4212dec67295909f1328Hans Wennborg                             llvm::GlobalVariable::NotThreadLocal, AddrSpace);
143949988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
144099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
144174391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (D) {
1442f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // FIXME: This code is overly simple and should be merged with other global
1443f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // handling.
1444a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    GV->setConstant(isTypeConstant(D->getType(), false));
144549988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
1446110e8e56af30363072c140285961592b0107f789John McCall    // Set linkage and visibility in case we never see a definition.
14472beda12c3fbaa9125831b7f818680978c596b205Rafael Espindola    LinkageInfo LV = D->getLinkageAndVisibility();
1448f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola    if (LV.getLinkage() != ExternalLinkage) {
144915e310a3b970b64a84cb30f0005bc396b4d978cbJohn McCall      // Don't set internal linkage on declarations.
1450110e8e56af30363072c140285961592b0107f789John McCall    } else {
1451110e8e56af30363072c140285961592b0107f789John McCall      if (D->hasAttr<DLLImportAttr>())
1452110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
14530a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1454110e8e56af30363072c140285961592b0107f789John McCall        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1455110e8e56af30363072c140285961592b0107f789John McCall
1456af14603ca61757cf4361b583b45639a04c57e651John McCall      // Set visibility on a declaration only if it's explicit.
1457f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola      if (LV.isVisibilityExplicit())
1458f127eb8aeb3ce861f3dbc1adbb3362bfd98461e1Rafael Espindola        GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1459110e8e56af30363072c140285961592b0107f789John McCall    }
146056ebe5082da7411fb37479e230b52735f77cff35Eli Friedman
1461de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    if (D->isThreadSpecified())
1462de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg      setTLSMode(GV, *D);
146374391b48b4791cded373683a3baf67314f358d50Chris Lattner  }
14641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14654dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  if (AddrSpace != Ty->getAddressSpace())
14664dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    return llvm::ConstantExpr::getBitCast(GV, Ty);
14674dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  else
14684dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    return GV;
146974391b48b4791cded373683a3baf67314f358d50Chris Lattner}
1470eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
1471eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
14723bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlssonllvm::GlobalVariable *
14735f9e272e632e951b1efe824cd16acb4d96077930Chris LattnerCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
14742acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                      llvm::Type *Ty,
14753bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
14763bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
14773bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  llvm::GlobalVariable *OldGV = 0;
14783bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
14793bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
14803bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (GV) {
14813bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Check if the variable has the right type.
14823bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (GV->getType()->getElementType() == Ty)
14833bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      return GV;
14843bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
14853bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Because C++ name mangling, the only way we can end up with an already
14863bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // existing global with the same name is if it has been declared extern "C".
1487c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    assert(GV->isDeclaration() && "Declaration has wrong type!");
14883bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV = GV;
14893bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
14903bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
14913bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  // Create a new variable.
14923bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
14933bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson                                Linkage, 0, Name);
14943bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
14953bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  if (OldGV) {
14963bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    // Replace occurrences of the old variable if needed.
14973bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    GV->takeName(OldGV);
14983bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
14993bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    if (!OldGV->use_empty()) {
15003bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::Constant *NewPtrForOldDecl =
15013bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
15023bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
15033bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    }
15043bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
15053bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson    OldGV->eraseFromParent();
15063bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  }
15073bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
15083bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson  return GV;
15093bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson}
15103bd6202ea2d5b5f7c8229cd280a846ae3dcf2355Anders Carlsson
151174391b48b4791cded373683a3baf67314f358d50Chris Lattner/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
151274391b48b4791cded373683a3baf67314f358d50Chris Lattner/// given global variable.  If Ty is non-null and if the global doesn't exist,
15130ff258b933fe385425bf2a85429bf46376d338f1Eric Christopher/// then it will be created with the specified type instead of whatever the
151474391b48b4791cded373683a3baf67314f358d50Chris Lattner/// normal requested type would be.
151574391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
15162acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner                                                  llvm::Type *Ty) {
151774391b48b4791cded373683a3baf67314f358d50Chris Lattner  assert(D->hasGlobalStorage() && "Not a global variable");
151874391b48b4791cded373683a3baf67314f358d50Chris Lattner  QualType ASTTy = D->getType();
151974391b48b4791cded373683a3baf67314f358d50Chris Lattner  if (Ty == 0)
152074391b48b4791cded373683a3baf67314f358d50Chris Lattner    Ty = getTypes().ConvertTypeForMem(ASTTy);
15211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15222acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::PointerType *PTy =
1523207f4d8543529221932af82836016a2ef066c917Peter Collingbourne    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1524f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
15255f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(D);
1526f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
152774391b48b4791cded373683a3baf67314f358d50Chris Lattner}
15283f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
152974391b48b4791cded373683a3baf67314f358d50Chris Lattner/// CreateRuntimeVariable - Create a new runtime global variable with the
153074391b48b4791cded373683a3baf67314f358d50Chris Lattner/// specified type and name.
153174391b48b4791cded373683a3baf67314f358d50Chris Lattnerllvm::Constant *
15322acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
15335f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                                     StringRef Name) {
15341de4d4e8cb2e9c88809fea8092bc6e835a5473d2John McCall  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1535c532b502858032f377056dc8cba2fe43cba8702bRafael Espindola                               true);
1536bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
1537bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
153803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbarvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
153903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  assert(!D->getInit() && "Cannot emit definite definitions here!");
154003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
15417520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  if (MayDeferGeneration(D)) {
15427520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // If we have not seen a reference to this variable yet, place it
15437520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // into the deferred declarations table to be emitted if needed
15447520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    // later.
15455f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef MangledName = getMangledName(D);
1546f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    if (!GetGlobalValue(MangledName)) {
1547555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson      DeferredDecls[MangledName] = D;
154803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar      return;
15497520bd1de12af10ea08c662440565adbdf589317Douglas Gregor    }
15507520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  }
15517520bd1de12af10ea08c662440565adbdf589317Douglas Gregor
15527520bd1de12af10ea08c662440565adbdf589317Douglas Gregor  // The tentative definition is the only definition.
155303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar  EmitGlobalVarDefinition(D);
155403f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar}
155503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar
15562acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris LattnerCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
155706f486ecd05bd6788da97c39164c1903a084c26dKen Dyck    return Context.toCharUnitsFromBits(
155825a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow      TheDataLayout.getTypeStoreSizeInBits(Ty));
1559687cc4a850b59116efee061018f0d8df50728b82Ken Dyck}
1560687cc4a850b59116efee061018f0d8df50728b82Ken Dyck
156119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redlllvm::Constant *
156219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian RedlCodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
156319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                       const Expr *rawInit) {
156419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
156519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (const ExprWithCleanups *withCleanups =
156619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl          dyn_cast<ExprWithCleanups>(rawInit)) {
156719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    cleanups = withCleanups->getObjects();
156819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    rawInit = withCleanups->getSubExpr();
156919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
157019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
157119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
157219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!init || !init->initializesStdInitializerList() ||
157319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl      init->getNumInits() == 0)
157419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
157519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
157619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ASTContext &ctx = getContext();
157719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  unsigned numInits = init->getNumInits();
1578062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // FIXME: This check is here because we would otherwise silently miscompile
1579062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // nested global std::initializer_lists. Better would be to have a real
1580062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // implementation.
1581062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  for (unsigned i = 0; i < numInits; ++i) {
1582062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1583062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    if (inner && inner->initializesStdInitializerList()) {
1584062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl      ErrorUnsupported(inner, "nested global std::initializer_list");
1585062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl      return 0;
1586062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl    }
1587062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  }
1588062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl
1589062a82cdfab01d95f7fa3d759342e6f2ee5c51b0Sebastian Redl  // Synthesize a fake VarDecl for the array and initialize that.
159019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType elementType = init->getInit(0)->getType();
159119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
159219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
159319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                ArrayType::Normal, 0);
159419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
159519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
159619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
159719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                              arrayType, D->getLocation());
159819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
159919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                                          D->getDeclContext()),
160019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          D->getLocStart(), D->getLocation(),
160119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          name, arrayType, sourceInfo,
160219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                                          SC_Static, SC_Static);
160319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
160419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Now clone the InitListExpr to initialize the array instead.
160519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Incredible hack: we want to use the existing InitListExpr here, so we need
160619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // to tell it that it no longer initializes a std::initializer_list.
16073b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer  ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
16083b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer                        init->getNumInits());
16093b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer  Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
16103b6bef9a213249c6ab6d67c07b1ac6380961be3eBenjamin Kramer                                           init->getRBraceLoc());
161119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  arrayInit->setType(arrayType);
161219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
161319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!cleanups.empty())
161419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
161519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
161619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  backingArray->setInit(arrayInit);
161719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
161819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Emit the definition of the array.
161919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  EmitGlobalVarDefinition(backingArray);
162019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
162119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Inspect the initializer list to validate it and determine its type.
162219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // FIXME: doing this every time is probably inefficient; caching would be nice
162319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
162419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  RecordDecl::field_iterator field = record->field_begin();
162519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (field == record->field_end()) {
162619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
162719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
162819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
162919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  QualType elementPtr = ctx.getPointerType(elementType.withConst());
163019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Start pointer.
163119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (!ctx.hasSameType(field->getType(), elementPtr)) {
163219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
163319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
163419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
163519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  ++field;
163619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (field == record->field_end()) {
163719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
163819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
163919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
164019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  bool isStartEnd = false;
164119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (ctx.hasSameType(field->getType(), elementPtr)) {
164219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // End pointer.
164319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    isStartEnd = true;
164419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
164519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    ErrorUnsupported(D, "weird std::initializer_list");
164619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    return 0;
164719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
164819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
164919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Now build an APValue representing the std::initializer_list.
165019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue initListValue(APValue::UninitStruct(), 0, 2);
165119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue &startField = initListValue.getStructField(0);
165219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  APValue::LValuePathEntry startOffsetPathEntry;
165319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  startOffsetPathEntry.ArrayIndex = 0;
165419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  startField = APValue(APValue::LValueBase(backingArray),
165519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       CharUnits::fromQuantity(0),
165619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       llvm::makeArrayRef(startOffsetPathEntry),
165719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       /*IsOnePastTheEnd=*/false, 0);
165819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
165919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  if (isStartEnd) {
166019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue &endField = initListValue.getStructField(1);
166119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue::LValuePathEntry endOffsetPathEntry;
166219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    endOffsetPathEntry.ArrayIndex = numInits;
166319b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    endField = APValue(APValue::LValueBase(backingArray),
166419b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       ctx.getTypeSizeInChars(elementType) * numInits,
166519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       llvm::makeArrayRef(endOffsetPathEntry),
166619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl                       /*IsOnePastTheEnd=*/true, 0);
166719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  } else {
166819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    APValue &sizeField = initListValue.getStructField(1);
166919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    sizeField = APValue(llvm::APSInt(numElements));
167019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  }
167119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
167219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  // Emit the constant for the initializer_list.
1673a3ca41f0c2bd1c4a752df88b283332f3b757d21eRichard Smith  llvm::Constant *llvmInit =
1674a3ca41f0c2bd1c4a752df88b283332f3b757d21eRichard Smith      EmitConstantValueForMemory(initListValue, D->getType());
167519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  assert(llvmInit && "failed to initialize as constant");
167619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl  return llvmInit;
167719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl}
167819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
16794dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourneunsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
16804dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne                                                 unsigned AddrSpace) {
16814dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
16824dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    if (D->hasAttr<CUDAConstantAttr>())
16834dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
16844dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    else if (D->hasAttr<CUDASharedAttr>())
16854dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
16864dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne    else
16874dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
16884dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  }
16894dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne
16904dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne  return AddrSpace;
16914dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne}
16924dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne
1693bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
16948f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
169577ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
16967ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
16977ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  bool NeedsGlobalCtor = false;
16987ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
16991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17002d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const VarDecl *InitDecl;
17012d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
170219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
17033bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson  if (!InitExpr) {
1704cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
170503f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // implicitly initialized with { 0 }.
170603f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    //
170703f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // Note that tentative definitions are only emitted at the end of
170803f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // a translation unit, so they should never have incomplete
170903f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // type. In addition, EmitTentativeDefinition makes sure that we
171003f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // never attempt to emit a tentative definition if a real one
171103f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // exists. A use may still exists, however, so we still may need
171203f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    // to do a RAUW.
171303f5ad9a7707e098f601921fcec17ed65eb355a7Daniel Dunbar    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1714b0d0ea042116c1f451d3db8ceff9f1dd92bc36d2Anders Carlsson    Init = EmitNullConstant(D->getType());
171577ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
171619b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // If this is a std::initializer_list, emit the special initializer.
171719b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
171819b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // An empty init list will perform zero-initialization, which happens
171919b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // to be exactly what we want.
172019b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // FIXME: It does so in a global constructor, which is *not* what we
172119b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl    // want.
172219b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl
17234904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    if (!Init) {
17244904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian      initializedGlobalDecl = GlobalDecl(D);
172519b1a6eb2c90fab7cefe74bea5b6de490b65ac9dSebastian Redl      Init = EmitConstantInit(*InitDecl);
17264904bf4e84cfb48080270ebaa9005327f18ab0e5Fariborz Jahanian    }
17276e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
17283bb92693c3332c1e99870a4e45afff3892e1c6aeAnders Carlsson      QualType T = InitExpr->getType();
1729c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor      if (D->getType()->isReferenceType())
1730c446d1816f46a4b6d2337102dfc001f55fc18211Douglas Gregor        T = D->getType();
17312d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith
17324e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus) {
173389ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = EmitNullConstant(T);
17347ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith        NeedsGlobalCtor = true;
173589ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      } else {
173689ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        ErrorUnsupported(D, "static initializer");
173789ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
173889ed31d3f9eeb8ec77c284a5cf404a74bf5e7acfAnders Carlsson      }
1739bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall    } else {
1740bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall      // We don't need an initializer, so remove the entry for the delayed
17417ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith      // initializer position (just in case this entry was delayed) if we
17427ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith      // also don't need to register a destructor.
17434e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie      if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1744bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall        DelayedCXXInitPosition.erase(D);
17456e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
17468f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
17478e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
17482acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type* InitType = Init->getType();
1749570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
17501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1751570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Strip off a bitcast if we got one back.
1752570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
17539d4a15fd3b85434c43ea27562793de63a793321aChris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
17549d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           // all zero index gep.
17559d4a15fd3b85434c43ea27562793de63a793321aChris Lattner           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1756570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry = CE->getOperand(0);
1757570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  }
17581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1759570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // Entry is now either a Function or GlobalVariable.
1760570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
17611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1762570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We have a definition after a declaration with the wrong type.
1763570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // We must make a new GlobalVariable* and update everything that used OldGV
1764570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (a declaration or tentative definition) with the new GlobalVariable*
1765570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // (which will be a definition).
1766570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  //
1767570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // This happens if there is a prototype for a global (e.g.
1768570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "extern int x[];") and then a definition of a different type (e.g.
1769570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // "int x[10];"). This also happens when an initializer has a different type
1770570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  // from the type of the global (this happens with unions).
1771570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner  if (GV == 0 ||
1772570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner      GV->getType()->getElementType() != InitType ||
1773207f4d8543529221932af82836016a2ef066c917Peter Collingbourne      GV->getType()->getAddressSpace() !=
17744dc34ebf2a0716bf77ba110dab6777a3fc4397ddPeter Collingbourne       GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
17751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1776f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // Move the old entry aside so that we'll create a new one.
17775f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    Entry->setName(StringRef());
1778232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
1779570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    // Make a new global with the correct type, this is now guaranteed to work.
1780570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
17810558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner
178277ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
17831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *NewPtrForOldDecl =
17843c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1785570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
178677ba708819285931932ecd33691a672bb59d221aEli Friedman
178777ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
1788570585c91dee98d7ba8ccf1198c03208ba17966bChris Lattner    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
178977ba708819285931932ecd33691a672bb59d221aEli Friedman  }
179077ba708819285931932ecd33691a672bb59d221aEli Friedman
179177f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
179277f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, GV);
17938bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
179488a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
1795e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner
1796e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  // If it is safe to mark the global 'constant', do so now.
1797a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1798a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith                  isTypeConstant(D->getType(), true));
17991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
18008b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1801a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith
180288a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
1803354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage =
1804354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GetLLVMLinkageVarDefinition(D, GV);
1805354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  GV->setLinkage(Linkage);
1806354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1807354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    // common vars aren't constant even if declared const.
1808354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    GV->setConstant(false);
1809354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1810354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  SetCommonAttributes(D, GV);
1811354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
18123030eb82593097502469a8b3fc26112c79c75605John McCall  // Emit the initializer function if necessary.
18137ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  if (NeedsGlobalCtor || NeedsGlobalDtor)
18147ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
18153030eb82593097502469a8b3fc26112c79c75605John McCall
181605c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  // If we are compiling with ASan, add metadata indicating dynamically
181705c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  // initialized globals.
18184f45bc099f2665bc6e4bcbb169aa452390dbf3feWill Dietz  if (SanOpts.Address && NeedsGlobalCtor) {
181905c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::Module &M = getModule();
182005c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany
182105c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::NamedMDNode *DynamicInitializers =
182205c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany        M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
182305c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::Value *GlobalToAdd[] = { GV };
182405c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
182505c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany    DynamicInitializers->addOperand(ThisGlobal);
182605c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany  }
182705c5ebc9bafe5613204eefb59a47ab878e4fbd0bKostya Serebryany
1828354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  // Emit global variable debug information.
182973fb35003aad027492e661a3749e921b5d1ecaf9Eric Christopher  if (CGDebugInfo *DI = getModuleDebugInfo())
18304cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor    if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1831fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov      DI->EmitGlobalVariable(GV, D);
1832354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian}
1833354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian
1834354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanianllvm::GlobalValue::LinkageTypes
1835354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz JahanianCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1836354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian                                           llvm::GlobalVariable *GV) {
183790e99a84ddd020e8fda79643748243725a2ed071Argyrios Kyrtzidis  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1838a0f00a71fcb0f98298709d5e5318339acf7958acDouglas Gregor  if (Linkage == GVA_Internal)
1839354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::InternalLinkage;
184040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLImportAttr>())
1841354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLImportLinkage;
184240b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  else if (D->hasAttr<DLLExportAttr>())
1843354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::Function::DLLExportLinkage;
1844e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner  else if (D->hasAttr<WeakAttr>()) {
1845e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    if (GV->isConstant())
1846354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakODRLinkage;
1847e78b86f3201ae5f09e2cf85bd6558f1d9b34de26Chris Lattner    else
1848354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian      return llvm::GlobalVariable::WeakAnyLinkage;
18498f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor  } else if (Linkage == GVA_TemplateInstantiation ||
18508f51a4f2d00b0abda3cde7f3828fb2e2b9beafb5Douglas Gregor             Linkage == GVA_ExplicitTemplateInstantiation)
185199ace16bc6962f1fc3dc45bbbdf2eb74e555a8adJohn McCall    return llvm::GlobalVariable::WeakODRLinkage;
18524e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  else if (!getLangOpts().CPlusPlus &&
1853a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1854a6cf1e709b96865210b81bd611d41e9a2d41500aEric Christopher             D->getAttr<CommonAttr>()) &&
1855309457d0f1b416c1b379c9f3e172848adffedb23Chris Lattner           !D->hasExternalStorage() && !D->getInit() &&
1856ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1857ab27d6ea7b4ce2762a16905281de796db32bb6f2Fariborz Jahanian           !D->getAttr<WeakImportAttr>()) {
185891f31dc234bbc98f3dd20e6741a7b0b98c7916bfEric Christopher    // Thread local vars aren't considered common linkage.
1859354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian    return llvm::GlobalVariable::CommonLinkage;
1860686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
1861354e712c81fbb07c0ce5f06180788b25fffa1b56Fariborz Jahanian  return llvm::GlobalVariable::ExternalLinkage;
186288a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
18635f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1864a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// Replace the uses of a function that was declared with a non-proto type.
1865a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// We want to silently drop extra arguments from call sites
1866a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCallstatic void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1867a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                          llvm::Function *newFn) {
1868a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  // Fast path.
1869a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  if (old->use_empty()) return;
1870a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1871a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  llvm::Type *newRetTy = newFn->getReturnType();
1872a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  SmallVector<llvm::Value*, 4> newArgs;
1873a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1874a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1875a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall         ui != ue; ) {
1876a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1877a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    llvm::User *user = *use;
1878a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1879a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // Recognize and replace uses of bitcasts.  Most calls to
1880a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // unprototyped functions will use bitcasts.
1881a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1882a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1883a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall        replaceUsesOfNonProtoConstant(bitcast, newFn);
1884bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
1885a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    }
1886a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1887a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // Recognize calls to the function.
1888a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    llvm::CallSite callSite(user);
1889a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (!callSite) continue;
1890a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (!callSite.isCallee(use)) continue;
1891bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1892a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // If the return types don't match exactly, then we can't
1893a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // transform this call unless it's dead.
1894a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (callSite->getType() != newRetTy && !callSite->use_empty())
1895a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      continue;
1896a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1897a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // Get the call site's attribute list.
1898b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling    SmallVector<llvm::AttributeSet, 8> newAttrs;
1899a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    llvm::AttributeSet oldAttrs = callSite.getAttributes();
1900a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1901a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // Collect any return attributes from the call.
1902a37ce617af7300eee3ceab435021c342e62c5661Bill Wendling    if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1903ed01f84d20a1586b2d639b47463cf1f22418f0f6Bill Wendling      newAttrs.push_back(
1904b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling        llvm::AttributeSet::get(newFn->getContext(),
1905b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling                                oldAttrs.getRetAttributes()));
1906a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1907a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // If the function was passed too few arguments, don't transform.
1908a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    unsigned newNumArgs = newFn->arg_size();
1909a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (callSite.arg_size() < newNumArgs) continue;
1910a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1911a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // If extra arguments were passed, we silently drop them.
1912a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // If any of the types mismatch, we don't transform.
1913a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    unsigned argNo = 0;
1914a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    bool dontTransform = false;
1915a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1916a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall           ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1917a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1918a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall        dontTransform = true;
1919bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner        break;
1920bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      }
192140f9c302f23a35611cd354f40b22b37f2c554a40John McCall
192240f9c302f23a35611cd354f40b22b37f2c554a40John McCall      // Add any parameter attributes.
192389530e45729d300b39c7332d2ad20c3ea476ab94Bill Wendling      if (oldAttrs.hasAttributes(argNo + 1))
192489530e45729d300b39c7332d2ad20c3ea476ab94Bill Wendling        newAttrs.
1925b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling          push_back(llvm::
1926b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling                    AttributeSet::get(newFn->getContext(),
1927b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling                                      oldAttrs.getParamAttributes(argNo + 1)));
1928bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
1929a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (dontTransform)
1930bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      continue;
19311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1932e67e4c93dfc9d68bff094c61b588f87456917f6fBill Wendling    if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1933b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling      newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1934b263bdf2954953cc7cca5d667eb01319ea0f72ecBill Wendling                                                 oldAttrs.getFnAttributes()));
193540f9c302f23a35611cd354f40b22b37f2c554a40John McCall
1936bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Okay, we can transform this.  Create the new call instruction and copy
1937bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // over the required information.
1938a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1939a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1940a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    llvm::CallSite newCall;
1941a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (callSite.isCall()) {
1942a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      newCall = llvm::CallInst::Create(newFn, newArgs, "",
1943a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                       callSite.getInstruction());
1944a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    } else {
1945a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      llvm::InvokeInst *oldInvoke =
1946a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall        cast<llvm::InvokeInst>(callSite.getInstruction());
1947a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      newCall = llvm::InvokeInst::Create(newFn,
1948a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                         oldInvoke->getNormalDest(),
1949a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                         oldInvoke->getUnwindDest(),
1950a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                         newArgs, "",
1951a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                         callSite.getInstruction());
1952a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    }
1953a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    newArgs.clear(); // for the next iteration
1954a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1955a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (!newCall->getType()->isVoidTy())
1956a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      newCall->takeName(callSite.getInstruction());
1957a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    newCall.setAttributes(
1958a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                     llvm::AttributeSet::get(newFn->getContext(), newAttrs));
1959a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    newCall.setCallingConv(callSite.getCallingConv());
1960bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1961bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    // Finally, remove the old call, replacing any uses with the new one.
1962a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (!callSite->use_empty())
1963a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      callSite->replaceAllUsesWith(newCall.getInstruction());
19643b122bc5f1203615e2128e0c1a63da438865b1ccDevang Patel
1965c60346388d60b1756f3675dabb60dc58da0728ecChris Lattner    // Copy debug location attached to CI.
1966a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (!callSite->getDebugLoc().isUnknown())
1967a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall      newCall->setDebugLoc(callSite->getDebugLoc());
1968a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    callSite->eraseFromParent();
1969bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner  }
1970bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner}
1971bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner
1972a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1973a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1974a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// existing call uses of the old function in the module, this adjusts them to
1975a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// call the new function directly.
1976a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall///
1977a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// This is not just a cleanup: the always_inline pass requires direct calls to
1978a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// functions to be able to inline them.  If there is a bitcast in the way, it
1979a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1980a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall/// run at -O0.
1981a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCallstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1982a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall                                                      llvm::Function *NewFn) {
1983a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  // If we're redefining a global as a function, don't transform it.
1984a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  if (!isa<llvm::Function>(Old)) return;
1985a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1986a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall  replaceUsesOfNonProtoConstant(Old, NewFn);
1987a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall}
1988a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall
1989025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindolavoid CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1990025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1991025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  // If we have a definition, this might be a deferred decl. If the
1992025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  // instantiation is explicit, make sure we emit it at the end.
1993025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola  if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1994025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola    GetAddrOfGlobalVar(VD);
1995afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis
1996afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis  EmitTopLevelDecl(VD);
1997234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola}
1998bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
1999b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattnervoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2000b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2001d26bc76c98006609002d9930f8840490e88ac5b5John McCall
20021f6f961293da9c2b1c23da2411c1b439a9502ed0John McCall  // Compute the function info and LLVM type.
2003de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2004de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2005d26bc76c98006609002d9930f8840490e88ac5b5John McCall
20069fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner  // Get or create the prototype for the function.
2007b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
20081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20090558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  // Strip off a bitcast if we got one back.
20100558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
20110558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    assert(CE->getOpcode() == llvm::Instruction::BitCast);
20120558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = CE->getOperand(0);
20130558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  }
20141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20160558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2017bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
20181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
201942745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
2020bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    assert(OldFn->isDeclaration() &&
20210558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner           "Shouldn't replace non-declaration");
202234809507232bc4c3c4840c7d092c7440219fddafChris Lattner
202362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
202462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
202562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
202662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
202762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
202862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
2029f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // (e.g. "int f(int x)").  Move the old function aside so that it
2030f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    // doesn't interfere with GetAddrOfFunction.
20315f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    OldFn->setName(StringRef());
2032b4880bab7fc1b61267cfd9a0ad52188e7a828cb3Chris Lattner    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
20331eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2034a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // This might be an implementation of a function without a
2035a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // prototype, in which case, try to do special replacement of
2036a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // calls which match the new prototype.  The really key thing here
2037a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // is that we also potentially drop arguments from the call site
2038a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // so as to make a direct call, which makes the inliner happier
2039a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // and suppresses a number of optimizer warnings (!) about
2040a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    // dropping arguments.
2041a923c9783e8bd8edd26e56df9eaacd872c43e20eJohn McCall    if (!OldFn->use_empty()) {
2042bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
20439fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner      OldFn->removeDeadConstantUsers();
20449fa959d5bfbbb17d7c6ba71252219201fc8dc971Chris Lattner    }
20451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
204662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
2047bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    if (!Entry->use_empty()) {
20481eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      llvm::Constant *NewPtrForOldDecl =
20493c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2050bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner      Entry->replaceAllUsesWith(NewPtrForOldDecl);
2051bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    }
20521eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
205362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
2054bdb0132722082886558f31eccdba06ae1852c0eeChris Lattner    OldFn->eraseFromParent();
20551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20560558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner    Entry = NewFn;
2057bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
20581eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2059112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // We need to set linkage and visibility on the function before
2060112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // generating code for it because various parts of IR generation
2061112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // want to propagate this information down (e.g. to local static
2062112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // declarations).
20630558e79840bfdbbd38c6e2b4f6765bf0158e85f4Chris Lattner  llvm::Function *Fn = cast<llvm::Function>(Entry);
20648b2423361648c39a7d8a3c5e8129e12006deac32John McCall  setFunctionLinkage(D, Fn);
2065bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
2066112c967bd5c862a0f5d7913aa06700c048807db8John McCall  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
20670ffeaad72cb335b926b064379be4c9886bbff004Anders Carlsson  setGlobalVisibility(Fn, D);
2068112c967bd5c862a0f5d7913aa06700c048807db8John McCall
2069d26bc76c98006609002d9930f8840490e88ac5b5John McCall  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
20706379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
20717c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetFunctionDefinitionAttributes(D, Fn);
20727c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetLLVMFunctionAttributesForDefinition(D, Fn);
20731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
207440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2075219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
207640b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2077219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
207877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D->hasAttr<AnnotateAttr>())
207977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge    AddGlobalAnnotations(D, Fn);
2080bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
2081bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
2082f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCallvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2083f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
208440b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  const AliasAttr *AA = D->getAttr<AliasAttr>();
2085bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  assert(AA && "Not an alias?");
2086bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
20875f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef MangledName = getMangledName(GD);
2088f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
2089f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // If there is a definition in the module, then it wins over the alias.
2090f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  // This is dubious, but allow it to be safe.  Just ignore the alias.
2091f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2092f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  if (Entry && !Entry->isDeclaration())
2093f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    return;
20941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
20952acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2096bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
2097bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create a reference to the named value.  This ensures that it is emitted
2098bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // if a deferred decl.
2099bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  llvm::Constant *Aliasee;
2100bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (isa<llvm::FunctionType>(DeclTy))
2101c857ce8b08397ed778928b8a000732ca90da2a8cAlex Rosenberg    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
21021faa89f9c619e4b2411fab4af7e22ee7a2bd9009Anders Carlsson                                      /*ForVTable=*/false);
2103bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  else
2104f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
210596e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson                                    llvm::PointerType::getUnqual(DeclTy), 0);
2106bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
2107bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  // Create the new alias itself, but don't set a name yet.
21081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalValue *GA =
2109bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    new llvm::GlobalAlias(Aliasee->getType(),
2110bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          llvm::Function::ExternalLinkage,
2111bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                          "", Aliasee, &getModule());
21121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2113bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  if (Entry) {
2114f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    assert(Entry->isDeclaration());
2115f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall
2116bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // If there is a declaration in the module, then we had an extern followed
2117bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // by the alias, as in:
2118bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   extern int test6();
2119bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   ...
2120bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //   int test6() __attribute__((alias("test7")));
2121bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    //
2122bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    // Remove it and replace uses of it with the alias.
2123f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall    GA->takeName(Entry);
21241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21253c4972def972f8ca44dcd0561779a12aaa6fec97Owen Anderson    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2126bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner                                                          Entry->getType()));
2127bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner    Entry->eraseFromParent();
2128f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else {
21299a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    GA->setName(MangledName);
2130bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner  }
21311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
21327c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // Set attributes which are particular to an alias; this is a
21337c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // specialization of the attributes which may be set on a global
21347c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  // variable/function.
213540b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D->hasAttr<DLLExportAttr>()) {
21367c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
21377c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      // The dllexport attribute is ignored for undefined symbols.
213806a54a38be5054c910ffc92db60edab23f9ea105Argyrios Kyrtzidis      if (FD->hasBody())
21397c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar        GA->setLinkage(llvm::Function::DLLExportLinkage);
21407c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    } else {
21417c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar      GA->setLinkage(llvm::Function::DLLExportLinkage);
21427c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    }
21431eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  } else if (D->hasAttr<WeakAttr>() ||
214411e8ce7380856abee188b237c2600272df2ed09dRafael Espindola             D->hasAttr<WeakRefAttr>() ||
21450a0d2b179085a52c10402feebeb6db8b4d96a140Douglas Gregor             D->isWeakImported()) {
21467c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar    GA->setLinkage(llvm::Function::WeakAnyLinkage);
21477c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  }
21487c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar
21497c65e990e9f0dafaf9adbc59b766dcc23eaee845Daniel Dunbar  SetCommonAttributes(D, GA);
2150bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner}
2151bd53271dc7570b54f7b7cab7b09bcf04c6e927f6Chris Lattner
21528dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
21532d3ba4f5a923a90c3fc290ddfba5e36c2d0a9b46Chris Lattner                                            ArrayRef<llvm::Type*> Tys) {
2154df983a8bcbbcea911b8dce283f044787df119d50Jay Foad  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
21558dd55a3c3b28d195717c87bbc60e765951d408feBenjamin Kramer                                         Tys);
21567acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
2157bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
21581d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarstatic llvm::StringMapEntry<llvm::Constant*> &
21591d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
21601d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         const StringLiteral *Literal,
216170ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                         bool TargetIsLSB,
21621d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         bool &IsUTF16,
21631d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar                         unsigned &StringLength) {
21645f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef String = Literal->getString();
21652f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer  unsigned NumBytes = String.size();
21661d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
2167f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  // Check for simple case.
2168f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  if (!Literal->containsNonAsciiOrNull()) {
2169f015b034159d40e7033309e50036804eb1971787Daniel Dunbar    StringLength = NumBytes;
21702f4eaef37476ae6891ede8ba215d0f6fd093629bBenjamin Kramer    return Map.GetOrCreateValue(String);
2171f015b034159d40e7033309e50036804eb1971787Daniel Dunbar  }
2172f015b034159d40e7033309e50036804eb1971787Daniel Dunbar
217384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // Otherwise, convert the UTF8 literals into a string of shorts.
217484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  IsUTF16 = true;
217584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
217684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
217731ba6135375433b617a8587ea6cc836a014ebd86Roman Divacky  const UTF8 *FromPtr = (const UTF8 *)String.data();
21781d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  UTF16 *ToPtr = &ToBuf[0];
21791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2180e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2181e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           &ToPtr, ToPtr + NumBytes,
2182e7ddfb974884ec75ffd66953b79511ea457493baFariborz Jahanian                           strictConversion);
21831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
218470ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar  // ConvertUTF8toUTF16 returns the length in ToPtr.
21851d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  StringLength = ToPtr - &ToBuf[0];
218670ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar
218784392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // Add an explicit null.
218884392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  *ToPtr = 0;
218984392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  return Map.
219084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
219184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling                               (StringLength + 1) * 2));
21921d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar}
21931d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar
2194cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanianstatic llvm::StringMapEntry<llvm::Constant*> &
2195cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz JahanianGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
21968322c23956c4dea057a930753f23ff6467353e55Bill Wendling                       const StringLiteral *Literal,
21978322c23956c4dea057a930753f23ff6467353e55Bill Wendling                       unsigned &StringLength) {
21988322c23956c4dea057a930753f23ff6467353e55Bill Wendling  StringRef String = Literal->getString();
21998322c23956c4dea057a930753f23ff6467353e55Bill Wendling  StringLength = String.size();
22008322c23956c4dea057a930753f23ff6467353e55Bill Wendling  return Map.GetOrCreateValue(String);
2201cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian}
2202cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian
22031d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbarllvm::Constant *
22041d5529132e4620562cab931c1f84c24e42f02741Daniel DunbarCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
22051d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  unsigned StringLength = 0;
22061d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  bool isUTF16 = false;
22071d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  llvm::StringMapEntry<llvm::Constant*> &Entry =
22081eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    GetConstantCFStringEntry(CFConstantStringMap, Literal,
220925a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow                             getDataLayout().isLittleEndian(),
221070ee975fad4653fa09f8e77f9a46a7b1f592ef59Daniel Dunbar                             isUTF16, StringLength);
22111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
22121d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  if (llvm::Constant *C = Entry.getValue())
22131d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar    return C;
22141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
22158b418685e9e4f02f4eb2a76e1ec063e07552b68dChris Lattner  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
22163e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
22171eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
22189d4a15fd3b85434c43ea27562793de63a793321aChris Lattner  // If we don't already have it, get __CFConstantStringClassReference.
2219c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
22202acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
222196e0fc726c6fe7538522c60743705d5e696b40afOwen Anderson    Ty = llvm::ArrayType::get(Ty, 0);
22221eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    llvm::Constant *GV = CreateRuntimeVariable(Ty,
22239d4a15fd3b85434c43ea27562793de63a793321aChris Lattner                                           "__CFConstantStringClassReference");
22243e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
22253e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
2226a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad      llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2227c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
22281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2229e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
22303e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
22312acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::StructType *STy =
2232e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2233e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
22341d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[4];
223544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
2236c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
22375add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[0] = CFConstantStringClassRef;
22381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2239c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
22402acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
22411eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
22425add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson    llvm::ConstantInt::get(Ty, 0x07C8);
22435add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
2244c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
224584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  llvm::Constant *C = 0;
224684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  if (isUTF16) {
224784392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    ArrayRef<uint16_t> Arr =
22485ba58a1b3cbe79497380e7ccecbe45c8bdd498c1David Greene      llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
22495ba58a1b3cbe79497380e7ccecbe45c8bdd498c1David Greene                                     const_cast<char *>(Entry.getKey().data())),
225084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling                                   Entry.getKey().size() / 2);
225184392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    C = llvm::ConstantDataArray::get(VMContext, Arr);
225284392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  } else {
225384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
225484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  }
2255a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar
225695b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner  llvm::GlobalValue::LinkageTypes Linkage;
22571bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  if (isUTF16)
2258278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner    // FIXME: why do utf strings get "_" labels instead of "L" labels?
225995b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    Linkage = llvm::GlobalValue::InternalLinkage;
22601bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  else
2261584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2262584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // when using private linkage. It is not clear if this is a bug in ld
2263584acf2ded2c18a18d6da0e1c01f5859a384d99fRafael Espindola    // or a reasonable new restriction.
2264dc0f137295bc7ec5b231ff1842388f149f43c0c8Rafael Espindola    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2265278b9f06933c385ffbccc15f8491787470cb4a1bChris Lattner
22661bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // Note: -fwritable-strings doesn't make the backing store strings of
22671bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling  // CFStrings writable. (See <rdar://problem/10657500>)
22681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  llvm::GlobalVariable *GV =
22691bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
22701bf7a3fcc4e2ad30688f7b0db464ad1ccabe77e2Bill Wendling                             Linkage, C, ".str");
2271b266a1fce09ab4ee7033268199509aacfbef056aRafael Espindola  GV->setUnnamedAddr(true);
2272a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  if (isUTF16) {
22734da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
22744da244c23d6093adbbbc41654aa5c5111b38f431Ken Dyck    GV->setAlignment(Align.getQuantity());
2275f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar  } else {
2276f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2277f7e903d7a30891083420c07ebeed281726a101d6Daniel Dunbar    GV->setAlignment(Align.getQuantity());
2278a9668e0b4c451a1021fe650c451b54dc98c2d18dDaniel Dunbar  }
227984392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
228084392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  // String.
2281a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
22825add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson
228384392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling  if (isUTF16)
228484392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    // Cast the UTF16 string to the correct type.
228584392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling    Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
228684392d0edc7127f868d3c97484ffc9d789c317ffBill Wendling
2287c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
2288c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
22895add6835b0c6b0f67e19fd5366825d3e41eb0dcfAnders Carlsson  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
22901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2291c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
229208e252425ca2cbdc44ba65d9a657ed5398014e36Owen Anderson  C = llvm::ConstantStruct::get(STy, Fields);
22931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
22941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                llvm::GlobalVariable::PrivateLinkage, C,
229595b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner                                "_unnamed_cfstring_");
2296bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor  if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
22978e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar    GV->setSection(Sect);
22981d5529132e4620562cab931c1f84c24e42f02741Daniel Dunbar  Entry.setValue(GV);
22991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
23000c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
2301c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
230245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
230345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregorstatic RecordDecl *
230445c4ea75b235de94f44bf96843624e6a559e4c00Douglas GregorCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
230545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                 DeclContext *DC, IdentifierInfo *Id) {
230645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  SourceLocation Loc;
23074e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (Ctx.getLangOpts().CPlusPlus)
230845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
230945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  else
231045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
231145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor}
231245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
231333e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanianllvm::Constant *
23144c73307c74764ba99e1379677fe92af72f676531Fariborz JahanianCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
23152bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  unsigned StringLength = 0;
23162bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::StringMapEntry<llvm::Constant*> &Entry =
2317cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
23182bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23192bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  if (llvm::Constant *C = Entry.getValue())
23202bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    return C;
23212bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
2322812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
23232bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::Constant *Zeros[] = { Zero, Zero };
23242bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
2325ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  // If we don't already have it, get _NSConstantStringClassReference.
23264c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  if (!ConstantStringClassRef) {
23274e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie    std::string StringClass(getLangOpts().ObjCConstantStringClass);
23282acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
23294c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    llvm::Constant *GV;
2330260611a32535c851237926bfcf78869b13c07d5bJohn McCall    if (LangOpts.ObjCRuntime.isNonFragile()) {
233125dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
233225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
233325dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "OBJC_CLASS_$_" + StringClass;
23346f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      GV = getObjCRuntime().GetClassGlobal(str);
23356f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Make sure the result is of the correct type.
23362acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
23376f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
23386f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian        llvm::ConstantExpr::getBitCast(GV, PTy);
23396f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian    } else {
234025dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      std::string str =
234125dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian        StringClass.empty() ? "_NSConstantStringClassReference"
234225dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian                            : "_" + StringClass + "ClassReference";
23432acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
234425dba5d294364fa8339091e4d9e6a8f5db008377Fariborz Jahanian      GV = CreateRuntimeVariable(PTy, str);
23456f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      // Decay array -> ptr
23466f40e2244b0590f144c5ceee07981a962fbbc72eFariborz Jahanian      ConstantStringClassRef =
2347a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad        llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
23484c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian    }
23492bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  }
235045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
235145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  if (!NSConstantStringType) {
235245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Construct the type for a constant NSString.
235345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
235445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                     Context.getTranslationUnitDecl(),
235545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                   &Context.Idents.get("__builtin_NSString"));
235645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->startDefinition();
235745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
235845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType FieldTypes[3];
235945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
236045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const int *isa;
236145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
236245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // const char *str;
236345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
236445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // unsigned int length;
236545c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    FieldTypes[2] = Context.UnsignedIntTy;
236645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
236745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    // Create fields
236845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    for (unsigned i = 0; i < 3; ++i) {
236945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context, D,
237045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(),
237145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           SourceLocation(), 0,
237245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
237345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*BitWidth=*/0,
237445c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor                                           /*Mutable=*/false,
2375ca5233044ef679840d1ad1c46a36b16e2ee8a6e1Richard Smith                                           ICIS_NoInit);
237645c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      Field->setAccess(AS_public);
237745c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor      D->addDecl(Field);
237845c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    }
237945c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor
238045c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    D->completeDefinition();
238145c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    QualType NSTy = Context.getTagDeclType(D);
238245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
238345c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  }
23842bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23851d236ab930816f5da27bade92904914c44b73b4cBenjamin Kramer  llvm::Constant *Fields[3];
23862bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23872bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // Class pointer.
23884c73307c74764ba99e1379677fe92af72f676531Fariborz Jahanian  Fields[0] = ConstantStringClassRef;
23892bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23902bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String pointer.
239194010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Constant *C =
239294010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
23932bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23942bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalValue::LinkageTypes Linkage;
23952bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  bool isConstant;
2396cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  Linkage = llvm::GlobalValue::PrivateLinkage;
23974e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  isConstant = !LangOpts.WritableStrings;
23982bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
23992bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  llvm::GlobalVariable *GV =
24002bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
24012bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                           ".str");
2402803d307a5385059b1a84dfe9706ab158c80a20dcRafael Espindola  GV->setUnnamedAddr(true);
2403cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2404cf8e168baf75b7ede6493d0373d64545c29c1a90Fariborz Jahanian  GV->setAlignment(Align.getQuantity());
2405a5c04344fa70d6eec34344760c1fe511e16f2d76Jay Foad  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
24062bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
24072bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // String length.
24082acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
24092bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
24102bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
24112bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // The struct.
241245c4ea75b235de94f44bf96843624e6a559e4c00Douglas Gregor  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
24132bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
24142bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                llvm::GlobalVariable::PrivateLinkage, C,
24152bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian                                "_unnamed_nsstring_");
24162bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  // FIXME. Fix section.
2417ec951e0c2fc0db00c36bc60c900331dde32c1b43Fariborz Jahanian  if (const char *Sect =
2418260611a32535c851237926bfcf78869b13c07d5bJohn McCall        LangOpts.ObjCRuntime.isNonFragile()
2419bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2420bcfd1f55bfbb3e5944cd5e03d07b343e280838c4Douglas Gregor          : getContext().getTargetInfo().getNSStringSection())
24212bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian    GV->setSection(Sect);
24222bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  Entry.setValue(GV);
24232bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian
24242bb5ddaff86ee73d2cea7ec1835978afc88a83f0Fariborz Jahanian  return GV;
242533e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian}
242633e982bf782d851bfe5767acb1336fcf3419ac6bFariborz Jahanian
24270815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas GregorQualType CodeGenModule::getObjCFastEnumerationStateType() {
24280815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  if (ObjCFastEnumerationStateType.isNull()) {
24290815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
24300815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                     Context.getTranslationUnitDecl(),
24310815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                      &Context.Idents.get("__objcFastEnumerationState"));
24320815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->startDefinition();
24330815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
24340815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    QualType FieldTypes[] = {
24350815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.UnsignedLongTy,
24360815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.getObjCIdType()),
24370815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getPointerType(Context.UnsignedLongTy),
24380815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Context.getConstantArrayType(Context.UnsignedLongTy,
24390815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                           llvm::APInt(32, 5), ArrayType::Normal, 0)
24400815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    };
24410815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
24420815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    for (size_t i = 0; i < 4; ++i) {
24430815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      FieldDecl *Field = FieldDecl::Create(Context,
24440815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           D,
24450815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(),
24460815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           SourceLocation(), 0,
24470815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           FieldTypes[i], /*TInfo=*/0,
24480815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*BitWidth=*/0,
24490815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor                                           /*Mutable=*/false,
2450ca5233044ef679840d1ad1c46a36b16e2ee8a6e1Richard Smith                                           ICIS_NoInit);
24510815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      Field->setAccess(AS_public);
24520815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor      D->addDecl(Field);
24530815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    }
24540815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
24550815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    D->completeDefinition();
24560815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
24570815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  }
24580815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
24590815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor  return ObjCFastEnumerationStateType;
24600815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor}
24610815b579b31cb3129f732bb7ea36fd6ba6949e98Douglas Gregor
246264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedmanllvm::Constant *
246364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli FriedmanCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
246464f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  assert(!E->getType()->isPointerType() && "Strings are always arrays");
246564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
246664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // Don't emit it as the address of the string, emit the string data itself
246764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  // as an inline array.
2468812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  if (E->getCharByteWidth() == 1) {
2469812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    SmallString<64> Str(E->getString());
2470812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner
2471812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    // Resize the string to the right size, which is indicated by its type.
2472812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2473812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    Str.resize(CAT->getSize().getZExtValue());
2474812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    return llvm::ConstantDataArray::getString(VMContext, Str, false);
2475812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  }
247694010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner
247794010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::ArrayType *AType =
247894010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
247994010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  llvm::Type *ElemTy = AType->getElementType();
248094010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  unsigned NumElements = AType->getNumElements();
2481d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2482d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  // Wide strings have either 2-byte or 4-byte elements.
2483d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  if (ElemTy->getPrimitiveSizeInBits() == 16) {
2484d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    SmallVector<uint16_t, 32> Elements;
2485d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.reserve(NumElements);
2486d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2487d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2488d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner      Elements.push_back(E->getCodeUnit(i));
2489d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.resize(NumElements);
2490d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    return llvm::ConstantDataArray::get(VMContext, Elements);
249194010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner  }
249294010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner
2493d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  assert(ElemTy->getPrimitiveSizeInBits() == 32);
2494d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  SmallVector<uint32_t, 32> Elements;
2495d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  Elements.reserve(NumElements);
2496d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner
2497d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2498d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner    Elements.push_back(E->getCodeUnit(i));
2499d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  Elements.resize(NumElements);
2500d79ed43d2bb9dd4a54889450ecff9299a9d4d1bcChris Lattner  return llvm::ConstantDataArray::get(VMContext, Elements);
250164f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman}
250264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
25036143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
25046143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
25056143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
25066143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2507a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  CharUnits Align = getContext().getTypeAlignInChars(S->getType());
250864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  if (S->isAscii() || S->isUTF8()) {
2509812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    SmallString<64> Str(S->getString());
2510812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner
2511812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    // Resize the string to the right size, which is indicated by its type.
2512812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2513812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    Str.resize(CAT->getSize().getZExtValue());
2514812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner    return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
25157eb79c1010c8d30b852768bec96e81cd3e6def2eEli Friedman  }
251664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman
2517812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  // FIXME: the following does not memoize wide strings.
251864f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
251964f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  llvm::GlobalVariable *GV =
252064f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman    new llvm::GlobalVariable(getModule(),C->getType(),
25214e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie                             !LangOpts.WritableStrings,
252264f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             llvm::GlobalValue::PrivateLinkage,
252364f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman                             C,".str");
25247d6a7c004361c45a463874a58da28d9f3c35f2e6Seth Cantrell
252564f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setAlignment(Align.getQuantity());
252664f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  GV->setUnnamedAddr(true);
252764f45a24b19eb89ff88f7c3ff0df9be8e861ac97Eli Friedman  return GV;
25286143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
25296143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
2530eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2531eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
2532eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
2533eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2534eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
2535eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2536a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
2537a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
2538eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
2539eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2540eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
2541a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
2542a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCallstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
254345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
25445fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
2545a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             const char *GlobalName,
2546a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                             unsigned Alignment) {
25476143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
25480032b2781b4deb131f8c9b7968f2030bf2489cddOwen Anderson  llvm::Constant *C =
254994010695f7fce626e41ef045b60def9c912e9ce8Chris Lattner      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
25501eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
255145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
25521257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  llvm::GlobalVariable *GV =
25531257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
25541257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             llvm::GlobalValue::PrivateLinkage,
25551257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola                             C, GlobalName);
2556a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  GV->setAlignment(Alignment);
25571257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  GV->setUnnamedAddr(true);
25581257bc6ee76b931e3f8e51a88298b95379963d24Rafael Espindola  return GV;
255945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
256045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
25616143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
25626143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
25636143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
25646143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
25656143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
25666143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
25676143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
25686143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
25695f9e272e632e951b1efe824cd16acb4d96077930Chris Lattnerllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2570a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       const char *GlobalName,
2571a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                       unsigned Alignment) {
25728e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Get the default prefix if a name wasn't specified.
25738e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  if (!GlobalName)
257495b851e55c328af4b69da7bfc1124bf258c0ffe5Chris Lattner    GlobalName = ".str";
25758e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar
25768e5c2b8072f4409c7c0004331d1db9652d5209c0Daniel Dunbar  // Don't share any string literals if strings aren't constant.
25774e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (LangOpts.WritableStrings)
2578a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
25791eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2580a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
25819de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer    ConstantStringMap.GetOrCreateValue(Str);
258245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
2583a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2584a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    if (Alignment > GV->getAlignment()) {
2585a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall      GV->setAlignment(Alignment);
2586a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    }
2587a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall    return GV;
2588a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  }
258945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
259045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
2591812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2592812234b70461eafd43acb6ccbd736bb4bbf88728Chris Lattner                                                   Alignment);
2593a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  Entry.setValue(GV);
2594a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GV;
259545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
25966143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
25976143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
25989de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramer/// array containing the literal and a terminating '\0'
25996143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
26009de4342ef79a18c706e46bc23f8f579f5add2375Benjamin Kramerllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2601a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        const char *GlobalName,
2602a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall                                                        unsigned Alignment) {
26035f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2604a5e19c6b2554f6d9c4b9850d4dbbbfa3643282e5John McCall  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
26056143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
260641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2607af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
2608af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
26091eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpvoid CodeGenModule::EmitObjCPropertyImplementations(const
2610af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
26111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  for (ObjCImplementationDecl::propimpl_iterator
261217945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2613581deb3da481053c4993c7600f97acf7768caac5David Blaikie    ObjCPropertyImplDecl *PID = *i;
26141eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2615af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
2616af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2617af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2618af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2619af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
26201e4691b9d8e1bdcc8ef62b323969d702c51b3c08Jordan Rose      // been overridden. Note that ::isPropertyAccessor is not the method
2621af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
2622af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
2623af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
262417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      if (!D->getInstanceMethod(PD->getGetterName()))
2625fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
2626fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2627af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
262817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis          !D->getInstanceMethod(PD->getSetterName()))
2629fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
2630fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
2631af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
2632af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
2633af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
2634af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
2635e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCallstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
2636db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2637db8264e4c5ffd7af6fbad4ca4306bd382bb02691Jordy Rose  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2638e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall       ivar; ivar = ivar->getNextIvar())
2639e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    if (ivar->getType().isDestructedType())
2640e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      return true;
2641e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2642e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  return false;
2643e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall}
2644e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2645109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// EmitObjCIvarInitializations - Emit information for ivar initialization
2646109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian/// for an implementation.
2647109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanianvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2648e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2649e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  if (needsDestructMethod(D)) {
2650e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2651e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2652e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    ObjCMethodDecl *DTORMethod =
2653e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
265475cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             cxxSelector, getContext().VoidTy, 0, D,
265575cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isInstance=*/true, /*isVariadic=*/false,
26561e4691b9d8e1bdcc8ef62b323969d702c51b3c08Jordan Rose                          /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
265775cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                             /*isDefined=*/false, ObjCMethodDecl::Required);
2658e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    D->addInstanceMethod(DTORMethod);
2659e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2660b03527a9a395168762ad8e25e59a7a272dd74561John McCall    D->setHasDestructors(true);
2661e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  }
2662e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall
2663e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // If the implementation doesn't have any ivar initializers, we don't need
2664e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  // a .cxx_construct.
2665827bbcc8a9115782693b21030a45378abe5c1862David Chisnall  if (D->getNumIvarInitializers() == 0)
2666109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    return;
2667109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
2668e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2669e81ac69c5da9fadfac33ee76e98d5fb558c4e389John McCall  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2670109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  // The constructor returns 'self'.
2671109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2672109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                D->getLocation(),
267311d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                D->getLocation(),
267411d77169555480ee0a04c6e5bc390d8fde41175dArgyrios Kyrtzidis                                                cxxSelector,
2675109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                getContext().getObjCIdType(), 0,
267675cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                D, /*isInstance=*/true,
267775cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isVariadic=*/false,
26781e4691b9d8e1bdcc8ef62b323969d702c51b3c08Jordan Rose                                                /*isPropertyAccessor=*/true,
267975cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isImplicitlyDeclared=*/true,
268075cf3e86d33ce810c12084126385371b335c30baArgyrios Kyrtzidis                                                /*isDefined=*/false,
2681109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian                                                ObjCMethodDecl::Required);
2682109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  D->addInstanceMethod(CTORMethod);
2683109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2684b03527a9a395168762ad8e25e59a7a272dd74561John McCall  D->setHasNonZeroConstructors(true);
2685109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian}
2686109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian
268791e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson/// EmitNamespace - Emit all declarations in a namespace.
2688984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlssonvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
268917945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2690984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson       I != E; ++I)
2691984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitTopLevelDecl(*I);
2692984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson}
2693984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson
269491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson// EmitLinkageSpec - Emit all declarations in a linkage spec.
269591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlssonvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2696f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2697f976be8a63f9e0d3bd50e33dadef02c3c9921747Eli Friedman      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
269891e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    ErrorUnsupported(LSD, "linkage spec");
269991e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    return;
270091e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  }
270191e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
270217945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2703c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian       I != E; ++I) {
2704107dae4c7afca73e97d2689d6f644c13ac3048a4Fariborz Jahanian    // Meta-data for ObjC class includes references to implemented methods.
2705107dae4c7afca73e97d2689d6f644c13ac3048a4Fariborz Jahanian    // Generate class's method definitions first.
2706c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian    if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2707c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian      for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2708c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian           MEnd = OID->meth_end();
2709c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian           M != MEnd; ++M)
2710c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian        EmitTopLevelDecl(*M);
2711c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian    }
271291e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitTopLevelDecl(*I);
2713c1868e533e63a1b7dad7a22714fc593c045382aeFariborz Jahanian  }
271491e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson}
271591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson
271641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
271741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
271841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
271941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
272041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
272141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
272241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
272341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
272416e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  // Ignore dependent declarations.
272516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
272616e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    return;
27271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
272841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
2729293361afd4199c92aabff9267fddea890943c586Anders Carlsson  case Decl::CXXConversion:
27302b77ba8bc7a842829ad9193816dc1d7d5e9c5be6Anders Carlsson  case Decl::CXXMethod:
273141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
273216e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor    // Skip function templates
27338387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
27348387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
273516e8be2ac532358d4e413fdfa2643b1876edda78Douglas Gregor      return;
27361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2737555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<FunctionDecl>(D));
2738555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    break;
2739555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson
274041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
2741555b4bb2749aea2ec8e2adc351a71ec1cb9bdc33Anders Carlsson    EmitGlobal(cast<VarDecl>(D));
274241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
274341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
274426fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // Indirect fields from global anonymous structs and unions can be
274526fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  // ignored; only the actual variable requires IR gen support.
274626fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall  case Decl::IndirectField:
274726fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall    break;
274826fbc72b33bdbd20b0145bf117c64d373f8051e3John McCall
274995d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // C++ Decls
275041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
2751984e06874685396ca2cb51f0008cfff7c9b3d9c6Anders Carlsson    EmitNamespace(cast<NamespaceDecl>(D));
275241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
27539cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    // No code generation needed.
27549d0c6613ec040ad8d952556be909232a7f25dedeJohn McCall  case Decl::UsingShadow:
27559cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor  case Decl::Using:
2756dd9967a6374c9a44be4af02aaeee340ffb82848fDouglas Gregor  case Decl::UsingDirective:
2757127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::ClassTemplate:
2758127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  case Decl::FunctionTemplate:
27593e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  case Decl::TypeAliasTemplate:
2760018837b081bd1a725bae1c020eb1649975b04d67Anders Carlsson  case Decl::NamespaceAlias:
27616a576ab708d3aa7d40e5d867ab1de5d3cb507553Douglas Gregor  case Decl::Block:
2762684aa73192d92850a926870be62a1787eb5b7ed9Michael Han  case Decl::Empty:
27639cfbe48a7a20a217fdb2920b29b67ae7941cb116Douglas Gregor    break;
276495d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  case Decl::CXXConstructor:
27651fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson    // Skip function templates
27668387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
27678387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet        cast<FunctionDecl>(D)->isLateTemplateParsed())
27681fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson      return;
27691fe598c026dc03fddbd65efb8119eb1afd9b1520Anders Carlsson
277095d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
277195d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson    break;
277227ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson  case Decl::CXXDestructor:
27738387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
27748387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      return;
277527ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
277627ae53665f8b00fe4ba21da0fa79a4ce6e0b6cd5Anders Carlsson    break;
277736674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
277836674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson  case Decl::StaticAssert:
277936674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    // Nothing to do.
278036674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson    break;
278136674d2978eb53962218ac67bb4d352cc287ea05Anders Carlsson
278295d4e5d2f87a0f07fb143ccb824dfc4c5c595c78Anders Carlsson  // Objective-C Decls
27831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
278438e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
2785b31cb7f1752ea011fd06ac9574ce24667d11cbdbFariborz Jahanian  case Decl::ObjCInterface:
2786ffb0c3adc27d257c8453886957b8d220d1ad14d8Eric Christopher  case Decl::ObjCCategory:
278741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2788285d0dba947b7c9960eaa88e8c4fced0398d4319Chris Lattner
2789bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  case Decl::ObjCProtocol: {
2790bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2791bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor    if (Proto->isThisDeclarationADefinition())
2792bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor      ObjCRuntime->GenerateProtocol(Proto);
279341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
2794bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor  }
2795bd9482d859a74bf2c45ef8b8aedec61c0e1c8374Douglas Gregor
279641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
2797af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
2798af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
2799e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
280041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
280141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
2802af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
2803af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2804af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
2805109dfc6ca6652f60c55ed0f2631aebf323d0200dFariborz Jahanian    EmitObjCIvarInitializations(OMD);
2806e926523105dd2604ccd5c101605dea43c5269965Peter Collingbourne    ObjCRuntime->GenerateClass(OMD);
2807be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher    // Emit global variable debug information.
2808be6c6869a993536d4cd007f04e84ef74a1c3b229Eric Christopher    if (CGDebugInfo *DI = getModuleDebugInfo())
280996a66392649f23e19bb9b2d512f2779b9dd420d0Alexey Samsonov      if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
281096a66392649f23e19bb9b2d512f2779b9dd420d0Alexey Samsonov        DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
281196a66392649f23e19bb9b2d512f2779b9dd420d0Alexey Samsonov            OMD->getClassInterface()), OMD->getLocation());
281241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
28131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
281441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
281541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
281641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
28176fb0aee4f9dc261bbec72e1283ad8dc0557a6d96Argyrios Kyrtzidis    if (OMD->getBody())
281841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
281941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
282041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
28211eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::ObjCCompatibleAlias:
282229254f4dd114fe2dd5c4e7a261ebea941973ad3dDavid Chisnall    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
282341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
282441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
282591e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson  case Decl::LinkageSpec:
282691e20dd8bf1bc8980ee93839383d2bd170bce050Anders Carlsson    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
282741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
282841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
282941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
283041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
28315f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef AsmString = AD->getAsmString()->getString();
28321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
283341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
283441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
283541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
28368ce9cca118b32604f481ad381eafab25b5798c9fJoerg Sonnenberger    else if (S.end()[-1] == '\n')
28379f5bff086cad25c15b4deb8a7763786097aadccdChris Lattner      getModule().setModuleInlineAsm(S + AsmString.str());
283841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
28398d04258483be6583f0865464234d014807a3e1ccBenjamin Kramer      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
284041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
284141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
28421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2843b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor  case Decl::Import: {
2844b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor    ImportDecl *Import = cast<ImportDecl>(D);
2845b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor
2846b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor    // Ignore import declarations that come from imported modules.
2847b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor    if (clang::Module *Owner = Import->getOwningModule()) {
2848b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor      if (getLangOpts().CurrentModule.empty() ||
2849b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor          Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2850b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor        break;
2851b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor    }
2852b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor
2853858afb3c22144027bcd8ba75e27262eede093a60Douglas Gregor    ImportedModules.insert(Import->getImportedModule());
2854b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor    break;
2855b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor }
2856b6cbe517237c3c223beb064d60d5b49e56d65c06Douglas Gregor
28571eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  default:
2858f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // Make sure we handled everything we should, every other kind is a
2859f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2860f5408fe484495ee4efbdd709c8a2c2fdbbbdb328Mike Stump    // function. Need to recode Decl::Kind to do that easily.
286141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
286241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
286341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
2864744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2865744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Turns the given pointer into a constant.
2866744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2867744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                          const void *Ptr) {
2868744016dde06fcffd50931e94a98c850f8b12cd87John McCall  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
28692acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2870744016dde06fcffd50931e94a98c850f8b12cd87John McCall  return llvm::ConstantInt::get(i64, PtrInt);
2871744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2872744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2873744016dde06fcffd50931e94a98c850f8b12cd87John McCallstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2874744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::NamedMDNode *&GlobalMetadata,
2875744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   GlobalDecl D,
2876744016dde06fcffd50931e94a98c850f8b12cd87John McCall                                   llvm::GlobalValue *Addr) {
2877744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (!GlobalMetadata)
2878744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GlobalMetadata =
2879744016dde06fcffd50931e94a98c850f8b12cd87John McCall      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2880744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2881744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // TODO: should we report variant information for ctors/dtors?
2882744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::Value *Ops[] = {
2883744016dde06fcffd50931e94a98c850f8b12cd87John McCall    Addr,
2884744016dde06fcffd50931e94a98c850f8b12cd87John McCall    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2885744016dde06fcffd50931e94a98c850f8b12cd87John McCall  };
28866f141659cab11109d9931d92d0988f8850778de3Jay Foad  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2887744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2888744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2889744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes associating all the global values in the
2890744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// current module with the Decls they came from.  This is useful for
2891744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// projects using IR gen as a subroutine.
2892744016dde06fcffd50931e94a98c850f8b12cd87John McCall///
2893744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Since there's currently no way to associate an MDNode directly
2894744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with an llvm::GlobalValue, we create a global named metadata
2895744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// with the name 'clang.global.decl.ptrs'.
2896744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenModule::EmitDeclMetadata() {
2897744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2898744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2899744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // StaticLocalDeclMap
29005f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2901744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2902744016dde06fcffd50931e94a98c850f8b12cd87John McCall       I != E; ++I) {
2903744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2904744016dde06fcffd50931e94a98c850f8b12cd87John McCall    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2905744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2906744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2907744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2908744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// Emits metadata nodes for all the local variables in the current
2909744016dde06fcffd50931e94a98c850f8b12cd87John McCall/// function.
2910744016dde06fcffd50931e94a98c850f8b12cd87John McCallvoid CodeGenFunction::EmitDeclMetadata() {
2911744016dde06fcffd50931e94a98c850f8b12cd87John McCall  if (LocalDeclMap.empty()) return;
2912744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2913744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::LLVMContext &Context = getLLVMContext();
2914744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2915744016dde06fcffd50931e94a98c850f8b12cd87John McCall  // Find the unique metadata ID for this name.
2916744016dde06fcffd50931e94a98c850f8b12cd87John McCall  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2917744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2918744016dde06fcffd50931e94a98c850f8b12cd87John McCall  llvm::NamedMDNode *GlobalMetadata = 0;
2919744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2920744016dde06fcffd50931e94a98c850f8b12cd87John McCall  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2921744016dde06fcffd50931e94a98c850f8b12cd87John McCall         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2922744016dde06fcffd50931e94a98c850f8b12cd87John McCall    const Decl *D = I->first;
2923744016dde06fcffd50931e94a98c850f8b12cd87John McCall    llvm::Value *Addr = I->second;
2924744016dde06fcffd50931e94a98c850f8b12cd87John McCall
2925744016dde06fcffd50931e94a98c850f8b12cd87John McCall    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2926744016dde06fcffd50931e94a98c850f8b12cd87John McCall      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
29276f141659cab11109d9931d92d0988f8850778de3Jay Foad      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2928744016dde06fcffd50931e94a98c850f8b12cd87John McCall    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2929744016dde06fcffd50931e94a98c850f8b12cd87John McCall      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2930744016dde06fcffd50931e94a98c850f8b12cd87John McCall      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2931744016dde06fcffd50931e94a98c850f8b12cd87John McCall    }
2932744016dde06fcffd50931e94a98c850f8b12cd87John McCall  }
2933744016dde06fcffd50931e94a98c850f8b12cd87John McCall}
2934673431a2986f750b4d8fadb57abf3f00db27bbbdDaniel Dunbar
29353dc05418538c719fea48b906bfa4febe5296e126Nick Lewyckyvoid CodeGenModule::EmitCoverageFile() {
29363dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky  if (!getCodeGenOpts().CoverageFile.empty()) {
29375ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
29385ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
29395ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      llvm::LLVMContext &Ctx = TheModule.getContext();
29403dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky      llvm::MDString *CoverageFile =
29413dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
29425ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
29435ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *CU = CUNode->getOperand(i);
29443dc05418538c719fea48b906bfa4febe5296e126Nick Lewycky        llvm::Value *node[] = { CoverageFile, CU };
29455ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
29465ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky        GCov->addOperand(N);
29475ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky      }
29485ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky    }
29495ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky  }
29505ea4f44e34449a78d6b38aa47c14b527839d7aacNick Lewycky}
2951c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2952c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weberllvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
2953c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber                                                     QualType GuidType) {
2954c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // Sema has checked that all uuid strings are of the form
2955c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  // "12345678-1234-1234-1234-1234567890ab".
2956c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  assert(Uuid.size() == 36);
2957c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  const char *Uuidstr = Uuid.data();
2958c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  for (int i = 0; i < 36; ++i) {
2959c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber    if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
29603f6f51e28231f65de9c2dd150a2d757b2162cfa3Jordan Rose    else                                         assert(isHexDigit(Uuidstr[i]));
2961c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  }
2962c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2963c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::APInt Field0(32, StringRef(Uuidstr     , 8), 16);
2964c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::APInt Field1(16, StringRef(Uuidstr +  9, 4), 16);
2965c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
2966193646f16d90f004123965606ec3fae180beafe1Nico Weber  static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
2967c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2968c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
2969c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
2970c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
2971c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
2972c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  APValue& Arr = InitStruct.getStructField(3);
2973c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  Arr = APValue(APValue::UninitArray(), 8, 8);
2974c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  for (int t = 0; t < 8; ++t)
297543085815b1b377dc30176afab2b96d6b807d42deNico Weber    Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
297643085815b1b377dc30176afab2b96d6b807d42deNico Weber          llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
2977c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber
2978c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber  return EmitConstantValue(InitStruct, GuidType);
2979c5f804636e367ef744fd24cf88f7c956a5af0434Nico Weber}
2980