CodeGenModule.cpp revision 62b33ea51adbd0e7f2f05983e9e4a3a2b2ed26de
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
14e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta#include "CGDebugInfo.h"
155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenModule.h"
165f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenFunction.h"
170dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar#include "CGCall.h"
18af2f62ce32e462f256855cd24b06dec4755d2827Daniel Dunbar#include "CGObjCRuntime.h"
195f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor#include "Mangle.h"
205f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/AST/ASTContext.h"
21c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/DeclObjC.h"
2221ef7ae45c8b91f23cf5eab2263421bb398a644bChris Lattner#include "clang/AST/DeclCXX.h"
232c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner#include "clang/Basic/Diagnostic.h"
248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
255f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "clang/Basic/TargetInfo.h"
26ec9426ca6039279bcc99bc2c625bb2abe4f0353dNate Begeman#include "llvm/CallingConv.h"
27bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner#include "llvm/Module.h"
285f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "llvm/Intrinsics.h"
2920ff3108fcd2c3bd734dc79efc22ebaa090abd41Anton Korobeynikov#include "llvm/Target/TargetData.h"
305f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
315f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
325f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
335f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
3445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris LattnerCodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35fb97b03e42d397405f617be0252be83e77a66f6eChris Lattner                             llvm::Module &M, const llvm::TargetData &TD,
36f77ac86f4eca528a04b817d7ad7f045a47d52712Daniel Dunbar                             Diagnostic &diags, bool GenerateDebugInfo)
3790a904309c79977fcba2ff0542e2e4cd8e3c3fafMike Stump  : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
382a998148a6823c44d67da347c95eb2ea21f6b986Mike Stump    TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
392a998148a6823c44d67da347c95eb2ea21f6b986Mike Stump    MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
40208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar
413c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  if (!Features.ObjC1)
423c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = 0;
433c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  else if (!Features.NeXTRuntime)
443c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = CreateGNUObjCRuntime(*this);
453c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  else if (Features.ObjCNonFragileABI)
463c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
473c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  else
483c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    Runtime = CreateMacObjCRuntime(*this);
49e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta
50e8b9f5b8ea60983c4a74cb8b63879616b914b65aSanjiv Gupta  // If debug info generation is enabled, create the CGDebugInfo object.
5126efc3388adb010984da2f70e1f24e8286e6476dMike Stump  DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
522b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
532b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner
542b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris LattnerCodeGenModule::~CodeGenModule() {
55815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete Runtime;
56815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek  delete DebugInfo;
57815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek}
58815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenek
59815c78fd9ab8bd5dfe8e8a91b8c6a413e2b8c889Ted Kremenekvoid CodeGenModule::Release() {
600269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitDeferred();
61219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  EmitAliases();
62208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar  if (Runtime)
63208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64208ff5e8a073de2a5d15cbe03cab8a4c0d935e28Daniel Dunbar      AddGlobalCtor(ObjCInitFunction);
656bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalCtors, "llvm.global_ctors");
666bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  EmitCtorList(GlobalDtors, "llvm.global_dtors");
67532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  EmitAnnotations();
680269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  EmitLLVMUsed();
69b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar  BindRuntimeGlobals();
702b94fe35edf951a14ecd32b21f7ebcc2e3754c67Chris Lattner}
715f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
72b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbarvoid CodeGenModule::BindRuntimeGlobals() {
73f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar  // Deal with protecting runtime function names.
74b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar  for (unsigned i = 0, e = RuntimeGlobals.size(); i < e; ++i) {
75b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar    llvm::GlobalValue *GV = RuntimeGlobals[i].first;
76b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar    const std::string &Name = RuntimeGlobals[i].second;
77f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
78b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar    // Discard unused runtime declarations.
79b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar    if (GV->isDeclaration() && GV->use_empty()) {
80b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar      GV->eraseFromParent();
810293d540baafbe070c1035611787a81001a4118eDaniel Dunbar      continue;
820293d540baafbe070c1035611787a81001a4118eDaniel Dunbar    }
830293d540baafbe070c1035611787a81001a4118eDaniel Dunbar
84e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // See if there is a conflict against a function by setting the name and
85e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // seeing if we got the desired name.
86e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    GV->setName(Name);
87e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    if (GV->isName(Name.c_str()))
88e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      continue;  // Yep, it worked!
89e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner
90e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    GV->setName(""); // Zap the bogus name until we work out the conflict.
91b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar    llvm::GlobalValue *Conflict = TheModule.getNamedValue(Name);
92e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    assert(Conflict && "Must have conflicted!");
93e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner
94e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // Decide which version to take. If the conflict is a definition
95e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // we are forced to take that, otherwise assume the runtime
96e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // knows best.
97b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar
98e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // FIXME: This will fail phenomenally when the conflict is the
99e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // wrong type of value. Just bail on it for now. This should
100e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    // really reuse something inside the LLVM Linker code.
101e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    assert(GV->getValueID() == Conflict->getValueID() &&
102e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner           "Unable to resolve conflict between globals of different types.");
103e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    if (!Conflict->isDeclaration()) {
104e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      llvm::Value *Casted =
105e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner        llvm::ConstantExpr::getBitCast(Conflict, GV->getType());
106e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      GV->replaceAllUsesWith(Casted);
107e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      GV->eraseFromParent();
108e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    } else {
109e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      GV->takeName(Conflict);
110e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      llvm::Value *Casted =
111e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner        llvm::ConstantExpr::getBitCast(GV, Conflict->getType());
112e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      Conflict->replaceAllUsesWith(Casted);
113e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner      Conflict->eraseFromParent();
114e21c4b829c9e69c20f4baab4916e05cdb786d9aeChris Lattner    }
115f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar  }
116f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
117f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
118488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
1192c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner/// specified stmt yet.
12090df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
12190df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
12290df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
12390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
124488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
12556b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
1262c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner  std::string Msg = Type;
1270a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
1280a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner    << Msg << S->getSourceRange();
1292c8569d5f43f7de1fb993e84c95ea571dd9ac55eChris Lattner}
13058c3f9ec11cbe852a518bf2f83af46f938b7b852Chris Lattner
131488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar/// ErrorUnsupported - Print out an error that codegen doesn't support the
132c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner/// specified decl yet.
13390df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbarvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
13490df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar                                     bool OmitOnError) {
13590df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar  if (OmitOnError && getDiags().hasErrorOccurred())
13690df4b6661968a84bf64baee489bb2f6d948fcc1Daniel Dunbar    return;
137488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
13856b8001b42bd603ef593e3cb278d8b9b9ba26ca9Daniel Dunbar                                               "cannot compile this %0 yet");
139c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner  std::string Msg = Type;
1400a14eee528a901c16f0e288fbc10a3abc1660d87Chris Lattner  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
141c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner}
142c6fdc34ac0183bfa03d65f317c78b7bdac52897eChris Lattner
14341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// setGlobalVisibility - Set the visibility for the given LLVM
14441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// GlobalValue according to the given clang AST visibility value.
14541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarstatic void setGlobalVisibility(llvm::GlobalValue *GV,
14641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar                                VisibilityAttr::VisibilityTypes Vis) {
1474f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman  switch (Vis) {
1484f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman  default: assert(0 && "Unknown visibility!");
1494f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman  case VisibilityAttr::DefaultVisibility:
1504f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1514f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    break;
1524f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman  case VisibilityAttr::HiddenVisibility:
1534f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1544f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    break;
1554f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman  case VisibilityAttr::ProtectedVisibility:
1564f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
1574f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman    break;
1584f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman  }
1594f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman}
1604f8d123e3e2c260de3377208106ddba87cee28b4Dan Gohman
1615f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// \brief Retrieves the mangled name for the given declaration.
1625f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor///
1635f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// If the given declaration requires a mangled name, returns an
164c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner/// const char* containing the mangled name.  Otherwise, returns
165c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner/// the unmangled name.
1665f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor///
1675f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// FIXME: Returning an IdentifierInfo* here is a total hack. We
1685f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// really need some kind of string abstraction that either stores a
1695f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// mangled name or stores an IdentifierInfo*. This will require
170b5da3e94b72a0106abd69c2a84bf650e773fa4acDaniel Dunbar/// changes to the GlobalDeclMap, too. (I disagree, I think what we
171b5da3e94b72a0106abd69c2a84bf650e773fa4acDaniel Dunbar/// actually need is for Sema to provide some notion of which Decls
172b5da3e94b72a0106abd69c2a84bf650e773fa4acDaniel Dunbar/// refer to the same semantic decl. We shouldn't need to mangle the
173b5da3e94b72a0106abd69c2a84bf650e773fa4acDaniel Dunbar/// names and see what comes out the same to figure this out. - DWD)
1745f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor///
1755f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// FIXME: Performance here is going to be terribly until we start
1765f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// caching mangled names. However, we should fix the problem above
1775f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor/// first.
1786ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregorconst char *CodeGenModule::getMangledName(const NamedDecl *ND) {
179c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  // In C, functions with no attributes never need to be mangled. Fastpath them.
180c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
181c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
1823c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    return ND->getNameAsCString();
183c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner  }
184c50689bd1e8788a7fc8f19070b7505ff95034979Chris Lattner
1856ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  llvm::SmallString<256> Name;
1866ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  llvm::raw_svector_ostream Out(Name);
187fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar  if (!mangleName(ND, Context, Out)) {
188fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
1893c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner    return ND->getNameAsCString();
190fe345572459b69a6b680322fef504b4f8bd98dd7Daniel Dunbar  }
1915f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
1926ec3668a2608b63473207319f5ceff9bbd22ea51Douglas Gregor  Name += '\0';
1933c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner  return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData();
1945f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor}
1955f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor
1966d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// AddGlobalCtor - Add a function to the list that will be called before
1976d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner/// main() runs.
1986bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
19949988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
2006bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
2016d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
2026d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
2036bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// AddGlobalDtor - Add a function to the list that will be called
2046bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar/// when the module is unloaded.
2056bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
20649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Type coercion of void()* types.
2076bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
2086bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar}
2096bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2106bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbarvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
2116bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Ctor function type is void()*.
2126bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  llvm::FunctionType* CtorFTy =
2136bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    llvm::FunctionType::get(llvm::Type::VoidTy,
2146bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                            std::vector<const llvm::Type*>(),
2156bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                            false);
2166bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
2176bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2186bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Get the type of a ctor entry, { i32, void ()* }.
219572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner  llvm::StructType* CtorStructTy =
2206bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    llvm::StructType::get(llvm::Type::Int32Ty,
2216bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                          llvm::PointerType::getUnqual(CtorFTy), NULL);
2226bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2236bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  // Construct the constructor and destructor arrays.
2246bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  std::vector<llvm::Constant*> Ctors;
2256bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
2266bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    std::vector<llvm::Constant*> S;
2276bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
2286bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
2296bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
2306bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  }
2316bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar
2326bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar  if (!Ctors.empty()) {
2336bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
2346bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar    new llvm::GlobalVariable(AT, false,
235572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             llvm::GlobalValue::AppendingLinkage,
2366bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                             llvm::ConstantArray::get(AT, Ctors),
2376bfed7e411adc46eaf616371f85f68305c6e6257Daniel Dunbar                             GlobalName,
238572cf09ae8a78af1c56d40b016ec4cf1837163acChris Lattner                             &TheModule);
2396d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner  }
2406d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner}
2416d39760673df2e92d9293f46ff8c66dad6ab5e0aChris Lattner
242532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begemanvoid CodeGenModule::EmitAnnotations() {
243532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  if (Annotations.empty())
244532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman    return;
245532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
246532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  // Create a new global variable for the ConstantStruct in the Module.
247532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::Constant *Array =
248532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
249532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                                                Annotations.size()),
250532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           Annotations);
251532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  llvm::GlobalValue *gv =
252532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  new llvm::GlobalVariable(Array->getType(), false,
253532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           llvm::GlobalValue::AppendingLinkage, Array,
254532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman                           "llvm.global.annotations", &TheModule);
255532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman  gv->setSection("llvm.metadata");
256532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman}
257532485cc6c078d9e51b517c6bbd8984deb17f0feNate Begeman
2585c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbarvoid CodeGenModule::SetGlobalValueAttributes(const Decl *D,
2595c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar                                             bool IsInternal,
2605c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar                                             bool IsInline,
2615c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar                                             llvm::GlobalValue *GV,
2625c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar                                             bool ForDefinition) {
26349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Set up linkage and many other things.  Note, this is a simple
264d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes  // approximation of what we really want.
265219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  if (!ForDefinition) {
266219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // Only a few attributes are set on declarations.
2672f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov    if (D->getAttr<DLLImportAttr>()) {
2682f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov      // The dllimport attribute is overridden by a subsequent declaration as
2692f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov      // dllexport.
2703ef5db646a6f66bb23146c3e506c294f31adf018Sebastian Redl      if (!D->getAttr<DLLExportAttr>()) {
2712f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov        // dllimport attribute can be applied only to function decls, not to
2722f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov        // definitions.
2732f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2742f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov          if (!FD->getBody())
2752f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov            GV->setLinkage(llvm::Function::DLLImportLinkage);
2762f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov        } else
2772f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov          GV->setLinkage(llvm::Function::DLLImportLinkage);
2783ef5db646a6f66bb23146c3e506c294f31adf018Sebastian Redl      }
2795e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar    } else if (D->getAttr<WeakAttr>() ||
2805e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar               D->getAttr<WeakImportAttr>()) {
2815e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar      // "extern_weak" is overloaded in LLVM; we probably should have
2825e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar      // separate linkage types for this.
283e3fedbeee8a014cd4f4e7cad8e7f6059eae12410Duncan Sands      GV->setLinkage(llvm::Function::ExternalWeakLinkage);
2845e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar   }
285219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  } else {
286219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    if (IsInternal) {
287219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      GV->setLinkage(llvm::Function::InternalLinkage);
288219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    } else {
2892f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov      if (D->getAttr<DLLExportAttr>()) {
2902f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2912f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov          // The dllexport attribute is ignored for undefined symbols.
2922f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov          if (FD->getBody())
2932f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov            GV->setLinkage(llvm::Function::DLLExportLinkage);
2942f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov        } else
2952f402708e62f89fb875442802e3d3f20fc909d33Anton Korobeynikov          GV->setLinkage(llvm::Function::DLLExportLinkage);
2965e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar      } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
2975e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar                 IsInline)
298286acbdbe0c82e9a6bcad5fca3c4fa582f3f1a2cMike Stump        GV->setLinkage(llvm::Function::WeakAnyLinkage);
299219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    }
3000dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar  }
301d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
30249988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // FIXME: Figure out the relative priority of the attribute,
30349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar  // -fvisibility, and private_extern.
3040dbe227feccf6a8dbadfff8ca3f80416b7bf2f28Daniel Dunbar  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
30541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    setGlobalVisibility(GV, attr->getVisibility());
306d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes  // FIXME: else handle -fvisibility
307a735ad8be5536a1cd3e9817ec27dfeb2a0c1d5caDaniel Dunbar
30817f194f4393a67fd28ad822c06d32b8cb99bad3fDaniel Dunbar  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
30917f194f4393a67fd28ad822c06d32b8cb99bad3fDaniel Dunbar    GV->setSection(SA->getName());
3105c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar
3115c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // Only add to llvm.used when we see a definition, otherwise we
3125c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // might add multiple times or risk the value being replaced by a
3135c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // subsequent RAUW.
3145c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  if (ForDefinition) {
3155c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar    if (D->getAttr<UsedAttr>())
3165c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar      AddUsedGlobal(GV);
3175c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  }
318d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes}
319d4cbda6292b321c2e7dce7f039d92918fee99b3aNuno Lopes
320761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patelvoid CodeGenModule::SetFunctionAttributes(const Decl *D,
32145c25ba11cbf8c9a461def5b03f6ee9481e06769Daniel Dunbar                                          const CGFunctionInfo &Info,
322b768807c49a1c7085def099b848631856af766faDaniel Dunbar                                          llvm::Function *F) {
323761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  AttributeListType AttributeList;
32488b5396b0897f28d22ae3debf4a0d97b33b6c362Daniel Dunbar  ConstructAttributeList(Info, D, AttributeList);
325c134fcb0d7989fe6937e47e6216637647e074aefEli Friedman
326761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
327761d7f78e2dac7ea5f35828c2271e60d91e106ceDevang Patel                                        AttributeList.size()));
328ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman
329ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman  // Set the appropriate calling convention for the Function.
33045c25ba11cbf8c9a461def5b03f6ee9481e06769Daniel Dunbar  if (D->getAttr<FastCallAttr>())
331f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov    F->setCallingConv(llvm::CallingConv::X86_FastCall);
332f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov
333f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov  if (D->getAttr<StdCallAttr>())
334f1c9c09e2e2220e4bbfb7e9d8adf9bf2c2406b80Anton Korobeynikov    F->setCallingConv(llvm::CallingConv::X86_StdCall);
335f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
336f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
337f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar/// SetFunctionAttributesForDefinition - Set function attributes
338f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar/// specific to a function definition.
339219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbarvoid CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
340219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar                                                       llvm::Function *F) {
341219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  if (isa<ObjCMethodDecl>(D)) {
342219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    SetGlobalValueAttributes(D, true, false, F, true);
343219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  } else {
344219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    const FunctionDecl *FD = cast<FunctionDecl>(D);
345219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
346219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar                             FD->isInline(), F, true);
347219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  }
348219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
34974ac74ae244c501027924c99f2a33559a1e23b53Daniel Dunbar  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
350f93349f3ec4d69eafba42436c33aaa91bfca7e70Daniel Dunbar    F->addFnAttr(llvm::Attribute::NoUnwind);
351af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar
352af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar  if (D->getAttr<AlwaysInlineAttr>())
353af668b0e7d3581dea3b4f29a9262686e83887e5bDaniel Dunbar    F->addFnAttr(llvm::Attribute::AlwaysInline);
35481ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson
35581ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson  if (D->getAttr<NoinlineAttr>())
35681ebbde0fb30a40df0f5e913d8a1f71c383d271aAnders Carlsson    F->addFnAttr(llvm::Attribute::NoInline);
357f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
358f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
359f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbarvoid CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
360f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar                                        llvm::Function *F) {
361541b63b1a9db77e4a8670e9823711c2c12e58afbDaniel Dunbar  SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
362f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
363219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  SetFunctionAttributesForDefinition(MD, F);
364f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar}
365f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar
366f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbarvoid CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
367f80519b919a348db004fba18530706314d1ebfb5Daniel Dunbar                                          llvm::Function *F) {
368541b63b1a9db77e4a8670e9823711c2c12e58afbDaniel Dunbar  SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
36945c25ba11cbf8c9a461def5b03f6ee9481e06769Daniel Dunbar
370219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
371219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar                           FD->isInline(), F, false);
372219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar}
373219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
37445c25ba11cbf8c9a461def5b03f6ee9481e06769Daniel Dunbar
375219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbarvoid CodeGenModule::EmitAliases() {
376219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
3775e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar    const ValueDecl *D = Aliases[i];
378219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    const AliasAttr *AA = D->getAttr<AliasAttr>();
379219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
380219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // This is something of a hack, if the FunctionDecl got overridden
381219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // then its attributes will be moved to the new declaration. In
382219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // this case the current decl has no alias attribute, but we will
383219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // eventually see it.
384219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    if (!AA)
385219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      continue;
386219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
387219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    const std::string& aliaseeName = AA->getAliasee();
3885e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar    llvm::GlobalValue *aliasee = getModule().getNamedValue(aliaseeName);
389219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    if (!aliasee) {
390219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      // FIXME: This isn't unsupported, this is just an error, which
391219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      // sema should catch, but...
392219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      ErrorUnsupported(D, "alias referencing a missing function");
393219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      continue;
394219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    }
395219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
3965d4f5c724533b994de05df49ae259120482ec366Chris Lattner    const char *MangledName = getMangledName(D);
397219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    llvm::GlobalValue *GA =
398219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      new llvm::GlobalAlias(aliasee->getType(),
399219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar                            llvm::Function::ExternalLinkage,
4005d4f5c724533b994de05df49ae259120482ec366Chris Lattner                            MangledName, aliasee, &getModule());
401219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
4025d4f5c724533b994de05df49ae259120482ec366Chris Lattner    llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
403219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    if (Entry) {
404219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      // If we created a dummy function for this then replace it.
405219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      GA->takeName(Entry);
406219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
407219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      llvm::Value *Casted =
408219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar        llvm::ConstantExpr::getBitCast(GA, Entry->getType());
409219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      Entry->replaceAllUsesWith(Casted);
410219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      Entry->eraseFromParent();
411ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman
412219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      Entry = GA;
413219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    }
414219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
415219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    // Alias should never be internal or inline.
416219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    SetGlobalValueAttributes(D, false, false, GA, true);
417219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  }
418ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman}
419ff4a2d9e2c1ddbf87e00e2a36ae341faf03eafb3Eli Friedman
4200269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
4210269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  assert(!GV->isDeclaration() &&
4220269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         "Only globals with definition can force usage.");
4230269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
4240269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
4250269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
4260269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4270269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitLLVMUsed() {
4280269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Don't create llvm.used if there is no need.
4290269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  if (LLVMUsed.empty())
4300269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    return;
4310269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4320269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
4330269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                                              LLVMUsed.size());
4340269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  llvm::GlobalVariable *GV =
4350269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    new llvm::GlobalVariable(ATy, false,
4360269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::GlobalValue::AppendingLinkage,
4370269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             llvm::ConstantArray::get(ATy, LLVMUsed),
4380269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar                             "llvm.used", &getModule());
4390269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4400269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  GV->setSection("llvm.metadata");
4410269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar}
4420269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar
4430269871c9cba493f76237175ab60313406f3bafaDaniel Dunbarvoid CodeGenModule::EmitDeferred() {
4440269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // Emit code for any deferred decl which was used.  Since a
4450269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // previously unused static decl may become used during the
4460269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // generation of code for a static function, iterate until no
4470269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  // changes are made.
4484c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  bool Changed;
4494c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  do {
4504c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman    Changed = false;
451b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson
4520269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
4530269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar         e = DeferredDecls.end(); i != e; ) {
454b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson      const ValueDecl *D = *i;
455b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson
4566f7e2eee917a136ffc36834f020782b3f15d8fa6Eli Friedman      // Check if we have used a decl with the same name
4576f7e2eee917a136ffc36834f020782b3f15d8fa6Eli Friedman      // FIXME: The AST should have some sort of aggregate decls or
4586f7e2eee917a136ffc36834f020782b3f15d8fa6Eli Friedman      // global symbol map.
459219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar      // FIXME: This is missing some important cases. For example, we
46073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      // need to check for uses in an alias.
4615f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor      if (!GlobalDeclMap.count(getMangledName(D))) {
462232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar        ++i;
463a735ad8be5536a1cd3e9817ec27dfeb2a0c1d5caDaniel Dunbar        continue;
464b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson      }
465b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson
466bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar      // Emit the definition.
467bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar      EmitGlobalDefinition(D);
468bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
4694c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman      // Erase the used decl from the list.
4700269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar      i = DeferredDecls.erase(i);
471b723f7520bcce5f13ccaae557c16a1e7133b6908Anders Carlsson
4724c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman      // Remember that we made a change.
4734c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman      Changed = true;
4744c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman    }
4754c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  } while (Changed);
4765f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
4775f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
4788bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
4798bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// annotation information for a given GlobalValue.  The annotation struct is
4808bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
4813c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar/// GlobalValue being annotated.  The second field is the constant string
4828bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// created from the AnnotateAttr's annotation.  The third field is a constant
4838bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// string containing the name of the translation unit.  The fourth field is
4848bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// the line number in the file of the annotated value declaration.
4858bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///
4868bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman/// FIXME: this does not unique the annotation string constants, as llvm-gcc
4878bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///        appears to.
4888bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman///
4898bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begemanllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
4908bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                const AnnotateAttr *AA,
4918bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                unsigned LineNo) {
4928bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Module *M = &getModule();
4938bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
4948bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // get [N x i8] constants for the annotation string, and the filename string
4958bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // which are the 2nd and 3rd elements of the global annotation structure.
4968bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
4978bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
4988bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
4998bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                                                  true);
5008bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
5018bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // Get the two global values corresponding to the ConstantArrays we just
5028bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // created to hold the bytes of the strings.
5038bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::GlobalValue *annoGV =
5048bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  new llvm::GlobalVariable(anno->getType(), false,
5058bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                           llvm::GlobalValue::InternalLinkage, anno,
5068bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                           GV->getName() + ".str", M);
5078bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // translation unit name string, emitted into the llvm.metadata section.
5088bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::GlobalValue *unitGV =
5098bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  new llvm::GlobalVariable(unit->getType(), false,
5108bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman                           llvm::GlobalValue::InternalLinkage, unit, ".str", M);
5118bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
5128bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  // Create the ConstantStruct that is the global annotion.
5138bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  llvm::Constant *Fields[4] = {
5148bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantExpr::getBitCast(GV, SBP),
5158bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantExpr::getBitCast(annoGV, SBP),
5168bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantExpr::getBitCast(unitGV, SBP),
5178bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
5188bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  };
5198bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  return llvm::ConstantStruct::get(Fields, 4, false);
5208bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman}
5218bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
52273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbarbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
5235c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // Never defer when EmitAllDecls is specified or the decl has
5245c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  // attribute used.
5255c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
52673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    return false;
527bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
528bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
52973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Constructors and destructors should never be deferred.
53073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
53173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return false;
53273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
53399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // FIXME: What about inline, and/or extern inline?
53473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    if (FD->getStorageClass() != FunctionDecl::Static)
53573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return false;
53673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  } else {
53773241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
53899b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    assert(VD->isFileVarDecl() && "Invalid decl");
53973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
54073241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    if (VD->getStorageClass() != VarDecl::Static)
54173241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return false;
54273241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  }
54373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
54473241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  return true;
54573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar}
54673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar
54773241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbarvoid CodeGenModule::EmitGlobal(const ValueDecl *Global) {
5485e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  // Aliases are deferred until code for everything else has been
5495e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  // emitted.
5505e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (Global->getAttr<AliasAttr>()) {
5515e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar    Aliases.push_back(Global);
5525e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar    return;
5535e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  }
554219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
5555e1e1f95c98b1add70c238093bbd5dc8d4f9c4e9Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
55673241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
55773241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    if (!FD->isThisDeclarationADefinition())
55873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
5590269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar  } else {
5600269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    const VarDecl *VD = cast<VarDecl>(Global);
561bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
562bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
56373241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar    // Forward declarations are emitted lazily on first use.
5647542bca16b63c84e401b44b586ac3378aed446c5Daniel Dunbar    if (!VD->getInit() && VD->hasExternalStorage())
56573241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar      return;
5664c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman  }
5674c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
56873241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  // Defer code generation when possible.
56973241dfeb5c498255b662984cca369fd28ec3147Daniel Dunbar  if (MayDeferGeneration(Global)) {
5700269871c9cba493f76237175ab60313406f3bafaDaniel Dunbar    DeferredDecls.push_back(Global);
571bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    return;
572bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
573bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
574bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  // Otherwise emit the definition.
575bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  EmitGlobalDefinition(Global);
5764c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman}
5774c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman
578bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
579bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
580bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    EmitGlobalFunctionDefinition(FD);
581bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
582bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    EmitGlobalVarDefinition(VD);
583bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  } else {
584bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    assert(0 && "Invalid argument to EmitGlobalDefinition()");
585bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
586bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
587bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
5889986eabd4423d867262c358ca62f94a60ac58412Daniel Dunbar llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
58977ba708819285931932ecd33691a672bb59d221aEli Friedman  assert(D->hasGlobalStorage() && "Not a global variable");
59077ba708819285931932ecd33691a672bb59d221aEli Friedman
591bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  QualType ASTTy = D->getType();
592bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
593bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
5943c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
5955d4f5c724533b994de05df49ae259120482ec366Chris Lattner  const char *MangledName = getMangledName(D);
5965d4f5c724533b994de05df49ae259120482ec366Chris Lattner  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
59799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (Entry) {
59899b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
59999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner
60099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    // Make sure the result is of the correct type.
60199b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    if (Entry->getType() != PTy)
60299b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner      return llvm::ConstantExpr::getBitCast(Entry, PTy);
60399b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    return Entry;
60499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  }
60599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner
60699b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  llvm::GlobalVariable *GV =
60799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    new llvm::GlobalVariable(Ty, false,
60899b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             llvm::GlobalValue::ExternalLinkage,
6095d4f5c724533b994de05df49ae259120482ec366Chris Lattner                             0, MangledName, &getModule(),
61099b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner                             0, ASTTy.getAddressSpace());
61149988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
61299b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // Handle things which are present even on external declarations.
61349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
61499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // FIXME: This code is overly simple and should be merged with
61599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // other global handling.
61649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
61799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  GV->setConstant(D->getType().isConstant(Context));
61849988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
61999b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  // FIXME: Merge with other attribute handling code.
620eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
62199b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (D->getStorageClass() == VarDecl::PrivateExtern)
62299b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
623eda9a5ec380f172f4e0063744eb796144a125480Daniel Dunbar
62499b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
62599b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner    GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
6263f75c43bd77e063342bc888ac276daf64ba0ce07Daniel Dunbar
62799b53613ebe2c59d41030e987962c1ed101b2efeChris Lattner  return Entry = GV;
628bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
629bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
630bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
6318f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  llvm::Constant *Init = 0;
63277ba708819285931932ecd33691a672bb59d221aEli Friedman  QualType ASTTy = D->getType();
63377ba708819285931932ecd33691a672bb59d221aEli Friedman  const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
63477ba708819285931932ecd33691a672bb59d221aEli Friedman
6358f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  if (D->getInit() == 0) {
636cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // This is a tentative definition; tentative definitions are
637cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // implicitly initialized with { 0 }
6382d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner    const llvm::Type *InitTy = VarTy;
639cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    if (ASTTy->isIncompleteArrayType()) {
640cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman      // An incomplete array is normally [ TYPE x 0 ], but we need
641cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman      // to fix it to [ TYPE x 1 ].
642cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman      const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
643cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman      InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
644cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    }
645cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    Init = llvm::Constant::getNullValue(InitTy);
64677ba708819285931932ecd33691a672bb59d221aEli Friedman  } else {
647bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar    Init = EmitConstantExpr(D->getInit());
6486e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    if (!Init) {
649232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar      ErrorUnsupported(D, "static initializer");
6506e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman      QualType T = D->getInit()->getType();
6516e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman      Init = llvm::UndefValue::get(getTypes().ConvertType(T));
6526e656f45ae04b415ba7a4c0c25e55633e2d0ecd0Eli Friedman    }
6538f32f7189b12f67aa4a19bc7c3855b599980eca0Chris Lattner  }
6548e53e720b3d7c962e91138a130dbd5d6c2def0e5Devang Patel
6552d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner  const llvm::Type* InitType = Init->getType();
6565d4f5c724533b994de05df49ae259120482ec366Chris Lattner  const char *MangledName = getMangledName(D);
6575d4f5c724533b994de05df49ae259120482ec366Chris Lattner  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
6583c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
6593c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar
66077ba708819285931932ecd33691a672bb59d221aEli Friedman  if (!GV) {
66177ba708819285931932ecd33691a672bb59d221aEli Friedman    GV = new llvm::GlobalVariable(InitType, false,
66277ba708819285931932ecd33691a672bb59d221aEli Friedman                                  llvm::GlobalValue::ExternalLinkage,
6635d4f5c724533b994de05df49ae259120482ec366Chris Lattner                                  0, MangledName,
6645f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor                                  &getModule(), 0, ASTTy.getAddressSpace());
665232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
666232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar  } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
667232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // If we already have this global and it has an initializer, then
668232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // we are in the rare situation where we emitted the defining
669232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // declaration of the global and are now being asked to emit a
670232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // definition which would be common. This occurs, for example, in
671232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // the following situation because statics can be emitted out of
672232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // order:
673232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    //
674232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    //  static int x;
675232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    //  static int *y = &x;
676232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    //  static int x = 10;
677232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    //  int **z = &y;
678232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    //
679232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // Bail here so we don't blow away the definition. Note that if we
680232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // can't distinguish here if we emitted a definition with a null
681232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    // initializer, but this case is safe.
682232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    assert(!D->getInit() && "Emitting multiple definitions of a decl!");
683232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar    return;
684232350d4faf46ec38d5ff60e11505f9c4fa9535bDaniel Dunbar
6853c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  } else if (GV->getType() !=
6863c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar             llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
68777ba708819285931932ecd33691a672bb59d221aEli Friedman    // We have a definition after a prototype with the wrong type.
68877ba708819285931932ecd33691a672bb59d221aEli Friedman    // We must make a new GlobalVariable* and update everything that used OldGV
68977ba708819285931932ecd33691a672bb59d221aEli Friedman    // (a declaration or tentative definition) with the new GlobalVariable*
69077ba708819285931932ecd33691a672bb59d221aEli Friedman    // (which will be a definition).
69177ba708819285931932ecd33691a672bb59d221aEli Friedman    //
6922d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner    // This happens if there is a prototype for a global (e.g.
6932d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner    // "extern int x[];") and then a definition of a different type (e.g.
6942d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner    // "int x[10];"). This also happens when an initializer has a different type
6952d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner    // from the type of the global (this happens with unions).
696cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    //
697cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // FIXME: This also ends up happening if there's a definition followed by
698cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // a tentative definition!  (Although Sema rejects that construct
699cd5f4aaf0c219189878126d556f35e38fdb8afa1Eli Friedman    // at the moment.)
70077ba708819285931932ecd33691a672bb59d221aEli Friedman
70177ba708819285931932ecd33691a672bb59d221aEli Friedman    // Save the old global
70277ba708819285931932ecd33691a672bb59d221aEli Friedman    llvm::GlobalVariable *OldGV = GV;
70377ba708819285931932ecd33691a672bb59d221aEli Friedman
70477ba708819285931932ecd33691a672bb59d221aEli Friedman    // Make a new global with the correct type
70577ba708819285931932ecd33691a672bb59d221aEli Friedman    GV = new llvm::GlobalVariable(InitType, false,
70677ba708819285931932ecd33691a672bb59d221aEli Friedman                                  llvm::GlobalValue::ExternalLinkage,
7075d4f5c724533b994de05df49ae259120482ec366Chris Lattner                                  0, MangledName,
7085f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor                                  &getModule(), 0, ASTTy.getAddressSpace());
70977ba708819285931932ecd33691a672bb59d221aEli Friedman    // Steal the name of the old global
71077ba708819285931932ecd33691a672bb59d221aEli Friedman    GV->takeName(OldGV);
71177ba708819285931932ecd33691a672bb59d221aEli Friedman
71277ba708819285931932ecd33691a672bb59d221aEli Friedman    // Replace all uses of the old global with the new global
71377ba708819285931932ecd33691a672bb59d221aEli Friedman    llvm::Constant *NewPtrForOldDecl =
71477ba708819285931932ecd33691a672bb59d221aEli Friedman        llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
71577ba708819285931932ecd33691a672bb59d221aEli Friedman    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
71677ba708819285931932ecd33691a672bb59d221aEli Friedman
71777ba708819285931932ecd33691a672bb59d221aEli Friedman    // Erase the old global, since it is no longer used.
7182d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner    // FIXME: What if it was attribute used?  Dangling pointer from LLVMUsed.
71977ba708819285931932ecd33691a672bb59d221aEli Friedman    OldGV->eraseFromParent();
72077ba708819285931932ecd33691a672bb59d221aEli Friedman  }
72177ba708819285931932ecd33691a672bb59d221aEli Friedman
7223c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  Entry = GV;
7239e32d4b4a7270a9701b7cb454381eeaa4cc42a77Devang Patel
7248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
7258bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    SourceManager &SM = Context.getSourceManager();
7268bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman    AddAnnotation(EmitAnnotateAttr(GV, AA,
727f7cf85b330bedd2877e1371fb0a83e99751ae162Chris Lattner                              SM.getInstantiationLineNumber(D->getLocation())));
7288bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman  }
7298bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
73088a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  GV->setInitializer(Init);
731b381aac9bae6d608c72267dd0ed08ec6369e94e4Nuno Lopes  GV->setConstant(D->getType().isConstant(Context));
7320de40af3a3aa14e3854c0eafeabd08f6762801f9Eli Friedman  GV->setAlignment(getContext().getDeclAlignInBytes(D));
73308d7802a406ee4a7cc18e8fce0c137b8c410ea7cEli Friedman
734ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
73541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    setGlobalVisibility(GV, attr->getVisibility());
736ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner  // FIXME: else handle -fvisibility
737a735ad8be5536a1cd3e9817ec27dfeb2a0c1d5caDaniel Dunbar
73888a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  // Set the llvm linkage type as appropriate.
7398fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner  if (D->getStorageClass() == VarDecl::Static)
7408fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner    GV->setLinkage(llvm::Function::InternalLinkage);
7418fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner  else if (D->getAttr<DLLImportAttr>())
742ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    GV->setLinkage(llvm::Function::DLLImportLinkage);
743ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner  else if (D->getAttr<DLLExportAttr>())
744ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    GV->setLinkage(llvm::Function::DLLExportLinkage);
7455e27314eb5a9cba7997cf9f6fc82428d99667077Daniel Dunbar  else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
746286acbdbe0c82e9a6bcad5fca3c4fa582f3f1a2cMike Stump    GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
7478fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner  else {
748ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    // FIXME: This isn't right.  This should handle common linkage and other
749ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    // stuff.
750ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    switch (D->getStorageClass()) {
7518fabd78f1976243cb223fb3e969c6f317d1ae44dChris Lattner    case VarDecl::Static: assert(0 && "This case handled above");
752ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    case VarDecl::Auto:
753ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    case VarDecl::Register:
754ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner      assert(0 && "Can't have auto or register globals");
755ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    case VarDecl::None:
756ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner      if (!D->getInit())
757ceb77d909f80d4949ee6177094510413c391cddcDuncan Sands        GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
75898883e1e699457697fb8d5ac6d175dd3ee078774Anders Carlsson      else
75998883e1e699457697fb8d5ac6d175dd3ee078774Anders Carlsson        GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
760ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner      break;
761ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    case VarDecl::Extern:
76249988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar      // FIXME: common
76349988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar      break;
76449988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar
765ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    case VarDecl::PrivateExtern:
76649988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
76749988884c1da4b2200bfe2298a1e41b3f044e8d4Daniel Dunbar      // FIXME: common
768ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner      break;
769ddee4231e9bdfbac1e1f5385ff1a17fd0e0b0e39Chris Lattner    }
77088a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner  }
771686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta
77217f194f4393a67fd28ad822c06d32b8cb99bad3fDaniel Dunbar  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
77317f194f4393a67fd28ad822c06d32b8cb99bad3fDaniel Dunbar    GV->setSection(SA->getName());
77417f194f4393a67fd28ad822c06d32b8cb99bad3fDaniel Dunbar
7755c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar  if (D->getAttr<UsedAttr>())
7765c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar    AddUsedGlobal(GV);
7775c61d97ad442b2c0bbecb617c8f21857ce1fff6dDaniel Dunbar
778686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  // Emit global variable debug information.
7792d58406872e5af0c924623d9f7c194c4f09936d3Chris Lattner  if (CGDebugInfo *DI = getDebugInfo()) {
78066031a5594bc9a7dc0dc5137c3e7955f835e4639Daniel Dunbar    DI->setLocation(D->getLocation());
781686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta    DI->EmitGlobalVariable(GV, D);
782686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
78388a69ad80e1550e9932666e6efa050a5b1223889Chris Lattner}
7845f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
78562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// CreateFunctionPrototypeIR - Create a new LLVM IR Function for the given
78662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// decl and set attributes as appropriate.
78762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner///
78862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// \arg Ty - If non-null the LLVM function type to use for the
78962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// decl; it is the callers responsibility to make sure this is
79062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner/// compatible with the correct type.
791bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarllvm::GlobalValue *
79262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris LattnerCodeGenModule::CreateFunctionPrototypeIR(const FunctionDecl *D,
79362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner                                         const llvm::Type *Ty) {
79462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  bool ShouldSetAttributes = true;
7952136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman  if (!Ty) {
796d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar    Ty = getTypes().ConvertType(D->getType());
7972136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman    if (!isa<llvm::FunctionType>(Ty)) {
7982136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman      // This function doesn't have a complete type (for example, the return
7992136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman      // type is an incomplete struct). Use a fake type instead, and make
8002136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman      // sure not to try to set attributes.
8012136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman      Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
8022136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman                                   std::vector<const llvm::Type*>(), false);
80362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner      ShouldSetAttributes = false;
8042136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman    }
8052136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman  }
80642745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar  llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
80742745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar                                             llvm::Function::ExternalLinkage,
80842745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar                                             getMangledName(D),
80942745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar                                             &getModule());
81062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  if (ShouldSetAttributes)
8112136b2e9345c23c26426110873dd97ef5d761ef2Eli Friedman    SetFunctionAttributes(D, F);
812219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  return F;
813bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
814bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
815bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarllvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
8163c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  // Lookup the entry, lazily creating it if necessary.
8175f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor  llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
8183c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  if (!Entry)
81962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    return Entry = CreateFunctionPrototypeIR(D, 0);
820bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
82162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  const llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
82262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  if (Entry->getType()->getElementType() == Ty)
82362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    return Entry;
82462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
82562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
82662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  return llvm::ConstantExpr::getBitCast(Entry, PTy);
827bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
828bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
829bd012ff1fa088181646a784f385b28867372d434Daniel Dunbarvoid CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
830d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar  const llvm::FunctionType *Ty =
831d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar    cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
832d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar
833d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar  // As a special case, make sure that definitions of K&R function
834d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar  // "type foo()" aren't declared as varargs (which forces the backend
835d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar  // to do unnecessary work).
836d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar  if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
837d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar    Ty = llvm::FunctionType::get(Ty->getReturnType(),
83862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner                                 std::vector<const llvm::Type*>(), false);
839d5d31801fc87239436fa349c89dce7797cf13537Daniel Dunbar
8405f2bfd4811996abb783aa6c7254c56baa6930e8cDouglas Gregor  llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
8413c827a79cb7d04c255db8080e682ee2c6912373dDaniel Dunbar  if (!Entry) {
84262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    Entry = CreateFunctionPrototypeIR(D, Ty);
84362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner  } else if (Entry->getType()->getElementType() != Ty) {
84442745815fa4e90bfb07e581d2e5152b2c2db08ffDaniel Dunbar    // If the types mismatch then we have to rewrite the definition.
84562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
84662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // F is the Function* for the one with the wrong type, we must make a new
84762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* and update everything that used F (a declaration) with the new
84862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Function* (which will be a definition).
84962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    //
85062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // This happens if there is a prototype for a function
85162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f()") and then a definition of a different type
85262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // (e.g. "int f(int x)").  Start by making a new function of the
85362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // correct type, RAUW, then steal the name.
85462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    llvm::GlobalValue *NewFn = CreateFunctionPrototypeIR(D, Ty);
85562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    NewFn->takeName(Entry);
85662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
85762b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Replace uses of F with the Function we will endow with a body.
85862b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    llvm::Constant *NewPtrForOldDecl =
85962b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner      llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
86062b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    Entry->replaceAllUsesWith(NewPtrForOldDecl);
86162b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
86262b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    // Ok, delete the old function now, which is dead.
86362b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
86462b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    Entry->eraseFromParent();
86562b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner
86662b33ea51adbd0e7f2f05983e9e4a3a2b2ed26deChris Lattner    Entry = NewFn;
867bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
868bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
869219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  llvm::Function *Fn = cast<llvm::Function>(Entry);
870219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  CodeGenFunction(*this).GenerateCode(D, Fn);
8716379a7a15335e0af543a942efe9cfd514a83dab8Daniel Dunbar
872219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  SetFunctionAttributesForDefinition(D, Fn);
873219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar
874219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
875219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalCtor(Fn, CA->getPriority());
876219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar  } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
877219df6644e2338ff067471ab0d85f27b88544ac2Daniel Dunbar    AddGlobalDtor(Fn, DA->getPriority());
878bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar  }
879bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar}
880bd012ff1fa088181646a784f385b28867372d434Daniel Dunbar
881f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbarllvm::Function *
882f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel DunbarCodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
883f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar                                     const std::string &Name) {
884f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar  llvm::Function *Fn = llvm::Function::Create(FTy,
885f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar                                              llvm::Function::ExternalLinkage,
886f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar                                              "", &TheModule);
887b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar  RuntimeGlobals.push_back(std::make_pair(Fn, Name));
888f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar  return Fn;
889f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar}
890f1968f28869f4e0675450ae39c478a37c5b9abd6Daniel Dunbar
891b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbarllvm::GlobalVariable *
892b681b8ffab2aa016b3897916d5110927c34a584bDaniel DunbarCodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
893b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar                                     const std::string &Name) {
894b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar  llvm::GlobalVariable *GV =
895b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar    new llvm::GlobalVariable(Ty, /*Constant=*/false,
896b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar                             llvm::GlobalValue::ExternalLinkage,
897b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar                             0, "", &TheModule);
898b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar  RuntimeGlobals.push_back(std::make_pair(GV, Name));
899b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar  return GV;
900b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar}
901b681b8ffab2aa016b3897916d5110927c34a584bDaniel Dunbar
902c5b8806cda286cf41866176ef98011fdaa68da01Chris Lattnervoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
903c5b8806cda286cf41866176ef98011fdaa68da01Chris Lattner  // Make sure that this type is translated.
904c5b8806cda286cf41866176ef98011fdaa68da01Chris Lattner  Types.UpdateCompletedType(TD);
905d86e6bc7ab4388a578daf46e7c76be9122a25072Chris Lattner}
906d86e6bc7ab4388a578daf46e7c76be9122a25072Chris Lattner
907d86e6bc7ab4388a578daf46e7c76be9122a25072Chris Lattner
908bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner/// getBuiltinLibFunction
909c136e6cf237711f9f1324637a0b2cdf6ae8e79e4Mike Stumpllvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
9101426fecdf90dd1986751b9940422e675880ff671Chris Lattner  if (BuiltinID > BuiltinFunctions.size())
9111426fecdf90dd1986751b9940422e675880ff671Chris Lattner    BuiltinFunctions.resize(BuiltinID);
912bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
9131426fecdf90dd1986751b9940422e675880ff671Chris Lattner  // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
9141426fecdf90dd1986751b9940422e675880ff671Chris Lattner  // a slot for it.
9151426fecdf90dd1986751b9940422e675880ff671Chris Lattner  assert(BuiltinID && "Invalid Builtin ID");
916c136e6cf237711f9f1324637a0b2cdf6ae8e79e4Mike Stump  llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
917bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  if (FunctionSlot)
918bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    return FunctionSlot;
919bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
9203e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
9213e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
9223e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor         "isn't a lib fn");
923bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
9243e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  // Get the name, skip over the __builtin_ prefix (if necessary).
9253e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
9263e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
9273e41d60eb627dc227c770f1c1c87d06909cf05fdDouglas Gregor    Name += 10;
928bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
929bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // Get the type for the builtin.
930370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor  Builtin::Context::GetBuiltinTypeError Error;
931370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor  QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
932370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor  assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
933370ab3f1373841d70582feac9e35c3c6b3489f63Douglas Gregor
934bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  const llvm::FunctionType *Ty =
935bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner    cast<llvm::FunctionType>(getTypes().ConvertType(Type));
936bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
937bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // FIXME: This has a serious problem with code like this:
938bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  //  void abs() {}
939bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  //    ... __builtin_abs(x);
940bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // The two versions of abs will collide.  The fix is for the builtin to win,
941bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // and for the existing one to be turned into a constantexpr cast of the
942bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // builtin.  In the case where the existing one is a static function, it
943bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // should just be renamed.
944c5e940fa551840ecd71e8116c316c9131490f5faChris Lattner  if (llvm::Function *Existing = getModule().getFunction(Name)) {
945c5e940fa551840ecd71e8116c316c9131490f5faChris Lattner    if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
946c5e940fa551840ecd71e8116c316c9131490f5faChris Lattner      return FunctionSlot = Existing;
947c5e940fa551840ecd71e8116c316c9131490f5faChris Lattner    assert(Existing == 0 && "FIXME: Name collision");
948c5e940fa551840ecd71e8116c316c9131490f5faChris Lattner  }
949bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
9504667c4a309f7d49f858e14c4c2462fe595bcc536Chris Lattner  llvm::GlobalValue *&ExistingFn =
9514667c4a309f7d49f858e14c4c2462fe595bcc536Chris Lattner    GlobalDeclMap[getContext().Idents.get(Name).getName()];
9525b60a0e369521825f892d755150255645d923646Chris Lattner  assert(!ExistingFn && "Asking for the same builtin multiple times?");
953c136e6cf237711f9f1324637a0b2cdf6ae8e79e4Mike Stump
954bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner  // FIXME: param attributes for sext/zext etc.
9554667c4a309f7d49f858e14c4c2462fe595bcc536Chris Lattner  return FunctionSlot = ExistingFn =
9564c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman    llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
9574c13b7a3973d2d263d9682d7b68fbfeb76334af5Nate Begeman                           &getModule());
958bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner}
959bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
9607acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattnerllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
9617acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner                                            unsigned NumTys) {
9627acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner  return llvm::Intrinsic::getDeclaration(&getModule(),
9637acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
9647acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner}
965bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattner
9665f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerllvm::Function *CodeGenModule::getMemCpyFn() {
9675f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  if (MemCpyFn) return MemCpyFn;
9684e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
9694e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
9705f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
971c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
9720c99509927a0c7a48490486b9fec287b63e5c09cEli Friedmanllvm::Function *CodeGenModule::getMemMoveFn() {
9730c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman  if (MemMoveFn) return MemMoveFn;
9744e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
9754e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
9760c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman}
9770c99509927a0c7a48490486b9fec287b63e5c09cEli Friedman
97841ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venanciollvm::Function *CodeGenModule::getMemSetFn() {
97941ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio  if (MemSetFn) return MemSetFn;
9804e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
9814e8a9e8640a6717120394ee2ee5f27989757754dChris Lattner  return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
98241ef30e869d3f4940437503eb6a2cf70819fdb08Lauro Ramos Venancio}
9837acda7c4a0e4aec6c003b3169ca45a5f3bc7e033Chris Lattner
984e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlssonstatic void appendFieldAndPadding(CodeGenModule &CGM,
985e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson                                  std::vector<llvm::Constant*>& Fields,
98644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                                  FieldDecl *FieldD, FieldDecl *NextFieldD,
98744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                                  llvm::Constant* Field,
9883c8f153ae767fa55b2da74438c7f8ec370a06d6fChris Lattner                                  RecordDecl* RD, const llvm::StructType *STy) {
989e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  // Append the field.
990e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  Fields.push_back(Field);
991e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
99244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
993e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
994e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  int NextStructFieldNo;
99544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  if (!NextFieldD) {
996e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    NextStructFieldNo = STy->getNumElements();
997e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  } else {
99844b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
999e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  }
1000e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1001e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  // Append padding
1002e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1003e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    llvm::Constant *C =
1004e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson      llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1005e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1006e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    Fields.push_back(C);
1007e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  }
1008e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson}
1009e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
10103e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar// We still need to work out the details of handling UTF-16.
10113e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar// See: <rdr://2996215>
1012bef20ac367a09555b30d6eb3847a81ec164caf88Chris Lattnerllvm::Constant *CodeGenModule::
1013bef20ac367a09555b30d6eb3847a81ec164caf88Chris LattnerGetAddrOfConstantCFString(const std::string &str) {
1014c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  llvm::StringMapEntry<llvm::Constant *> &Entry =
1015c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1016c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1017c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (Entry.getValue())
1018c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    return Entry.getValue();
1019c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
10203e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
10213e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *Zeros[] = { Zero, Zero };
1022c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1023c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  if (!CFConstantStringClassRef) {
1024c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1025c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson    Ty = llvm::ArrayType::get(Ty, 0);
10263e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
10273e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // FIXME: This is fairly broken if
10283e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // __CFConstantStringClassReference is already defined, in that it
10293e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // will get renamed and the user will most likely see an opaque
10303e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // error message. This is a general issue with relying on
10313e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // particular names.
10323e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    llvm::GlobalVariable *GV =
1033c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson      new llvm::GlobalVariable(Ty, false,
1034c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               llvm::GlobalVariable::ExternalLinkage, 0,
1035c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               "__CFConstantStringClassReference",
1036c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               &getModule());
10373e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
10383e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    // Decay array -> ptr
10393e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar    CFConstantStringClassRef =
10403e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1041c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  }
1042c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1043e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  QualType CFTy = getContext().getCFConstantStringType();
1044e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
10453e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
1046e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  const llvm::StructType *STy =
1047e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1048e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson
1049e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  std::vector<llvm::Constant*> Fields;
105044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  RecordDecl::field_iterator Field = CFRD->field_begin();
105144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
1052c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Class pointer.
105344b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  FieldDecl *CurField = *Field++;
105444b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  FieldDecl *NextField = *Field++;
105544b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
105644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                        CFConstantStringClassRef, CFRD, STy);
1057c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1058c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // Flags.
105944b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  CurField = NextField;
106044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  NextField = *Field++;
10613e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
106244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
106344b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                        llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
1064c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1065c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String pointer.
106644b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  CurField = NextField;
106744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  NextField = *Field++;
10683e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar  llvm::Constant *C = llvm::ConstantArray::get(str);
1069c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  C = new llvm::GlobalVariable(C->getType(), true,
1070c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson                               llvm::GlobalValue::InternalLinkage,
1071e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson                               C, ".str", &getModule());
107244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
1073e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson                        llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1074e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson                        CFRD, STy);
1075c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1076c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // String length.
107744b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  CurField = NextField;
107844b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  NextField = 0;
1079c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  Ty = getTypes().ConvertType(getContext().LongTy);
108044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor  appendFieldAndPadding(*this, Fields, CurField, NextField,
108144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor                        llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
1082c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson
1083c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson  // The struct.
1084e3daa761061982f2267f7c8fb847ea02abad0aa9Anders Carlsson  C = llvm::ConstantStruct::get(STy, Fields);
10850c67829763b98bc670062b553897a851fab17401Anders Carlsson  llvm::GlobalVariable *GV =
10860c67829763b98bc670062b553897a851fab17401Anders Carlsson    new llvm::GlobalVariable(C->getType(), true,
10870c67829763b98bc670062b553897a851fab17401Anders Carlsson                             llvm::GlobalVariable::InternalLinkage,
10880c67829763b98bc670062b553897a851fab17401Anders Carlsson                             C, "", &getModule());
10893e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
10900c67829763b98bc670062b553897a851fab17401Anders Carlsson  GV->setSection("__DATA,__cfstring");
10910c67829763b98bc670062b553897a851fab17401Anders Carlsson  Entry.setValue(GV);
10923e9df9920db8de8ec93a424b0c1784f9bff301eaDaniel Dunbar
10930c67829763b98bc670062b553897a851fab17401Anders Carlsson  return GV;
1094c9e2091efcb535110474434dd12015afdc3b1637Anders Carlsson}
109545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
10966143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetStringForStringLiteral - Return the appropriate bytes for a
10971e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar/// string literal, properly padded to match the literal type.
10986143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
10991e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const char *StrData = E->getStrData();
11001e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  unsigned Len = E->getByteLength();
11011e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
11021e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  const ConstantArrayType *CAT =
11031e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar    getContext().getAsConstantArrayType(E->getType());
11041e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  assert(CAT && "String isn't pointer or array!");
11051e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
1106dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  // Resize the string to the right size.
11071e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  std::string Str(StrData, StrData+Len);
11081e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  uint64_t RealLen = CAT->getSize().getZExtValue();
1109dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner
1110dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner  if (E->isWide())
1111dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner    RealLen *= getContext().Target.getWCharWidth()/8;
1112dbb1ecc32ca122b07b7c98fd0a8f6f53985adaccChris Lattner
11131e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  Str.resize(RealLen, '\0');
11141e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
11151e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar  return Str;
11161e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar}
11171e04976fc2611d8cc06986a81deed4c42183b870Daniel Dunbar
11186143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
11196143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// constant array for the given string literal.
11206143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbarllvm::Constant *
11216143293fa4366ee95d7e47e61bd030a34bf68b55Daniel DunbarCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
11226143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // FIXME: This can be more efficient.
11236143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  return GetAddrOfConstantString(GetStringForStringLiteral(S));
11246143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
11256143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
1126eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1127eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner/// array for the given ObjCEncodeExpr node.
1128eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattnerllvm::Constant *
1129eaf2bb89eb2aad3b80673de30febe52df43c10ecChris LattnerCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1130eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  std::string Str;
1131eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1132a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman
1133a210f350fa78c263caa26e0f999cce85bb235309Eli Friedman  return GetAddrOfConstantCString(Str);
1134eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner}
1135eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1136eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner
1137a7ad98ff0919d6a24ea7c46634ea29bea551c1a0Chris Lattner/// GenerateWritableString -- Creates storage for a string literal.
113845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattnerstatic llvm::Constant *GenerateStringLiteral(const std::string &str,
113945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner                                             bool constant,
11405fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             CodeGenModule &CGM,
11415fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                             const char *GlobalName) {
11426143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  // Create Constant for this string literal. Don't add a '\0'.
11436143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar  llvm::Constant *C = llvm::ConstantArray::get(str, false);
114445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
114545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this string
1146eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner  return new llvm::GlobalVariable(C->getType(), constant,
1147eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner                                  llvm::GlobalValue::InternalLinkage,
1148eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner                                  C, GlobalName ? GlobalName : ".str",
1149eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner                                  &CGM.getModule());
115045e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
115145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
11526143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantString - Returns a pointer to a character array
11536143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// containing the literal. This contents are exactly that of the
11546143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// given string, i.e. it will not be null terminated automatically;
11556143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// see GetAddrOfConstantCString. Note that whether the result is
11566143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// actually a pointer to an LLVM constant depends on
11576143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// Feature.WriteableStrings.
11586143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar///
11596143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// The result has pointer to array type.
11605fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbarllvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
11615fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                                       const char *GlobalName) {
116245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Don't share any string literals if writable-strings is turned on.
116345e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  if (Features.WritableStrings)
11645fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar    return GenerateStringLiteral(str, false, *this, GlobalName);
116545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
116645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  llvm::StringMapEntry<llvm::Constant *> &Entry =
116745e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
116845e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
116945e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  if (Entry.getValue())
1170eaf2bb89eb2aad3b80673de30febe52df43c10ecChris Lattner    return Entry.getValue();
117145e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner
117245e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  // Create a global variable for this.
11735fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
117445e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  Entry.setValue(C);
117545e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner  return C;
117645e8cbdce25c2e16c7aac2036a591f6190097ae6Chris Lattner}
11776143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar
11786143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// GetAddrOfConstantCString - Returns a pointer to a character
11796143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// array containing the literal and a terminating '\-'
11806143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar/// character. The result has pointer to array type.
11815fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbarllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
11825fabf9dbee29464bcd06cd09f8e569d1b850f948Daniel Dunbar                                                        const char *GlobalName){
1183c9f29c61856ffb5f643cedbe87ac076f21a1381aChris Lattner  return GetAddrOfConstantString(str + '\0', GlobalName);
11846143293fa4366ee95d7e47e61bd030a34bf68b55Daniel Dunbar}
118541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1186af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// EmitObjCPropertyImplementations - Emit information for synthesized
1187af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar/// properties for an implementation.
1188af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbarvoid CodeGenModule::EmitObjCPropertyImplementations(const
1189af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar                                                    ObjCImplementationDecl *D) {
1190af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1191af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar         e = D->propimpl_end(); i != e; ++i) {
1192af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCPropertyImplDecl *PID = *i;
1193af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1194af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Dynamic is just for type-checking.
1195af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1196af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1197af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
1198af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // Determine which methods need to be implemented, some may have
1199af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // been overridden. Note that ::isSynthesized is not the method
1200af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // we want, that just indicates if the decl came from a
1201af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // property. What we want to know is if the method is defined in
1202af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      // this implementation.
1203af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!D->getInstanceMethod(PD->getGetterName()))
1204fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCGetter(
1205fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
1206af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar      if (!PD->isReadOnly() &&
1207af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar          !D->getInstanceMethod(PD->getSetterName()))
1208fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian        CodeGenFunction(*this).GenerateObjCSetter(
1209fef30b55230064d334a669a065a1c9acdb87cdfeFariborz Jahanian                                 const_cast<ObjCImplementationDecl *>(D), PID);
1210af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    }
1211af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
1212af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar}
1213af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
121441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar/// EmitTopLevelDecl - Emit code for a single top level declaration.
121541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbarvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
121641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // If an error has occurred, stop code generation, but continue
121741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // parsing and semantic analysis (to ensure all warnings and errors
121841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  // are emitted).
121941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  if (Diags.hasErrorOccurred())
122041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    return;
122141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
122241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  switch (D->getKind()) {
122341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Function:
122441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Var:
122541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    EmitGlobal(cast<ValueDecl>(D));
122641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
122741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
122841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::Namespace:
1229662174c82ef46b19a2329c7d37208e1d12dfb7b3Daniel Dunbar    ErrorUnsupported(D, "namespace");
123041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
123141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
123241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // Objective-C Decls
123341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
123438e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  // Forward declarations, no (immediate) code generation.
123541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCClass:
123641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCForwardProtocol:
123741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
123838e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian
123941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCProtocol:
124038e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  case Decl::ObjCCategory:
124138e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  case Decl::ObjCInterface: {
124238e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian    ObjCContainerDecl *OCD = cast<ObjCContainerDecl>(D);
124338e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian    for (ObjCContainerDecl::tuvar_iterator i = OCD->tuvar_begin(),
124438e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian         e = OCD->tuvar_end(); i != e; ++i) {
124538e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian        VarDecl *VD = *i;
124638e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian        EmitGlobal(VD);
124738e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian    }
124838e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian    if (D->getKind() == Decl::ObjCProtocol)
124938e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian      Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
125041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
125138e24c782c17b6058bf61d635747bbde19fb1bc7Fariborz Jahanian  }
125241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
125341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCategoryImpl:
1254af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // Categories have properties but don't support synthesize so we
1255af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    // can ignore them here.
1256af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar
125741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
125841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
125941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
1260af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  case Decl::ObjCImplementation: {
1261af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1262af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    EmitObjCPropertyImplementations(OMD);
1263af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar    Runtime->GenerateClass(OMD);
126441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
1265af05bb9073319d8381b71c4325188853fd4b8ed6Daniel Dunbar  }
126641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCMethod: {
126741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
126841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // If this is not a prototype, emit the body.
126941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (OMD->getBody())
127041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      CodeGenFunction(*this).GenerateObjCMethod(OMD);
127141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
127241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
127341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::ObjCCompatibleAlias:
1274305c658ebce84bb9833fc0e7675554656453b8e8Fariborz Jahanian    // compatibility-alias is a directive and has no code gen.
127541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
127641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
127741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::LinkageSpec: {
127841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
127941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
1280488e993a135ce700b982bf099c3d6b856301d642Daniel Dunbar      ErrorUnsupported(LSD, "linkage spec");
128141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // FIXME: implement C++ linkage, C linkage works mostly by C
128241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // language reuse already.
128341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
128441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
128541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
128641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  case Decl::FileScopeAsm: {
128741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
128841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    std::string AsmString(AD->getAsmString()->getStrData(),
128941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar                          AD->getAsmString()->getByteLength());
129041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
129141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    const std::string &S = getModule().getModuleInlineAsm();
129241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    if (S.empty())
129341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(AsmString);
129441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    else
129541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar      getModule().setModuleInlineAsm(S + '\n' + AsmString);
129641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    break;
129741071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
129841071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar
129941071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  default:
130041071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // Make sure we handled everything we should, every other kind is
130141071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // a non-top-level decl.  FIXME: Would be nice to have an
130241071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // isTopLevelDeclKind function. Need to recode Decl::Kind to do
130341071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    // that easily.
130441071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
130541071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar  }
130641071debe9b8887449c3f2ee0dd7124ed47bdda8Daniel Dunbar}
1307