CodeGenModule.cpp revision 221345
1193326Sed//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This coordinates the per-module state used while generating code.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "CodeGenModule.h"
15193326Sed#include "CGDebugInfo.h"
16193326Sed#include "CodeGenFunction.h"
17218893Sdim#include "CodeGenTBAA.h"
18193326Sed#include "CGCall.h"
19212904Sdim#include "CGCXXABI.h"
20193326Sed#include "CGObjCRuntime.h"
21202379Srdivacky#include "TargetInfo.h"
22210299Sed#include "clang/Frontend/CodeGenOptions.h"
23193326Sed#include "clang/AST/ASTContext.h"
24203955Srdivacky#include "clang/AST/CharUnits.h"
25193326Sed#include "clang/AST/DeclObjC.h"
26193326Sed#include "clang/AST/DeclCXX.h"
27210299Sed#include "clang/AST/DeclTemplate.h"
28218893Sdim#include "clang/AST/Mangle.h"
29199990Srdivacky#include "clang/AST/RecordLayout.h"
30194179Sed#include "clang/Basic/Builtins.h"
31193326Sed#include "clang/Basic/Diagnostic.h"
32193326Sed#include "clang/Basic/SourceManager.h"
33193326Sed#include "clang/Basic/TargetInfo.h"
34193326Sed#include "clang/Basic/ConvertUTF.h"
35193326Sed#include "llvm/CallingConv.h"
36193326Sed#include "llvm/Module.h"
37193326Sed#include "llvm/Intrinsics.h"
38201361Srdivacky#include "llvm/LLVMContext.h"
39204793Srdivacky#include "llvm/ADT/Triple.h"
40218893Sdim#include "llvm/Target/Mangler.h"
41193326Sed#include "llvm/Target/TargetData.h"
42207619Srdivacky#include "llvm/Support/CallSite.h"
43199482Srdivacky#include "llvm/Support/ErrorHandling.h"
44193326Sedusing namespace clang;
45193326Sedusing namespace CodeGen;
46193326Sed
47212904Sdimstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
48212904Sdim  switch (CGM.getContext().Target.getCXXABI()) {
49212904Sdim  case CXXABI_ARM: return *CreateARMCXXABI(CGM);
50212904Sdim  case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
51212904Sdim  case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
52212904Sdim  }
53193326Sed
54212904Sdim  llvm_unreachable("invalid C++ ABI kind");
55212904Sdim  return *CreateItaniumCXXABI(CGM);
56212904Sdim}
57212904Sdim
58212904Sdim
59199482SrdivackyCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
60193326Sed                             llvm::Module &M, const llvm::TargetData &TD,
61193326Sed                             Diagnostic &diags)
62218893Sdim  : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
63202379Srdivacky    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
64212904Sdim    ABI(createCXXABI(*this)),
65212904Sdim    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
66218893Sdim    TBAA(0),
67221345Sdim    VTables(*this), Runtime(0), DebugInfo(0),
68218893Sdim    CFConstantStringClassRef(0), ConstantStringClassRef(0),
69212904Sdim    VMContext(M.getContext()),
70212904Sdim    NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
71212904Sdim    NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
72212904Sdim    BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
73218893Sdim    BlockObjectAssign(0), BlockObjectDispose(0),
74218893Sdim    BlockDescriptorType(0), GenericBlockLiteralType(0) {
75221345Sdim  if (Features.ObjC1)
76221345Sdim     createObjCRuntime();
77193326Sed
78218893Sdim  // Enable TBAA unless it's suppressed.
79218893Sdim  if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
80218893Sdim    TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
81218893Sdim                           ABI.getMangleContext());
82218893Sdim
83221345Sdim  // If debug info or coverage generation is enabled, create the CGDebugInfo
84221345Sdim  // object.
85221345Sdim  if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
86221345Sdim      CodeGenOpts.EmitGcovNotes)
87221345Sdim    DebugInfo = new CGDebugInfo(*this);
88218893Sdim
89218893Sdim  Block.GlobalUniqueCount = 0;
90218893Sdim
91218893Sdim  // Initialize the type cache.
92218893Sdim  llvm::LLVMContext &LLVMContext = M.getContext();
93218893Sdim  Int8Ty  = llvm::Type::getInt8Ty(LLVMContext);
94218893Sdim  Int32Ty  = llvm::Type::getInt32Ty(LLVMContext);
95218893Sdim  Int64Ty  = llvm::Type::getInt64Ty(LLVMContext);
96218893Sdim  PointerWidthInBits = C.Target.getPointerWidth(0);
97219077Sdim  PointerAlignInBytes =
98219077Sdim    C.toCharUnitsFromBits(C.Target.getPointerAlign(0)).getQuantity();
99218893Sdim  IntTy = llvm::IntegerType::get(LLVMContext, C.Target.getIntWidth());
100218893Sdim  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
101218893Sdim  Int8PtrTy = Int8Ty->getPointerTo(0);
102218893Sdim  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
103193326Sed}
104193326Sed
105193326SedCodeGenModule::~CodeGenModule() {
106193326Sed  delete Runtime;
107212904Sdim  delete &ABI;
108218893Sdim  delete TBAA;
109193326Sed  delete DebugInfo;
110193326Sed}
111193326Sed
112202879Srdivackyvoid CodeGenModule::createObjCRuntime() {
113202879Srdivacky  if (!Features.NeXTRuntime)
114202879Srdivacky    Runtime = CreateGNUObjCRuntime(*this);
115202879Srdivacky  else
116202879Srdivacky    Runtime = CreateMacObjCRuntime(*this);
117202879Srdivacky}
118202879Srdivacky
119193326Sedvoid CodeGenModule::Release() {
120202379Srdivacky  EmitDeferred();
121198092Srdivacky  EmitCXXGlobalInitFunc();
122205408Srdivacky  EmitCXXGlobalDtorFunc();
123193326Sed  if (Runtime)
124193326Sed    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
125193326Sed      AddGlobalCtor(ObjCInitFunction);
126193326Sed  EmitCtorList(GlobalCtors, "llvm.global_ctors");
127193326Sed  EmitCtorList(GlobalDtors, "llvm.global_dtors");
128193326Sed  EmitAnnotations();
129193326Sed  EmitLLVMUsed();
130210299Sed
131218893Sdim  SimplifyPersonality();
132218893Sdim
133210299Sed  if (getCodeGenOpts().EmitDeclMetadata)
134210299Sed    EmitDeclMetadata();
135193326Sed}
136193326Sed
137221345Sdimvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
138221345Sdim  // Make sure that this type is translated.
139221345Sdim  Types.UpdateCompletedType(TD);
140221345Sdim  if (DebugInfo)
141221345Sdim    DebugInfo->UpdateCompletedType(TD);
142221345Sdim}
143221345Sdim
144218893Sdimllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
145218893Sdim  if (!TBAA)
146218893Sdim    return 0;
147218893Sdim  return TBAA->getTBAAInfo(QTy);
148218893Sdim}
149218893Sdim
150218893Sdimvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
151218893Sdim                                        llvm::MDNode *TBAAInfo) {
152218893Sdim  Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
153218893Sdim}
154218893Sdim
155204793Srdivackybool CodeGenModule::isTargetDarwin() const {
156221345Sdim  return getContext().Target.getTriple().isOSDarwin();
157204793Srdivacky}
158204793Srdivacky
159221345Sdimvoid CodeGenModule::Error(SourceLocation loc, llvm::StringRef error) {
160221345Sdim  unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
161221345Sdim  getDiags().Report(Context.getFullLoc(loc), diagID);
162221345Sdim}
163221345Sdim
164193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the
165193326Sed/// specified stmt yet.
166193326Sedvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
167193326Sed                                     bool OmitOnError) {
168193326Sed  if (OmitOnError && getDiags().hasErrorOccurred())
169193326Sed    return;
170198092Srdivacky  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
171193326Sed                                               "cannot compile this %0 yet");
172193326Sed  std::string Msg = Type;
173193326Sed  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
174193326Sed    << Msg << S->getSourceRange();
175193326Sed}
176193326Sed
177193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the
178193326Sed/// specified decl yet.
179193326Sedvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
180193326Sed                                     bool OmitOnError) {
181193326Sed  if (OmitOnError && getDiags().hasErrorOccurred())
182193326Sed    return;
183198092Srdivacky  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
184193326Sed                                               "cannot compile this %0 yet");
185193326Sed  std::string Msg = Type;
186193326Sed  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
187193326Sed}
188193326Sed
189198092Srdivackyvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
190218893Sdim                                        const NamedDecl *D) const {
191193326Sed  // Internal definitions always have default visibility.
192193326Sed  if (GV->hasLocalLinkage()) {
193193326Sed    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
194193326Sed    return;
195193326Sed  }
196193326Sed
197218893Sdim  // Set visibility for definitions.
198218893Sdim  NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
199218893Sdim  if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
200218893Sdim    GV->setVisibility(GetLLVMVisibility(LV.visibility()));
201193326Sed}
202193326Sed
203212904Sdim/// Set the symbol visibility of type information (vtable and RTTI)
204212904Sdim/// associated with the given type.
205212904Sdimvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
206212904Sdim                                      const CXXRecordDecl *RD,
207218893Sdim                                      TypeVisibilityKind TVK) const {
208212904Sdim  setGlobalVisibility(GV, RD);
209212904Sdim
210212904Sdim  if (!CodeGenOpts.HiddenWeakVTables)
211212904Sdim    return;
212212904Sdim
213218893Sdim  // We never want to drop the visibility for RTTI names.
214218893Sdim  if (TVK == TVK_ForRTTIName)
215218893Sdim    return;
216218893Sdim
217212904Sdim  // We want to drop the visibility to hidden for weak type symbols.
218212904Sdim  // This isn't possible if there might be unresolved references
219212904Sdim  // elsewhere that rely on this symbol being visible.
220212904Sdim
221212904Sdim  // This should be kept roughly in sync with setThunkVisibility
222212904Sdim  // in CGVTables.cpp.
223212904Sdim
224212904Sdim  // Preconditions.
225218893Sdim  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
226212904Sdim      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
227212904Sdim    return;
228212904Sdim
229212904Sdim  // Don't override an explicit visibility attribute.
230221345Sdim  if (RD->getExplicitVisibility())
231212904Sdim    return;
232212904Sdim
233212904Sdim  switch (RD->getTemplateSpecializationKind()) {
234212904Sdim  // We have to disable the optimization if this is an EI definition
235212904Sdim  // because there might be EI declarations in other shared objects.
236212904Sdim  case TSK_ExplicitInstantiationDefinition:
237212904Sdim  case TSK_ExplicitInstantiationDeclaration:
238212904Sdim    return;
239212904Sdim
240212904Sdim  // Every use of a non-template class's type information has to emit it.
241212904Sdim  case TSK_Undeclared:
242212904Sdim    break;
243212904Sdim
244212904Sdim  // In theory, implicit instantiations can ignore the possibility of
245212904Sdim  // an explicit instantiation declaration because there necessarily
246212904Sdim  // must be an EI definition somewhere with default visibility.  In
247212904Sdim  // practice, it's possible to have an explicit instantiation for
248212904Sdim  // an arbitrary template class, and linkers aren't necessarily able
249212904Sdim  // to deal with mixed-visibility symbols.
250212904Sdim  case TSK_ExplicitSpecialization:
251212904Sdim  case TSK_ImplicitInstantiation:
252212904Sdim    if (!CodeGenOpts.HiddenWeakTemplateVTables)
253212904Sdim      return;
254212904Sdim    break;
255212904Sdim  }
256212904Sdim
257212904Sdim  // If there's a key function, there may be translation units
258212904Sdim  // that don't have the key function's definition.  But ignore
259212904Sdim  // this if we're emitting RTTI under -fno-rtti.
260218893Sdim  if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
261212904Sdim    if (Context.getKeyFunction(RD))
262212904Sdim      return;
263218893Sdim  }
264212904Sdim
265212904Sdim  // Otherwise, drop the visibility to hidden.
266212904Sdim  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
267218893Sdim  GV->setUnnamedAddr(true);
268212904Sdim}
269212904Sdim
270210299Sedllvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
271198092Srdivacky  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
272198092Srdivacky
273210299Sed  llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
274210299Sed  if (!Str.empty())
275210299Sed    return Str;
276198092Srdivacky
277212904Sdim  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
278210299Sed    IdentifierInfo *II = ND->getIdentifier();
279210299Sed    assert(II && "Attempt to mangle unnamed decl.");
280193326Sed
281210299Sed    Str = II->getName();
282210299Sed    return Str;
283193326Sed  }
284210299Sed
285210299Sed  llvm::SmallString<256> Buffer;
286218893Sdim  llvm::raw_svector_ostream Out(Buffer);
287210299Sed  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
288218893Sdim    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
289210299Sed  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
290218893Sdim    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
291210299Sed  else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
292218893Sdim    getCXXABI().getMangleContext().mangleBlock(BD, Out);
293210299Sed  else
294218893Sdim    getCXXABI().getMangleContext().mangleName(ND, Out);
295198092Srdivacky
296210299Sed  // Allocate space for the mangled name.
297218893Sdim  Out.flush();
298210299Sed  size_t Length = Buffer.size();
299210299Sed  char *Name = MangledNamesAllocator.Allocate<char>(Length);
300210299Sed  std::copy(Buffer.begin(), Buffer.end(), Name);
301210299Sed
302210299Sed  Str = llvm::StringRef(Name, Length);
303210299Sed
304210299Sed  return Str;
305193326Sed}
306193326Sed
307218893Sdimvoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
308218893Sdim                                        const BlockDecl *BD) {
309218893Sdim  MangleContext &MangleCtx = getCXXABI().getMangleContext();
310218893Sdim  const Decl *D = GD.getDecl();
311218893Sdim  llvm::raw_svector_ostream Out(Buffer.getBuffer());
312218893Sdim  if (D == 0)
313218893Sdim    MangleCtx.mangleGlobalBlock(BD, Out);
314218893Sdim  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
315218893Sdim    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
316218893Sdim  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
317218893Sdim    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
318218893Sdim  else
319218893Sdim    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
320210299Sed}
321210299Sed
322205408Srdivackyllvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
323205408Srdivacky  return getModule().getNamedValue(Name);
324193326Sed}
325193326Sed
326193326Sed/// AddGlobalCtor - Add a function to the list that will be called before
327193326Sed/// main() runs.
328193326Sedvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
329193326Sed  // FIXME: Type coercion of void()* types.
330193326Sed  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
331193326Sed}
332193326Sed
333193326Sed/// AddGlobalDtor - Add a function to the list that will be called
334193326Sed/// when the module is unloaded.
335193326Sedvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
336193326Sed  // FIXME: Type coercion of void()* types.
337193326Sed  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
338193326Sed}
339193326Sed
340193326Sedvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
341193326Sed  // Ctor function type is void()*.
342193326Sed  llvm::FunctionType* CtorFTy =
343218893Sdim    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
344193326Sed  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
345193326Sed
346193326Sed  // Get the type of a ctor entry, { i32, void ()* }.
347198092Srdivacky  llvm::StructType* CtorStructTy =
348198092Srdivacky    llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
349193326Sed                          llvm::PointerType::getUnqual(CtorFTy), NULL);
350193326Sed
351193326Sed  // Construct the constructor and destructor arrays.
352193326Sed  std::vector<llvm::Constant*> Ctors;
353193326Sed  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
354193326Sed    std::vector<llvm::Constant*> S;
355198092Srdivacky    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
356198092Srdivacky                I->second, false));
357193326Sed    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
358193326Sed    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
359193326Sed  }
360193326Sed
361193326Sed  if (!Ctors.empty()) {
362193326Sed    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
363198092Srdivacky    new llvm::GlobalVariable(TheModule, AT, false,
364193326Sed                             llvm::GlobalValue::AppendingLinkage,
365193326Sed                             llvm::ConstantArray::get(AT, Ctors),
366198092Srdivacky                             GlobalName);
367193326Sed  }
368193326Sed}
369193326Sed
370193326Sedvoid CodeGenModule::EmitAnnotations() {
371193326Sed  if (Annotations.empty())
372193326Sed    return;
373193326Sed
374193326Sed  // Create a new global variable for the ConstantStruct in the Module.
375193326Sed  llvm::Constant *Array =
376193326Sed  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
377193326Sed                                                Annotations.size()),
378193326Sed                           Annotations);
379198092Srdivacky  llvm::GlobalValue *gv =
380198092Srdivacky  new llvm::GlobalVariable(TheModule, Array->getType(), false,
381198092Srdivacky                           llvm::GlobalValue::AppendingLinkage, Array,
382198092Srdivacky                           "llvm.global.annotations");
383193326Sed  gv->setSection("llvm.metadata");
384193326Sed}
385193326Sed
386204643Srdivackyllvm::GlobalValue::LinkageTypes
387204643SrdivackyCodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
388212904Sdim  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
389193326Sed
390210299Sed  if (Linkage == GVA_Internal)
391204643Srdivacky    return llvm::Function::InternalLinkage;
392210299Sed
393210299Sed  if (D->hasAttr<DLLExportAttr>())
394204643Srdivacky    return llvm::Function::DLLExportLinkage;
395210299Sed
396210299Sed  if (D->hasAttr<WeakAttr>())
397204643Srdivacky    return llvm::Function::WeakAnyLinkage;
398210299Sed
399210299Sed  // In C99 mode, 'inline' functions are guaranteed to have a strong
400210299Sed  // definition somewhere else, so we can use available_externally linkage.
401210299Sed  if (Linkage == GVA_C99Inline)
402204643Srdivacky    return llvm::Function::AvailableExternallyLinkage;
403210299Sed
404210299Sed  // In C++, the compiler has to emit a definition in every translation unit
405210299Sed  // that references the function.  We should use linkonce_odr because
406210299Sed  // a) if all references in this translation unit are optimized away, we
407210299Sed  // don't need to codegen it.  b) if the function persists, it needs to be
408210299Sed  // merged with other definitions. c) C++ has the ODR, so we know the
409210299Sed  // definition is dependable.
410210299Sed  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
411218893Sdim    return !Context.getLangOptions().AppleKext
412218893Sdim             ? llvm::Function::LinkOnceODRLinkage
413218893Sdim             : llvm::Function::InternalLinkage;
414210299Sed
415210299Sed  // An explicit instantiation of a template has weak linkage, since
416210299Sed  // explicit instantiations can occur in multiple translation units
417210299Sed  // and must all be equivalent. However, we are not allowed to
418210299Sed  // throw away these explicit instantiations.
419210299Sed  if (Linkage == GVA_ExplicitTemplateInstantiation)
420218893Sdim    return !Context.getLangOptions().AppleKext
421218893Sdim             ? llvm::Function::WeakODRLinkage
422218893Sdim             : llvm::Function::InternalLinkage;
423210299Sed
424210299Sed  // Otherwise, we have strong external linkage.
425210299Sed  assert(Linkage == GVA_StrongExternal);
426210299Sed  return llvm::Function::ExternalLinkage;
427204643Srdivacky}
428193326Sed
429204643Srdivacky
430204643Srdivacky/// SetFunctionDefinitionAttributes - Set attributes for a global.
431204643Srdivacky///
432204643Srdivacky/// FIXME: This is currently only done for aliases and functions, but not for
433204643Srdivacky/// variables (these details are set in EmitGlobalVarDefinition for variables).
434204643Srdivackyvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
435204643Srdivacky                                                    llvm::GlobalValue *GV) {
436193326Sed  SetCommonAttributes(D, GV);
437193326Sed}
438193326Sed
439193326Sedvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
440198092Srdivacky                                              const CGFunctionInfo &Info,
441193326Sed                                              llvm::Function *F) {
442198092Srdivacky  unsigned CallingConv;
443193326Sed  AttributeListType AttributeList;
444198092Srdivacky  ConstructAttributeList(Info, D, AttributeList, CallingConv);
445193326Sed  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
446198092Srdivacky                                          AttributeList.size()));
447198092Srdivacky  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
448193326Sed}
449193326Sed
450193326Sedvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
451193326Sed                                                           llvm::Function *F) {
452193326Sed  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
453198092Srdivacky    F->addFnAttr(llvm::Attribute::NoUnwind);
454193326Sed
455195341Sed  if (D->hasAttr<AlwaysInlineAttr>())
456193326Sed    F->addFnAttr(llvm::Attribute::AlwaysInline);
457198092Srdivacky
458218893Sdim  if (D->hasAttr<NakedAttr>())
459218893Sdim    F->addFnAttr(llvm::Attribute::Naked);
460218893Sdim
461198092Srdivacky  if (D->hasAttr<NoInlineAttr>())
462193326Sed    F->addFnAttr(llvm::Attribute::NoInline);
463198092Srdivacky
464218893Sdim  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
465218893Sdim    F->setUnnamedAddr(true);
466218893Sdim
467199482Srdivacky  if (Features.getStackProtectorMode() == LangOptions::SSPOn)
468199482Srdivacky    F->addFnAttr(llvm::Attribute::StackProtect);
469199482Srdivacky  else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
470199482Srdivacky    F->addFnAttr(llvm::Attribute::StackProtectReq);
471199482Srdivacky
472212904Sdim  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
473212904Sdim  if (alignment)
474212904Sdim    F->setAlignment(alignment);
475212904Sdim
476198092Srdivacky  // C++ ABI requires 2-byte alignment for member functions.
477198092Srdivacky  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
478198092Srdivacky    F->setAlignment(2);
479193326Sed}
480193326Sed
481198092Srdivackyvoid CodeGenModule::SetCommonAttributes(const Decl *D,
482193326Sed                                        llvm::GlobalValue *GV) {
483218893Sdim  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
484218893Sdim    setGlobalVisibility(GV, ND);
485218893Sdim  else
486218893Sdim    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
487193326Sed
488195341Sed  if (D->hasAttr<UsedAttr>())
489193326Sed    AddUsedGlobal(GV);
490193326Sed
491195341Sed  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
492193326Sed    GV->setSection(SA->getName());
493202379Srdivacky
494202379Srdivacky  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
495193326Sed}
496193326Sed
497193326Sedvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
498193326Sed                                                  llvm::Function *F,
499193326Sed                                                  const CGFunctionInfo &FI) {
500193326Sed  SetLLVMFunctionAttributes(D, FI, F);
501193326Sed  SetLLVMFunctionAttributesForDefinition(D, F);
502193326Sed
503193326Sed  F->setLinkage(llvm::Function::InternalLinkage);
504193326Sed
505193326Sed  SetCommonAttributes(D, F);
506193326Sed}
507193326Sed
508203955Srdivackyvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
509193326Sed                                          llvm::Function *F,
510193326Sed                                          bool IsIncompleteFunction) {
511221345Sdim  if (unsigned IID = F->getIntrinsicID()) {
512221345Sdim    // If this is an intrinsic function, set the function's attributes
513221345Sdim    // to the intrinsic's attributes.
514221345Sdim    F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
515221345Sdim    return;
516221345Sdim  }
517221345Sdim
518203955Srdivacky  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
519203955Srdivacky
520193326Sed  if (!IsIncompleteFunction)
521203955Srdivacky    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
522198092Srdivacky
523193326Sed  // Only a few attributes are set on declarations; these may later be
524193326Sed  // overridden by a definition.
525198092Srdivacky
526195341Sed  if (FD->hasAttr<DLLImportAttr>()) {
527193326Sed    F->setLinkage(llvm::Function::DLLImportLinkage);
528198092Srdivacky  } else if (FD->hasAttr<WeakAttr>() ||
529221345Sdim             FD->isWeakImported()) {
530193326Sed    // "extern_weak" is overloaded in LLVM; we probably should have
531198092Srdivacky    // separate linkage types for this.
532193326Sed    F->setLinkage(llvm::Function::ExternalWeakLinkage);
533193326Sed  } else {
534198092Srdivacky    F->setLinkage(llvm::Function::ExternalLinkage);
535218893Sdim
536218893Sdim    NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
537218893Sdim    if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
538218893Sdim      F->setVisibility(GetLLVMVisibility(LV.visibility()));
539218893Sdim    }
540193326Sed  }
541193326Sed
542195341Sed  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
543193326Sed    F->setSection(SA->getName());
544193326Sed}
545193326Sed
546193326Sedvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
547198092Srdivacky  assert(!GV->isDeclaration() &&
548193326Sed         "Only globals with definition can force usage.");
549193326Sed  LLVMUsed.push_back(GV);
550193326Sed}
551193326Sed
552193326Sedvoid CodeGenModule::EmitLLVMUsed() {
553193326Sed  // Don't create llvm.used if there is no need.
554198092Srdivacky  if (LLVMUsed.empty())
555193326Sed    return;
556193326Sed
557198092Srdivacky  const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
558198092Srdivacky
559193326Sed  // Convert LLVMUsed to what ConstantArray needs.
560193326Sed  std::vector<llvm::Constant*> UsedArray;
561193326Sed  UsedArray.resize(LLVMUsed.size());
562193326Sed  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
563198092Srdivacky    UsedArray[i] =
564198092Srdivacky     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
565198092Srdivacky                                      i8PTy);
566193326Sed  }
567198092Srdivacky
568195099Sed  if (UsedArray.empty())
569195099Sed    return;
570195099Sed  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
571198092Srdivacky
572198092Srdivacky  llvm::GlobalVariable *GV =
573198092Srdivacky    new llvm::GlobalVariable(getModule(), ATy, false,
574193326Sed                             llvm::GlobalValue::AppendingLinkage,
575193326Sed                             llvm::ConstantArray::get(ATy, UsedArray),
576198092Srdivacky                             "llvm.used");
577193326Sed
578193326Sed  GV->setSection("llvm.metadata");
579193326Sed}
580193326Sed
581193326Sedvoid CodeGenModule::EmitDeferred() {
582193326Sed  // Emit code for any potentially referenced deferred decls.  Since a
583193326Sed  // previously unused static decl may become used during the generation of code
584193326Sed  // for a static function, iterate until no  changes are made.
585204962Srdivacky
586207619Srdivacky  while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
587207619Srdivacky    if (!DeferredVTables.empty()) {
588207619Srdivacky      const CXXRecordDecl *RD = DeferredVTables.back();
589207619Srdivacky      DeferredVTables.pop_back();
590207619Srdivacky      getVTables().GenerateClassData(getVTableLinkage(RD), RD);
591204962Srdivacky      continue;
592204962Srdivacky    }
593204962Srdivacky
594193326Sed    GlobalDecl D = DeferredDeclsToEmit.back();
595193326Sed    DeferredDeclsToEmit.pop_back();
596193326Sed
597208600Srdivacky    // Check to see if we've already emitted this.  This is necessary
598208600Srdivacky    // for a couple of reasons: first, decls can end up in the
599208600Srdivacky    // deferred-decls queue multiple times, and second, decls can end
600208600Srdivacky    // up with definitions in unusual ways (e.g. by an extern inline
601208600Srdivacky    // function acquiring a strong function redefinition).  Just
602208600Srdivacky    // ignore these cases.
603208600Srdivacky    //
604208600Srdivacky    // TODO: That said, looking this up multiple times is very wasteful.
605210299Sed    llvm::StringRef Name = getMangledName(D);
606205408Srdivacky    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
607193326Sed    assert(CGRef && "Deferred decl wasn't referenced?");
608198092Srdivacky
609193326Sed    if (!CGRef->isDeclaration())
610193326Sed      continue;
611198092Srdivacky
612208600Srdivacky    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
613208600Srdivacky    // purposes an alias counts as a definition.
614208600Srdivacky    if (isa<llvm::GlobalAlias>(CGRef))
615208600Srdivacky      continue;
616208600Srdivacky
617193326Sed    // Otherwise, emit the definition and move on to the next one.
618193326Sed    EmitGlobalDefinition(D);
619193326Sed  }
620193326Sed}
621193326Sed
622198092Srdivacky/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
623193326Sed/// annotation information for a given GlobalValue.  The annotation struct is
624198092Srdivacky/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
625198092Srdivacky/// GlobalValue being annotated.  The second field is the constant string
626198092Srdivacky/// created from the AnnotateAttr's annotation.  The third field is a constant
627193326Sed/// string containing the name of the translation unit.  The fourth field is
628193326Sed/// the line number in the file of the annotated value declaration.
629193326Sed///
630193326Sed/// FIXME: this does not unique the annotation string constants, as llvm-gcc
631193326Sed///        appears to.
632193326Sed///
633198092Srdivackyllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
634193326Sed                                                const AnnotateAttr *AA,
635193326Sed                                                unsigned LineNo) {
636193326Sed  llvm::Module *M = &getModule();
637193326Sed
638193326Sed  // get [N x i8] constants for the annotation string, and the filename string
639193326Sed  // which are the 2nd and 3rd elements of the global annotation structure.
640198092Srdivacky  const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
641198092Srdivacky  llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
642198092Srdivacky                                                  AA->getAnnotation(), true);
643198092Srdivacky  llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
644198092Srdivacky                                                  M->getModuleIdentifier(),
645193326Sed                                                  true);
646193326Sed
647193326Sed  // Get the two global values corresponding to the ConstantArrays we just
648193326Sed  // created to hold the bytes of the strings.
649198092Srdivacky  llvm::GlobalValue *annoGV =
650198092Srdivacky    new llvm::GlobalVariable(*M, anno->getType(), false,
651198092Srdivacky                             llvm::GlobalValue::PrivateLinkage, anno,
652198092Srdivacky                             GV->getName());
653193326Sed  // translation unit name string, emitted into the llvm.metadata section.
654193326Sed  llvm::GlobalValue *unitGV =
655198092Srdivacky    new llvm::GlobalVariable(*M, unit->getType(), false,
656198092Srdivacky                             llvm::GlobalValue::PrivateLinkage, unit,
657198092Srdivacky                             ".str");
658218893Sdim  unitGV->setUnnamedAddr(true);
659193326Sed
660193326Sed  // Create the ConstantStruct for the global annotation.
661193326Sed  llvm::Constant *Fields[4] = {
662193326Sed    llvm::ConstantExpr::getBitCast(GV, SBP),
663193326Sed    llvm::ConstantExpr::getBitCast(annoGV, SBP),
664193326Sed    llvm::ConstantExpr::getBitCast(unitGV, SBP),
665198092Srdivacky    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
666193326Sed  };
667198092Srdivacky  return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
668193326Sed}
669193326Sed
670193326Sedbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
671212904Sdim  // Never defer when EmitAllDecls is specified.
672212904Sdim  if (Features.EmitAllDecls)
673193326Sed    return false;
674193326Sed
675212904Sdim  return !getContext().DeclMustBeEmitted(Global);
676193326Sed}
677193326Sed
678204793Srdivackyllvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
679204793Srdivacky  const AliasAttr *AA = VD->getAttr<AliasAttr>();
680204793Srdivacky  assert(AA && "No alias?");
681204793Srdivacky
682204793Srdivacky  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
683204793Srdivacky
684204793Srdivacky  // See if there is already something with the target's name in the module.
685205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
686204793Srdivacky
687204793Srdivacky  llvm::Constant *Aliasee;
688204793Srdivacky  if (isa<llvm::FunctionType>(DeclTy))
689218893Sdim    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
690218893Sdim                                      /*ForVTable=*/false);
691204793Srdivacky  else
692205408Srdivacky    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
693204793Srdivacky                                    llvm::PointerType::getUnqual(DeclTy), 0);
694204793Srdivacky  if (!Entry) {
695204793Srdivacky    llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
696204793Srdivacky    F->setLinkage(llvm::Function::ExternalWeakLinkage);
697204793Srdivacky    WeakRefReferences.insert(F);
698204793Srdivacky  }
699204793Srdivacky
700204793Srdivacky  return Aliasee;
701204793Srdivacky}
702204793Srdivacky
703193326Sedvoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
704198092Srdivacky  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
705198092Srdivacky
706204793Srdivacky  // Weak references don't produce any output by themselves.
707204793Srdivacky  if (Global->hasAttr<WeakRefAttr>())
708204793Srdivacky    return;
709204793Srdivacky
710193326Sed  // If this is an alias definition (which otherwise looks like a declaration)
711193326Sed  // emit it now.
712195341Sed  if (Global->hasAttr<AliasAttr>())
713205408Srdivacky    return EmitAliasDefinition(GD);
714193326Sed
715193326Sed  // Ignore declarations, they will be emitted on their first use.
716193326Sed  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
717212904Sdim    if (FD->getIdentifier()) {
718212904Sdim      llvm::StringRef Name = FD->getName();
719212904Sdim      if (Name == "_Block_object_assign") {
720212904Sdim        BlockObjectAssignDecl = FD;
721212904Sdim      } else if (Name == "_Block_object_dispose") {
722212904Sdim        BlockObjectDisposeDecl = FD;
723212904Sdim      }
724212904Sdim    }
725212904Sdim
726193326Sed    // Forward declarations are emitted lazily on first use.
727193326Sed    if (!FD->isThisDeclarationADefinition())
728193326Sed      return;
729193326Sed  } else {
730193326Sed    const VarDecl *VD = cast<VarDecl>(Global);
731193326Sed    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
732193326Sed
733212904Sdim    if (VD->getIdentifier()) {
734212904Sdim      llvm::StringRef Name = VD->getName();
735212904Sdim      if (Name == "_NSConcreteGlobalBlock") {
736212904Sdim        NSConcreteGlobalBlockDecl = VD;
737212904Sdim      } else if (Name == "_NSConcreteStackBlock") {
738212904Sdim        NSConcreteStackBlockDecl = VD;
739212904Sdim      }
740212904Sdim    }
741212904Sdim
742212904Sdim
743203955Srdivacky    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
744193326Sed      return;
745193326Sed  }
746193326Sed
747193326Sed  // Defer code generation when possible if this is a static definition, inline
748193326Sed  // function etc.  These we only want to emit if they are used.
749207619Srdivacky  if (!MayDeferGeneration(Global)) {
750207619Srdivacky    // Emit the definition if it can't be deferred.
751207619Srdivacky    EmitGlobalDefinition(GD);
752193326Sed    return;
753193326Sed  }
754212904Sdim
755212904Sdim  // If we're deferring emission of a C++ variable with an
756212904Sdim  // initializer, remember the order in which it appeared in the file.
757212904Sdim  if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
758212904Sdim      cast<VarDecl>(Global)->hasInit()) {
759212904Sdim    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
760212904Sdim    CXXGlobalInits.push_back(0);
761212904Sdim  }
762207619Srdivacky
763207619Srdivacky  // If the value has already been used, add it directly to the
764207619Srdivacky  // DeferredDeclsToEmit list.
765210299Sed  llvm::StringRef MangledName = getMangledName(GD);
766207619Srdivacky  if (GetGlobalValue(MangledName))
767207619Srdivacky    DeferredDeclsToEmit.push_back(GD);
768207619Srdivacky  else {
769207619Srdivacky    // Otherwise, remember that we saw a deferred decl with this name.  The
770207619Srdivacky    // first use of the mangled name will cause it to move into
771207619Srdivacky    // DeferredDeclsToEmit.
772207619Srdivacky    DeferredDecls[MangledName] = GD;
773207619Srdivacky  }
774193326Sed}
775193326Sed
776193326Sedvoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
777198092Srdivacky  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
778198092Srdivacky
779207619Srdivacky  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
780198893Srdivacky                                 Context.getSourceManager(),
781198893Srdivacky                                 "Generating code for declaration");
782198893Srdivacky
783210299Sed  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
784210299Sed    // At -O0, don't generate IR for functions with available_externally
785210299Sed    // linkage.
786212904Sdim    if (CodeGenOpts.OptimizationLevel == 0 &&
787212904Sdim        !Function->hasAttr<AlwaysInlineAttr>() &&
788210299Sed        getFunctionLinkage(Function)
789210299Sed                                  == llvm::Function::AvailableExternallyLinkage)
790210299Sed      return;
791206084Srdivacky
792210299Sed    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
793210299Sed      if (Method->isVirtual())
794210299Sed        getVTables().EmitThunks(GD);
795210299Sed
796210299Sed      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
797210299Sed        return EmitCXXConstructor(CD, GD.getCtorType());
798207619Srdivacky
799210299Sed      if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
800210299Sed        return EmitCXXDestructor(DD, GD.getDtorType());
801210299Sed    }
802207619Srdivacky
803207619Srdivacky    return EmitGlobalFunctionDefinition(GD);
804210299Sed  }
805207619Srdivacky
806207619Srdivacky  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
807207619Srdivacky    return EmitGlobalVarDefinition(VD);
808207619Srdivacky
809207619Srdivacky  assert(0 && "Invalid argument to EmitGlobalDefinition()");
810193326Sed}
811193326Sed
812193326Sed/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
813193326Sed/// module, create and return an llvm Function with the specified type. If there
814193326Sed/// is something in the module with the specified name, return it potentially
815193326Sed/// bitcasted to the right type.
816193326Sed///
817193326Sed/// If D is non-null, it specifies a decl that correspond to this.  This is used
818193326Sed/// to set the attributes on the function when it is first created.
819205408Srdivackyllvm::Constant *
820205408SrdivackyCodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
821205408Srdivacky                                       const llvm::Type *Ty,
822218893Sdim                                       GlobalDecl D, bool ForVTable) {
823193326Sed  // Lookup the entry, lazily creating it if necessary.
824205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
825193326Sed  if (Entry) {
826204793Srdivacky    if (WeakRefReferences.count(Entry)) {
827204793Srdivacky      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
828204793Srdivacky      if (FD && !FD->hasAttr<WeakAttr>())
829206084Srdivacky        Entry->setLinkage(llvm::Function::ExternalLinkage);
830204793Srdivacky
831204793Srdivacky      WeakRefReferences.erase(Entry);
832204793Srdivacky    }
833204793Srdivacky
834193326Sed    if (Entry->getType()->getElementType() == Ty)
835193326Sed      return Entry;
836198092Srdivacky
837193326Sed    // Make sure the result is of the correct type.
838193326Sed    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
839193326Sed    return llvm::ConstantExpr::getBitCast(Entry, PTy);
840193326Sed  }
841198092Srdivacky
842199482Srdivacky  // This function doesn't have a complete type (for example, the return
843199482Srdivacky  // type is an incomplete struct). Use a fake type instead, and make
844199482Srdivacky  // sure not to try to set attributes.
845199482Srdivacky  bool IsIncompleteFunction = false;
846207619Srdivacky
847207619Srdivacky  const llvm::FunctionType *FTy;
848207619Srdivacky  if (isa<llvm::FunctionType>(Ty)) {
849207619Srdivacky    FTy = cast<llvm::FunctionType>(Ty);
850207619Srdivacky  } else {
851218893Sdim    FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
852199482Srdivacky    IsIncompleteFunction = true;
853199482Srdivacky  }
854210299Sed
855207619Srdivacky  llvm::Function *F = llvm::Function::Create(FTy,
856199482Srdivacky                                             llvm::Function::ExternalLinkage,
857205408Srdivacky                                             MangledName, &getModule());
858205408Srdivacky  assert(F->getName() == MangledName && "name was uniqued!");
859199482Srdivacky  if (D.getDecl())
860203955Srdivacky    SetFunctionAttributes(D, F, IsIncompleteFunction);
861199482Srdivacky
862193326Sed  // This is the first use or definition of a mangled name.  If there is a
863193326Sed  // deferred decl with this name, remember that we need to emit it at the end
864193326Sed  // of the file.
865205408Srdivacky  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
866193326Sed  if (DDI != DeferredDecls.end()) {
867193326Sed    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
868193326Sed    // list, and remove it from DeferredDecls (since we don't need it anymore).
869193326Sed    DeferredDeclsToEmit.push_back(DDI->second);
870193326Sed    DeferredDecls.erase(DDI);
871218893Sdim
872218893Sdim  // Otherwise, there are cases we have to worry about where we're
873218893Sdim  // using a declaration for which we must emit a definition but where
874218893Sdim  // we might not find a top-level definition:
875218893Sdim  //   - member functions defined inline in their classes
876218893Sdim  //   - friend functions defined inline in some class
877218893Sdim  //   - special member functions with implicit definitions
878218893Sdim  // If we ever change our AST traversal to walk into class methods,
879218893Sdim  // this will be unnecessary.
880218893Sdim  //
881218893Sdim  // We also don't emit a definition for a function if it's going to be an entry
882218893Sdim  // in a vtable, unless it's already marked as used.
883218893Sdim  } else if (getLangOptions().CPlusPlus && D.getDecl()) {
884218893Sdim    // Look for a declaration that's lexically in a record.
885218893Sdim    const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
886218893Sdim    do {
887218893Sdim      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
888218893Sdim        if (FD->isImplicit() && !ForVTable) {
889218893Sdim          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
890218893Sdim          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
891218893Sdim          break;
892218893Sdim        } else if (FD->isThisDeclarationADefinition()) {
893218893Sdim          DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
894218893Sdim          break;
895218893Sdim        }
896204643Srdivacky      }
897218893Sdim      FD = FD->getPreviousDeclaration();
898218893Sdim    } while (FD);
899193326Sed  }
900198092Srdivacky
901207619Srdivacky  // Make sure the result is of the requested type.
902207619Srdivacky  if (!IsIncompleteFunction) {
903207619Srdivacky    assert(F->getType()->getElementType() == Ty);
904207619Srdivacky    return F;
905207619Srdivacky  }
906207619Srdivacky
907207619Srdivacky  const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
908207619Srdivacky  return llvm::ConstantExpr::getBitCast(F, PTy);
909193326Sed}
910193326Sed
911193326Sed/// GetAddrOfFunction - Return the address of the given function.  If Ty is
912193326Sed/// non-null, then this function will use the specified type if it has to
913193326Sed/// create it (this occurs when we see a definition of the function).
914193326Sedllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
915218893Sdim                                                 const llvm::Type *Ty,
916218893Sdim                                                 bool ForVTable) {
917193326Sed  // If there was no specific requested type, just convert it now.
918193326Sed  if (!Ty)
919198092Srdivacky    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
920210299Sed
921210299Sed  llvm::StringRef MangledName = getMangledName(GD);
922218893Sdim  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
923193326Sed}
924193326Sed
925193326Sed/// CreateRuntimeFunction - Create a new runtime function with the specified
926193326Sed/// type and name.
927193326Sedllvm::Constant *
928193326SedCodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
929205408Srdivacky                                     llvm::StringRef Name) {
930218893Sdim  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false);
931193326Sed}
932193326Sed
933200583Srdivackystatic bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
934203955Srdivacky  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
935200583Srdivacky    return false;
936200583Srdivacky  if (Context.getLangOptions().CPlusPlus &&
937200583Srdivacky      Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
938200583Srdivacky    // FIXME: We should do something fancier here!
939200583Srdivacky    return false;
940200583Srdivacky  }
941200583Srdivacky  return true;
942200583Srdivacky}
943200583Srdivacky
944193326Sed/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
945193326Sed/// create and return an llvm GlobalVariable with the specified type.  If there
946193326Sed/// is something in the module with the specified name, return it potentially
947193326Sed/// bitcasted to the right type.
948193326Sed///
949193326Sed/// If D is non-null, it specifies a decl that correspond to this.  This is used
950193326Sed/// to set the attributes on the global when it is first created.
951205408Srdivackyllvm::Constant *
952205408SrdivackyCodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
953205408Srdivacky                                     const llvm::PointerType *Ty,
954218893Sdim                                     const VarDecl *D,
955218893Sdim                                     bool UnnamedAddr) {
956193326Sed  // Lookup the entry, lazily creating it if necessary.
957205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
958193326Sed  if (Entry) {
959204793Srdivacky    if (WeakRefReferences.count(Entry)) {
960204793Srdivacky      if (D && !D->hasAttr<WeakAttr>())
961206084Srdivacky        Entry->setLinkage(llvm::Function::ExternalLinkage);
962204793Srdivacky
963204793Srdivacky      WeakRefReferences.erase(Entry);
964204793Srdivacky    }
965204793Srdivacky
966218893Sdim    if (UnnamedAddr)
967218893Sdim      Entry->setUnnamedAddr(true);
968218893Sdim
969193326Sed    if (Entry->getType() == Ty)
970193326Sed      return Entry;
971198092Srdivacky
972193326Sed    // Make sure the result is of the correct type.
973193326Sed    return llvm::ConstantExpr::getBitCast(Entry, Ty);
974193326Sed  }
975198092Srdivacky
976193326Sed  // This is the first use or definition of a mangled name.  If there is a
977193326Sed  // deferred decl with this name, remember that we need to emit it at the end
978193326Sed  // of the file.
979205408Srdivacky  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
980193326Sed  if (DDI != DeferredDecls.end()) {
981193326Sed    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
982193326Sed    // list, and remove it from DeferredDecls (since we don't need it anymore).
983193326Sed    DeferredDeclsToEmit.push_back(DDI->second);
984193326Sed    DeferredDecls.erase(DDI);
985193326Sed  }
986198092Srdivacky
987198092Srdivacky  llvm::GlobalVariable *GV =
988198092Srdivacky    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
989193326Sed                             llvm::GlobalValue::ExternalLinkage,
990205408Srdivacky                             0, MangledName, 0,
991193326Sed                             false, Ty->getAddressSpace());
992193326Sed
993193326Sed  // Handle things which are present even on external declarations.
994193326Sed  if (D) {
995193326Sed    // FIXME: This code is overly simple and should be merged with other global
996193326Sed    // handling.
997200583Srdivacky    GV->setConstant(DeclIsConstantGlobal(Context, D));
998193326Sed
999218893Sdim    // Set linkage and visibility in case we never see a definition.
1000218893Sdim    NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1001218893Sdim    if (LV.linkage() != ExternalLinkage) {
1002218893Sdim      // Don't set internal linkage on declarations.
1003218893Sdim    } else {
1004218893Sdim      if (D->hasAttr<DLLImportAttr>())
1005218893Sdim        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1006221345Sdim      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1007218893Sdim        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1008193326Sed
1009218893Sdim      // Set visibility on a declaration only if it's explicit.
1010218893Sdim      if (LV.visibilityExplicit())
1011218893Sdim        GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1012218893Sdim    }
1013193326Sed
1014193326Sed    GV->setThreadLocal(D->isThreadSpecified());
1015193326Sed  }
1016198092Srdivacky
1017205408Srdivacky  return GV;
1018193326Sed}
1019193326Sed
1020193326Sed
1021218893Sdimllvm::GlobalVariable *
1022218893SdimCodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
1023218893Sdim                                      const llvm::Type *Ty,
1024218893Sdim                                      llvm::GlobalValue::LinkageTypes Linkage) {
1025218893Sdim  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1026218893Sdim  llvm::GlobalVariable *OldGV = 0;
1027218893Sdim
1028218893Sdim
1029218893Sdim  if (GV) {
1030218893Sdim    // Check if the variable has the right type.
1031218893Sdim    if (GV->getType()->getElementType() == Ty)
1032218893Sdim      return GV;
1033218893Sdim
1034218893Sdim    // Because C++ name mangling, the only way we can end up with an already
1035218893Sdim    // existing global with the same name is if it has been declared extern "C".
1036218893Sdim      assert(GV->isDeclaration() && "Declaration has wrong type!");
1037218893Sdim    OldGV = GV;
1038218893Sdim  }
1039218893Sdim
1040218893Sdim  // Create a new variable.
1041218893Sdim  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1042218893Sdim                                Linkage, 0, Name);
1043218893Sdim
1044218893Sdim  if (OldGV) {
1045218893Sdim    // Replace occurrences of the old variable if needed.
1046218893Sdim    GV->takeName(OldGV);
1047218893Sdim
1048218893Sdim    if (!OldGV->use_empty()) {
1049218893Sdim      llvm::Constant *NewPtrForOldDecl =
1050218893Sdim      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1051218893Sdim      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1052218893Sdim    }
1053218893Sdim
1054218893Sdim    OldGV->eraseFromParent();
1055218893Sdim  }
1056218893Sdim
1057218893Sdim  return GV;
1058218893Sdim}
1059218893Sdim
1060193326Sed/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1061193326Sed/// given global variable.  If Ty is non-null and if the global doesn't exist,
1062193326Sed/// then it will be greated with the specified type instead of whatever the
1063193326Sed/// normal requested type would be.
1064193326Sedllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1065193326Sed                                                  const llvm::Type *Ty) {
1066193326Sed  assert(D->hasGlobalStorage() && "Not a global variable");
1067193326Sed  QualType ASTTy = D->getType();
1068193326Sed  if (Ty == 0)
1069193326Sed    Ty = getTypes().ConvertTypeForMem(ASTTy);
1070198092Srdivacky
1071198092Srdivacky  const llvm::PointerType *PTy =
1072221345Sdim    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1073205408Srdivacky
1074210299Sed  llvm::StringRef MangledName = getMangledName(D);
1075205408Srdivacky  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1076193326Sed}
1077193326Sed
1078193326Sed/// CreateRuntimeVariable - Create a new runtime global variable with the
1079193326Sed/// specified type and name.
1080193326Sedllvm::Constant *
1081193326SedCodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
1082205408Srdivacky                                     llvm::StringRef Name) {
1083221345Sdim  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1084218893Sdim                               true);
1085193326Sed}
1086193326Sed
1087193326Sedvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1088193326Sed  assert(!D->getInit() && "Cannot emit definite definitions here!");
1089193326Sed
1090193326Sed  if (MayDeferGeneration(D)) {
1091193326Sed    // If we have not seen a reference to this variable yet, place it
1092193326Sed    // into the deferred declarations table to be emitted if needed
1093193326Sed    // later.
1094210299Sed    llvm::StringRef MangledName = getMangledName(D);
1095205408Srdivacky    if (!GetGlobalValue(MangledName)) {
1096198092Srdivacky      DeferredDecls[MangledName] = D;
1097193326Sed      return;
1098193326Sed    }
1099193326Sed  }
1100193326Sed
1101193326Sed  // The tentative definition is the only definition.
1102193326Sed  EmitGlobalVarDefinition(D);
1103193326Sed}
1104193326Sed
1105208600Srdivackyvoid CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1106208600Srdivacky  if (DefinitionRequired)
1107208600Srdivacky    getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1108208600Srdivacky}
1109208600Srdivacky
1110202379Srdivackyllvm::GlobalVariable::LinkageTypes
1111207619SrdivackyCodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1112202379Srdivacky  if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1113202379Srdivacky    return llvm::GlobalVariable::InternalLinkage;
1114202379Srdivacky
1115202379Srdivacky  if (const CXXMethodDecl *KeyFunction
1116202379Srdivacky                                    = RD->getASTContext().getKeyFunction(RD)) {
1117202379Srdivacky    // If this class has a key function, use that to determine the linkage of
1118202379Srdivacky    // the vtable.
1119202379Srdivacky    const FunctionDecl *Def = 0;
1120210299Sed    if (KeyFunction->hasBody(Def))
1121202379Srdivacky      KeyFunction = cast<CXXMethodDecl>(Def);
1122202379Srdivacky
1123202379Srdivacky    switch (KeyFunction->getTemplateSpecializationKind()) {
1124202379Srdivacky      case TSK_Undeclared:
1125202379Srdivacky      case TSK_ExplicitSpecialization:
1126218893Sdim        // When compiling with optimizations turned on, we emit all vtables,
1127218893Sdim        // even if the key function is not defined in the current translation
1128218893Sdim        // unit. If this is the case, use available_externally linkage.
1129218893Sdim        if (!Def && CodeGenOpts.OptimizationLevel)
1130218893Sdim          return llvm::GlobalVariable::AvailableExternallyLinkage;
1131218893Sdim
1132202379Srdivacky        if (KeyFunction->isInlined())
1133218893Sdim          return !Context.getLangOptions().AppleKext ?
1134218893Sdim                   llvm::GlobalVariable::LinkOnceODRLinkage :
1135218893Sdim                   llvm::Function::InternalLinkage;
1136202379Srdivacky
1137202379Srdivacky        return llvm::GlobalVariable::ExternalLinkage;
1138202379Srdivacky
1139202379Srdivacky      case TSK_ImplicitInstantiation:
1140218893Sdim        return !Context.getLangOptions().AppleKext ?
1141218893Sdim                 llvm::GlobalVariable::LinkOnceODRLinkage :
1142218893Sdim                 llvm::Function::InternalLinkage;
1143218893Sdim
1144202379Srdivacky      case TSK_ExplicitInstantiationDefinition:
1145218893Sdim        return !Context.getLangOptions().AppleKext ?
1146218893Sdim                 llvm::GlobalVariable::WeakODRLinkage :
1147218893Sdim                 llvm::Function::InternalLinkage;
1148218893Sdim
1149202379Srdivacky      case TSK_ExplicitInstantiationDeclaration:
1150202379Srdivacky        // FIXME: Use available_externally linkage. However, this currently
1151202379Srdivacky        // breaks LLVM's build due to undefined symbols.
1152202379Srdivacky        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1153218893Sdim        return !Context.getLangOptions().AppleKext ?
1154218893Sdim                 llvm::GlobalVariable::LinkOnceODRLinkage :
1155218893Sdim                 llvm::Function::InternalLinkage;
1156202379Srdivacky    }
1157202379Srdivacky  }
1158202379Srdivacky
1159218893Sdim  if (Context.getLangOptions().AppleKext)
1160218893Sdim    return llvm::Function::InternalLinkage;
1161218893Sdim
1162202379Srdivacky  switch (RD->getTemplateSpecializationKind()) {
1163202379Srdivacky  case TSK_Undeclared:
1164202379Srdivacky  case TSK_ExplicitSpecialization:
1165202379Srdivacky  case TSK_ImplicitInstantiation:
1166202379Srdivacky    // FIXME: Use available_externally linkage. However, this currently
1167202379Srdivacky    // breaks LLVM's build due to undefined symbols.
1168202379Srdivacky    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1169218893Sdim  case TSK_ExplicitInstantiationDeclaration:
1170218893Sdim    return llvm::GlobalVariable::LinkOnceODRLinkage;
1171218893Sdim
1172218893Sdim  case TSK_ExplicitInstantiationDefinition:
1173218893Sdim      return llvm::GlobalVariable::WeakODRLinkage;
1174202379Srdivacky  }
1175202379Srdivacky
1176202379Srdivacky  // Silence GCC warning.
1177218893Sdim  return llvm::GlobalVariable::LinkOnceODRLinkage;
1178202379Srdivacky}
1179202379Srdivacky
1180203955SrdivackyCharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1181218893Sdim    return Context.toCharUnitsFromBits(
1182218893Sdim      TheTargetData.getTypeStoreSizeInBits(Ty));
1183203955Srdivacky}
1184203955Srdivacky
1185193326Sedvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1186193326Sed  llvm::Constant *Init = 0;
1187193326Sed  QualType ASTTy = D->getType();
1188202379Srdivacky  bool NonConstInit = false;
1189198092Srdivacky
1190203955Srdivacky  const Expr *InitExpr = D->getAnyInitializer();
1191203955Srdivacky
1192203955Srdivacky  if (!InitExpr) {
1193193326Sed    // This is a tentative definition; tentative definitions are
1194193326Sed    // implicitly initialized with { 0 }.
1195193326Sed    //
1196193326Sed    // Note that tentative definitions are only emitted at the end of
1197193326Sed    // a translation unit, so they should never have incomplete
1198193326Sed    // type. In addition, EmitTentativeDefinition makes sure that we
1199193326Sed    // never attempt to emit a tentative definition if a real one
1200193326Sed    // exists. A use may still exists, however, so we still may need
1201193326Sed    // to do a RAUW.
1202193326Sed    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1203198092Srdivacky    Init = EmitNullConstant(D->getType());
1204193326Sed  } else {
1205208600Srdivacky    Init = EmitConstantExpr(InitExpr, D->getType());
1206193326Sed    if (!Init) {
1207203955Srdivacky      QualType T = InitExpr->getType();
1208208600Srdivacky      if (D->getType()->isReferenceType())
1209208600Srdivacky        T = D->getType();
1210208600Srdivacky
1211198092Srdivacky      if (getLangOptions().CPlusPlus) {
1212198092Srdivacky        Init = EmitNullConstant(T);
1213202379Srdivacky        NonConstInit = true;
1214198092Srdivacky      } else {
1215198092Srdivacky        ErrorUnsupported(D, "static initializer");
1216198092Srdivacky        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1217198092Srdivacky      }
1218212904Sdim    } else {
1219212904Sdim      // We don't need an initializer, so remove the entry for the delayed
1220212904Sdim      // initializer position (just in case this entry was delayed).
1221212904Sdim      if (getLangOptions().CPlusPlus)
1222212904Sdim        DelayedCXXInitPosition.erase(D);
1223193326Sed    }
1224193326Sed  }
1225193326Sed
1226193326Sed  const llvm::Type* InitType = Init->getType();
1227193326Sed  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1228198092Srdivacky
1229193326Sed  // Strip off a bitcast if we got one back.
1230193326Sed  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1231198092Srdivacky    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1232198092Srdivacky           // all zero index gep.
1233198092Srdivacky           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1234193326Sed    Entry = CE->getOperand(0);
1235193326Sed  }
1236198092Srdivacky
1237193326Sed  // Entry is now either a Function or GlobalVariable.
1238193326Sed  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1239198092Srdivacky
1240193326Sed  // We have a definition after a declaration with the wrong type.
1241193326Sed  // We must make a new GlobalVariable* and update everything that used OldGV
1242193326Sed  // (a declaration or tentative definition) with the new GlobalVariable*
1243193326Sed  // (which will be a definition).
1244193326Sed  //
1245193326Sed  // This happens if there is a prototype for a global (e.g.
1246193326Sed  // "extern int x[];") and then a definition of a different type (e.g.
1247193326Sed  // "int x[10];"). This also happens when an initializer has a different type
1248193326Sed  // from the type of the global (this happens with unions).
1249193326Sed  if (GV == 0 ||
1250193326Sed      GV->getType()->getElementType() != InitType ||
1251221345Sdim      GV->getType()->getAddressSpace() !=
1252221345Sdim        getContext().getTargetAddressSpace(ASTTy)) {
1253198092Srdivacky
1254205408Srdivacky    // Move the old entry aside so that we'll create a new one.
1255205408Srdivacky    Entry->setName(llvm::StringRef());
1256193326Sed
1257193326Sed    // Make a new global with the correct type, this is now guaranteed to work.
1258193326Sed    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1259193326Sed
1260193326Sed    // Replace all uses of the old global with the new global
1261198092Srdivacky    llvm::Constant *NewPtrForOldDecl =
1262193326Sed        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1263193326Sed    Entry->replaceAllUsesWith(NewPtrForOldDecl);
1264193326Sed
1265193326Sed    // Erase the old global, since it is no longer used.
1266193326Sed    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1267193326Sed  }
1268193326Sed
1269195341Sed  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1270193326Sed    SourceManager &SM = Context.getSourceManager();
1271193326Sed    AddAnnotation(EmitAnnotateAttr(GV, AA,
1272193326Sed                              SM.getInstantiationLineNumber(D->getLocation())));
1273193326Sed  }
1274193326Sed
1275193326Sed  GV->setInitializer(Init);
1276198092Srdivacky
1277198092Srdivacky  // If it is safe to mark the global 'constant', do so now.
1278198092Srdivacky  GV->setConstant(false);
1279202379Srdivacky  if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1280198092Srdivacky    GV->setConstant(true);
1281198092Srdivacky
1282203955Srdivacky  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1283218893Sdim
1284218893Sdim  // Set the llvm linkage type as appropriate.
1285218893Sdim  llvm::GlobalValue::LinkageTypes Linkage =
1286218893Sdim    GetLLVMLinkageVarDefinition(D, GV);
1287218893Sdim  GV->setLinkage(Linkage);
1288218893Sdim  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1289218893Sdim    // common vars aren't constant even if declared const.
1290218893Sdim    GV->setConstant(false);
1291193326Sed
1292218893Sdim  SetCommonAttributes(D, GV);
1293218893Sdim
1294218893Sdim  // Emit the initializer function if necessary.
1295218893Sdim  if (NonConstInit)
1296218893Sdim    EmitCXXGlobalVarDeclInitFunc(D, GV);
1297218893Sdim
1298218893Sdim  // Emit global variable debug information.
1299221345Sdim  if (CGDebugInfo *DI = getModuleDebugInfo()) {
1300218893Sdim    DI->setLocation(D->getLocation());
1301218893Sdim    DI->EmitGlobalVariable(GV, D);
1302218893Sdim  }
1303218893Sdim}
1304218893Sdim
1305218893Sdimllvm::GlobalValue::LinkageTypes
1306218893SdimCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1307218893Sdim                                           llvm::GlobalVariable *GV) {
1308212904Sdim  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1309198112Srdivacky  if (Linkage == GVA_Internal)
1310218893Sdim    return llvm::Function::InternalLinkage;
1311195341Sed  else if (D->hasAttr<DLLImportAttr>())
1312218893Sdim    return llvm::Function::DLLImportLinkage;
1313195341Sed  else if (D->hasAttr<DLLExportAttr>())
1314218893Sdim    return llvm::Function::DLLExportLinkage;
1315198092Srdivacky  else if (D->hasAttr<WeakAttr>()) {
1316198092Srdivacky    if (GV->isConstant())
1317218893Sdim      return llvm::GlobalVariable::WeakODRLinkage;
1318198092Srdivacky    else
1319218893Sdim      return llvm::GlobalVariable::WeakAnyLinkage;
1320205219Srdivacky  } else if (Linkage == GVA_TemplateInstantiation ||
1321205219Srdivacky             Linkage == GVA_ExplicitTemplateInstantiation)
1322221345Sdim    return llvm::GlobalVariable::WeakODRLinkage;
1323218893Sdim  else if (!getLangOptions().CPlusPlus &&
1324218893Sdim           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1325218893Sdim             D->getAttr<CommonAttr>()) &&
1326198092Srdivacky           !D->hasExternalStorage() && !D->getInit() &&
1327212904Sdim           !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1328212904Sdim    // Thread local vars aren't considered common linkage.
1329218893Sdim    return llvm::GlobalVariable::CommonLinkage;
1330193326Sed  }
1331218893Sdim  return llvm::GlobalVariable::ExternalLinkage;
1332193326Sed}
1333193326Sed
1334193326Sed/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1335193326Sed/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1336193326Sed/// existing call uses of the old function in the module, this adjusts them to
1337193326Sed/// call the new function directly.
1338193326Sed///
1339193326Sed/// This is not just a cleanup: the always_inline pass requires direct calls to
1340193326Sed/// functions to be able to inline them.  If there is a bitcast in the way, it
1341193326Sed/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1342193326Sed/// run at -O0.
1343193326Sedstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1344193326Sed                                                      llvm::Function *NewFn) {
1345193326Sed  // If we're redefining a global as a function, don't transform it.
1346193326Sed  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1347193326Sed  if (OldFn == 0) return;
1348198092Srdivacky
1349193326Sed  const llvm::Type *NewRetTy = NewFn->getReturnType();
1350193326Sed  llvm::SmallVector<llvm::Value*, 4> ArgList;
1351193326Sed
1352193326Sed  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1353193326Sed       UI != E; ) {
1354193326Sed    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1355207619Srdivacky    llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1356207619Srdivacky    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1357212904Sdim    if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1358207619Srdivacky    llvm::CallSite CS(CI);
1359207619Srdivacky    if (!CI || !CS.isCallee(I)) continue;
1360198092Srdivacky
1361193326Sed    // If the return types don't match exactly, and if the call isn't dead, then
1362193326Sed    // we can't transform this call.
1363193326Sed    if (CI->getType() != NewRetTy && !CI->use_empty())
1364193326Sed      continue;
1365193326Sed
1366193326Sed    // If the function was passed too few arguments, don't transform.  If extra
1367193326Sed    // arguments were passed, we silently drop them.  If any of the types
1368193326Sed    // mismatch, we don't transform.
1369193326Sed    unsigned ArgNo = 0;
1370193326Sed    bool DontTransform = false;
1371193326Sed    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1372193326Sed         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1373207619Srdivacky      if (CS.arg_size() == ArgNo ||
1374207619Srdivacky          CS.getArgument(ArgNo)->getType() != AI->getType()) {
1375193326Sed        DontTransform = true;
1376193326Sed        break;
1377193326Sed      }
1378193326Sed    }
1379193326Sed    if (DontTransform)
1380193326Sed      continue;
1381198092Srdivacky
1382193326Sed    // Okay, we can transform this.  Create the new call instruction and copy
1383193326Sed    // over the required information.
1384207619Srdivacky    ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1385193326Sed    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1386193326Sed                                                     ArgList.end(), "", CI);
1387193326Sed    ArgList.clear();
1388198092Srdivacky    if (!NewCall->getType()->isVoidTy())
1389193326Sed      NewCall->takeName(CI);
1390198092Srdivacky    NewCall->setAttributes(CI->getAttributes());
1391193326Sed    NewCall->setCallingConv(CI->getCallingConv());
1392193326Sed
1393193326Sed    // Finally, remove the old call, replacing any uses with the new one.
1394193326Sed    if (!CI->use_empty())
1395193326Sed      CI->replaceAllUsesWith(NewCall);
1396198092Srdivacky
1397206084Srdivacky    // Copy debug location attached to CI.
1398206084Srdivacky    if (!CI->getDebugLoc().isUnknown())
1399206084Srdivacky      NewCall->setDebugLoc(CI->getDebugLoc());
1400193326Sed    CI->eraseFromParent();
1401193326Sed  }
1402193326Sed}
1403193326Sed
1404193326Sed
1405193326Sedvoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1406193326Sed  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1407221345Sdim
1408221345Sdim  // Compute the function info and LLVM type.
1409221345Sdim  const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
1410221345Sdim  bool variadic = false;
1411221345Sdim  if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1412221345Sdim    variadic = fpt->isVariadic();
1413221345Sdim  const llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic, false);
1414221345Sdim
1415193326Sed  // Get or create the prototype for the function.
1416193326Sed  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1417198092Srdivacky
1418193326Sed  // Strip off a bitcast if we got one back.
1419193326Sed  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1420193326Sed    assert(CE->getOpcode() == llvm::Instruction::BitCast);
1421193326Sed    Entry = CE->getOperand(0);
1422193326Sed  }
1423198092Srdivacky
1424198092Srdivacky
1425193326Sed  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1426193326Sed    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1427198092Srdivacky
1428193326Sed    // If the types mismatch then we have to rewrite the definition.
1429193326Sed    assert(OldFn->isDeclaration() &&
1430193326Sed           "Shouldn't replace non-declaration");
1431193326Sed
1432193326Sed    // F is the Function* for the one with the wrong type, we must make a new
1433193326Sed    // Function* and update everything that used F (a declaration) with the new
1434193326Sed    // Function* (which will be a definition).
1435193326Sed    //
1436193326Sed    // This happens if there is a prototype for a function
1437193326Sed    // (e.g. "int f()") and then a definition of a different type
1438205408Srdivacky    // (e.g. "int f(int x)").  Move the old function aside so that it
1439205408Srdivacky    // doesn't interfere with GetAddrOfFunction.
1440205408Srdivacky    OldFn->setName(llvm::StringRef());
1441193326Sed    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1442198092Srdivacky
1443193326Sed    // If this is an implementation of a function without a prototype, try to
1444193326Sed    // replace any existing uses of the function (which may be calls) with uses
1445193326Sed    // of the new function
1446193326Sed    if (D->getType()->isFunctionNoProtoType()) {
1447193326Sed      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1448193326Sed      OldFn->removeDeadConstantUsers();
1449193326Sed    }
1450198092Srdivacky
1451193326Sed    // Replace uses of F with the Function we will endow with a body.
1452193326Sed    if (!Entry->use_empty()) {
1453198092Srdivacky      llvm::Constant *NewPtrForOldDecl =
1454193326Sed        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1455193326Sed      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1456193326Sed    }
1457198092Srdivacky
1458193326Sed    // Ok, delete the old function now, which is dead.
1459193326Sed    OldFn->eraseFromParent();
1460198092Srdivacky
1461193326Sed    Entry = NewFn;
1462193326Sed  }
1463198092Srdivacky
1464218893Sdim  // We need to set linkage and visibility on the function before
1465218893Sdim  // generating code for it because various parts of IR generation
1466218893Sdim  // want to propagate this information down (e.g. to local static
1467218893Sdim  // declarations).
1468193326Sed  llvm::Function *Fn = cast<llvm::Function>(Entry);
1469208600Srdivacky  setFunctionLinkage(D, Fn);
1470193326Sed
1471218893Sdim  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1472218893Sdim  setGlobalVisibility(Fn, D);
1473218893Sdim
1474221345Sdim  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1475193326Sed
1476193326Sed  SetFunctionDefinitionAttributes(D, Fn);
1477193326Sed  SetLLVMFunctionAttributesForDefinition(D, Fn);
1478198092Srdivacky
1479195341Sed  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1480193326Sed    AddGlobalCtor(Fn, CA->getPriority());
1481195341Sed  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1482193326Sed    AddGlobalDtor(Fn, DA->getPriority());
1483193326Sed}
1484193326Sed
1485205408Srdivackyvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1486205408Srdivacky  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1487195341Sed  const AliasAttr *AA = D->getAttr<AliasAttr>();
1488193326Sed  assert(AA && "Not an alias?");
1489193326Sed
1490210299Sed  llvm::StringRef MangledName = getMangledName(GD);
1491205408Srdivacky
1492205408Srdivacky  // If there is a definition in the module, then it wins over the alias.
1493205408Srdivacky  // This is dubious, but allow it to be safe.  Just ignore the alias.
1494205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1495205408Srdivacky  if (Entry && !Entry->isDeclaration())
1496205408Srdivacky    return;
1497205408Srdivacky
1498193326Sed  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1499198092Srdivacky
1500193326Sed  // Create a reference to the named value.  This ensures that it is emitted
1501193326Sed  // if a deferred decl.
1502193326Sed  llvm::Constant *Aliasee;
1503193326Sed  if (isa<llvm::FunctionType>(DeclTy))
1504218893Sdim    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1505218893Sdim                                      /*ForVTable=*/false);
1506193326Sed  else
1507205408Srdivacky    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1508193326Sed                                    llvm::PointerType::getUnqual(DeclTy), 0);
1509193326Sed
1510193326Sed  // Create the new alias itself, but don't set a name yet.
1511198092Srdivacky  llvm::GlobalValue *GA =
1512193326Sed    new llvm::GlobalAlias(Aliasee->getType(),
1513193326Sed                          llvm::Function::ExternalLinkage,
1514193326Sed                          "", Aliasee, &getModule());
1515198092Srdivacky
1516205408Srdivacky  if (Entry) {
1517205408Srdivacky    assert(Entry->isDeclaration());
1518198092Srdivacky
1519193326Sed    // If there is a declaration in the module, then we had an extern followed
1520193326Sed    // by the alias, as in:
1521193326Sed    //   extern int test6();
1522193326Sed    //   ...
1523193326Sed    //   int test6() __attribute__((alias("test7")));
1524193326Sed    //
1525193326Sed    // Remove it and replace uses of it with the alias.
1526205408Srdivacky    GA->takeName(Entry);
1527198092Srdivacky
1528193326Sed    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1529193326Sed                                                          Entry->getType()));
1530193326Sed    Entry->eraseFromParent();
1531205408Srdivacky  } else {
1532210299Sed    GA->setName(MangledName);
1533193326Sed  }
1534198092Srdivacky
1535193326Sed  // Set attributes which are particular to an alias; this is a
1536193326Sed  // specialization of the attributes which may be set on a global
1537193326Sed  // variable/function.
1538195341Sed  if (D->hasAttr<DLLExportAttr>()) {
1539193326Sed    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1540193326Sed      // The dllexport attribute is ignored for undefined symbols.
1541210299Sed      if (FD->hasBody())
1542193326Sed        GA->setLinkage(llvm::Function::DLLExportLinkage);
1543193326Sed    } else {
1544193326Sed      GA->setLinkage(llvm::Function::DLLExportLinkage);
1545193326Sed    }
1546198092Srdivacky  } else if (D->hasAttr<WeakAttr>() ||
1547204643Srdivacky             D->hasAttr<WeakRefAttr>() ||
1548221345Sdim             D->isWeakImported()) {
1549193326Sed    GA->setLinkage(llvm::Function::WeakAnyLinkage);
1550193326Sed  }
1551193326Sed
1552193326Sed  SetCommonAttributes(D, GA);
1553193326Sed}
1554193326Sed
1555193326Sed/// getBuiltinLibFunction - Given a builtin id for a function like
1556193326Sed/// "__builtin_fabsf", return a Function* for "fabsf".
1557198092Srdivackyllvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1558198092Srdivacky                                                  unsigned BuiltinID) {
1559193326Sed  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1560198092Srdivacky          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1561193326Sed         "isn't a lib fn");
1562198092Srdivacky
1563193326Sed  // Get the name, skip over the __builtin_ prefix (if necessary).
1564193326Sed  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1565193326Sed  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1566193326Sed    Name += 10;
1567198092Srdivacky
1568198092Srdivacky  const llvm::FunctionType *Ty =
1569200583Srdivacky    cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1570193326Sed
1571218893Sdim  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD), /*ForVTable=*/false);
1572193326Sed}
1573193326Sed
1574193326Sedllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1575193326Sed                                            unsigned NumTys) {
1576193326Sed  return llvm::Intrinsic::getDeclaration(&getModule(),
1577193326Sed                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
1578193326Sed}
1579193326Sed
1580198092Srdivackystatic llvm::StringMapEntry<llvm::Constant*> &
1581198092SrdivackyGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1582198092Srdivacky                         const StringLiteral *Literal,
1583198092Srdivacky                         bool TargetIsLSB,
1584198092Srdivacky                         bool &IsUTF16,
1585198092Srdivacky                         unsigned &StringLength) {
1586212904Sdim  llvm::StringRef String = Literal->getString();
1587212904Sdim  unsigned NumBytes = String.size();
1588198092Srdivacky
1589198092Srdivacky  // Check for simple case.
1590198092Srdivacky  if (!Literal->containsNonAsciiOrNull()) {
1591198092Srdivacky    StringLength = NumBytes;
1592212904Sdim    return Map.GetOrCreateValue(String);
1593193326Sed  }
1594198092Srdivacky
1595198092Srdivacky  // Otherwise, convert the UTF8 literals into a byte string.
1596198092Srdivacky  llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1597212904Sdim  const UTF8 *FromPtr = (UTF8 *)String.data();
1598198092Srdivacky  UTF16 *ToPtr = &ToBuf[0];
1599198092Srdivacky
1600218893Sdim  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1601218893Sdim                           &ToPtr, ToPtr + NumBytes,
1602218893Sdim                           strictConversion);
1603198092Srdivacky
1604198092Srdivacky  // ConvertUTF8toUTF16 returns the length in ToPtr.
1605198092Srdivacky  StringLength = ToPtr - &ToBuf[0];
1606198092Srdivacky
1607198092Srdivacky  // Render the UTF-16 string into a byte array and convert to the target byte
1608198092Srdivacky  // order.
1609198092Srdivacky  //
1610198092Srdivacky  // FIXME: This isn't something we should need to do here.
1611198092Srdivacky  llvm::SmallString<128> AsBytes;
1612198092Srdivacky  AsBytes.reserve(StringLength * 2);
1613198092Srdivacky  for (unsigned i = 0; i != StringLength; ++i) {
1614198092Srdivacky    unsigned short Val = ToBuf[i];
1615198092Srdivacky    if (TargetIsLSB) {
1616198092Srdivacky      AsBytes.push_back(Val & 0xFF);
1617198092Srdivacky      AsBytes.push_back(Val >> 8);
1618198092Srdivacky    } else {
1619198092Srdivacky      AsBytes.push_back(Val >> 8);
1620198092Srdivacky      AsBytes.push_back(Val & 0xFF);
1621198092Srdivacky    }
1622198092Srdivacky  }
1623198092Srdivacky  // Append one extra null character, the second is automatically added by our
1624198092Srdivacky  // caller.
1625198092Srdivacky  AsBytes.push_back(0);
1626198092Srdivacky
1627198092Srdivacky  IsUTF16 = true;
1628198092Srdivacky  return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1629193326Sed}
1630193326Sed
1631198092Srdivackyllvm::Constant *
1632198092SrdivackyCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1633193326Sed  unsigned StringLength = 0;
1634193326Sed  bool isUTF16 = false;
1635198092Srdivacky  llvm::StringMapEntry<llvm::Constant*> &Entry =
1636198092Srdivacky    GetConstantCFStringEntry(CFConstantStringMap, Literal,
1637198092Srdivacky                             getTargetData().isLittleEndian(),
1638198092Srdivacky                             isUTF16, StringLength);
1639198092Srdivacky
1640193326Sed  if (llvm::Constant *C = Entry.getValue())
1641193326Sed    return C;
1642198092Srdivacky
1643198092Srdivacky  llvm::Constant *Zero =
1644198092Srdivacky      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1645193326Sed  llvm::Constant *Zeros[] = { Zero, Zero };
1646198092Srdivacky
1647198092Srdivacky  // If we don't already have it, get __CFConstantStringClassReference.
1648193326Sed  if (!CFConstantStringClassRef) {
1649193326Sed    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1650193326Sed    Ty = llvm::ArrayType::get(Ty, 0);
1651198092Srdivacky    llvm::Constant *GV = CreateRuntimeVariable(Ty,
1652198092Srdivacky                                           "__CFConstantStringClassReference");
1653193326Sed    // Decay array -> ptr
1654193326Sed    CFConstantStringClassRef =
1655193326Sed      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1656193326Sed  }
1657198092Srdivacky
1658193326Sed  QualType CFTy = getContext().getCFConstantStringType();
1659193326Sed
1660198092Srdivacky  const llvm::StructType *STy =
1661193326Sed    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1662193326Sed
1663198092Srdivacky  std::vector<llvm::Constant*> Fields(4);
1664193326Sed
1665193326Sed  // Class pointer.
1666198092Srdivacky  Fields[0] = CFConstantStringClassRef;
1667198092Srdivacky
1668193326Sed  // Flags.
1669193326Sed  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1670198092Srdivacky  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1671198092Srdivacky    llvm::ConstantInt::get(Ty, 0x07C8);
1672198092Srdivacky
1673193326Sed  // String pointer.
1674198092Srdivacky  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1675193326Sed
1676198092Srdivacky  llvm::GlobalValue::LinkageTypes Linkage;
1677193326Sed  bool isConstant;
1678193326Sed  if (isUTF16) {
1679198092Srdivacky    // FIXME: why do utf strings get "_" labels instead of "L" labels?
1680198092Srdivacky    Linkage = llvm::GlobalValue::InternalLinkage;
1681198092Srdivacky    // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1682198092Srdivacky    // does make plain ascii ones writable.
1683198092Srdivacky    isConstant = true;
1684193326Sed  } else {
1685221345Sdim    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1686221345Sdim    // when using private linkage. It is not clear if this is a bug in ld
1687221345Sdim    // or a reasonable new restriction.
1688221345Sdim    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1689198092Srdivacky    isConstant = !Features.WritableStrings;
1690193326Sed  }
1691198092Srdivacky
1692198092Srdivacky  llvm::GlobalVariable *GV =
1693198092Srdivacky    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1694198092Srdivacky                             ".str");
1695218893Sdim  GV->setUnnamedAddr(true);
1696193326Sed  if (isUTF16) {
1697203955Srdivacky    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1698203955Srdivacky    GV->setAlignment(Align.getQuantity());
1699221345Sdim  } else {
1700221345Sdim    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1701221345Sdim    GV->setAlignment(Align.getQuantity());
1702193326Sed  }
1703198092Srdivacky  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1704198092Srdivacky
1705193326Sed  // String length.
1706193326Sed  Ty = getTypes().ConvertType(getContext().LongTy);
1707198092Srdivacky  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1708198092Srdivacky
1709193326Sed  // The struct.
1710193326Sed  C = llvm::ConstantStruct::get(STy, Fields);
1711198092Srdivacky  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1712198092Srdivacky                                llvm::GlobalVariable::PrivateLinkage, C,
1713198092Srdivacky                                "_unnamed_cfstring_");
1714193326Sed  if (const char *Sect = getContext().Target.getCFStringSection())
1715193326Sed    GV->setSection(Sect);
1716193326Sed  Entry.setValue(GV);
1717198092Srdivacky
1718193326Sed  return GV;
1719193326Sed}
1720193326Sed
1721207619Srdivackyllvm::Constant *
1722218893SdimCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1723207619Srdivacky  unsigned StringLength = 0;
1724207619Srdivacky  bool isUTF16 = false;
1725207619Srdivacky  llvm::StringMapEntry<llvm::Constant*> &Entry =
1726207619Srdivacky    GetConstantCFStringEntry(CFConstantStringMap, Literal,
1727207619Srdivacky                             getTargetData().isLittleEndian(),
1728207619Srdivacky                             isUTF16, StringLength);
1729207619Srdivacky
1730207619Srdivacky  if (llvm::Constant *C = Entry.getValue())
1731207619Srdivacky    return C;
1732207619Srdivacky
1733207619Srdivacky  llvm::Constant *Zero =
1734207619Srdivacky  llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1735207619Srdivacky  llvm::Constant *Zeros[] = { Zero, Zero };
1736207619Srdivacky
1737207619Srdivacky  // If we don't already have it, get _NSConstantStringClassReference.
1738218893Sdim  if (!ConstantStringClassRef) {
1739218893Sdim    std::string StringClass(getLangOptions().ObjCConstantStringClass);
1740207619Srdivacky    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1741207619Srdivacky    Ty = llvm::ArrayType::get(Ty, 0);
1742218893Sdim    llvm::Constant *GV;
1743218893Sdim    if (StringClass.empty())
1744218893Sdim      GV = CreateRuntimeVariable(Ty,
1745218893Sdim                                 Features.ObjCNonFragileABI ?
1746218893Sdim                                 "OBJC_CLASS_$_NSConstantString" :
1747218893Sdim                                 "_NSConstantStringClassReference");
1748218893Sdim    else {
1749218893Sdim      std::string str;
1750218893Sdim      if (Features.ObjCNonFragileABI)
1751218893Sdim        str = "OBJC_CLASS_$_" + StringClass;
1752218893Sdim      else
1753218893Sdim        str = "_" + StringClass + "ClassReference";
1754218893Sdim      GV = CreateRuntimeVariable(Ty, str);
1755218893Sdim    }
1756207619Srdivacky    // Decay array -> ptr
1757218893Sdim    ConstantStringClassRef =
1758218893Sdim    llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1759207619Srdivacky  }
1760207619Srdivacky
1761207619Srdivacky  QualType NSTy = getContext().getNSConstantStringType();
1762207619Srdivacky
1763207619Srdivacky  const llvm::StructType *STy =
1764207619Srdivacky  cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1765207619Srdivacky
1766207619Srdivacky  std::vector<llvm::Constant*> Fields(3);
1767207619Srdivacky
1768207619Srdivacky  // Class pointer.
1769218893Sdim  Fields[0] = ConstantStringClassRef;
1770207619Srdivacky
1771207619Srdivacky  // String pointer.
1772207619Srdivacky  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1773207619Srdivacky
1774207619Srdivacky  llvm::GlobalValue::LinkageTypes Linkage;
1775207619Srdivacky  bool isConstant;
1776207619Srdivacky  if (isUTF16) {
1777207619Srdivacky    // FIXME: why do utf strings get "_" labels instead of "L" labels?
1778207619Srdivacky    Linkage = llvm::GlobalValue::InternalLinkage;
1779207619Srdivacky    // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1780207619Srdivacky    // does make plain ascii ones writable.
1781207619Srdivacky    isConstant = true;
1782207619Srdivacky  } else {
1783207619Srdivacky    Linkage = llvm::GlobalValue::PrivateLinkage;
1784207619Srdivacky    isConstant = !Features.WritableStrings;
1785207619Srdivacky  }
1786207619Srdivacky
1787207619Srdivacky  llvm::GlobalVariable *GV =
1788207619Srdivacky  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1789207619Srdivacky                           ".str");
1790218893Sdim  GV->setUnnamedAddr(true);
1791207619Srdivacky  if (isUTF16) {
1792207619Srdivacky    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1793207619Srdivacky    GV->setAlignment(Align.getQuantity());
1794221345Sdim  } else {
1795221345Sdim    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1796221345Sdim    GV->setAlignment(Align.getQuantity());
1797207619Srdivacky  }
1798207619Srdivacky  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1799207619Srdivacky
1800207619Srdivacky  // String length.
1801207619Srdivacky  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1802207619Srdivacky  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1803207619Srdivacky
1804207619Srdivacky  // The struct.
1805207619Srdivacky  C = llvm::ConstantStruct::get(STy, Fields);
1806207619Srdivacky  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1807207619Srdivacky                                llvm::GlobalVariable::PrivateLinkage, C,
1808207619Srdivacky                                "_unnamed_nsstring_");
1809207619Srdivacky  // FIXME. Fix section.
1810207619Srdivacky  if (const char *Sect =
1811207619Srdivacky        Features.ObjCNonFragileABI
1812207619Srdivacky          ? getContext().Target.getNSStringNonFragileABISection()
1813207619Srdivacky          : getContext().Target.getNSStringSection())
1814207619Srdivacky    GV->setSection(Sect);
1815207619Srdivacky  Entry.setValue(GV);
1816207619Srdivacky
1817207619Srdivacky  return GV;
1818207619Srdivacky}
1819207619Srdivacky
1820193326Sed/// GetStringForStringLiteral - Return the appropriate bytes for a
1821193326Sed/// string literal, properly padded to match the literal type.
1822193326Sedstd::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1823218893Sdim  const ASTContext &Context = getContext();
1824193326Sed  const ConstantArrayType *CAT =
1825218893Sdim    Context.getAsConstantArrayType(E->getType());
1826193326Sed  assert(CAT && "String isn't pointer or array!");
1827198092Srdivacky
1828193326Sed  // Resize the string to the right size.
1829193326Sed  uint64_t RealLen = CAT->getSize().getZExtValue();
1830198092Srdivacky
1831193326Sed  if (E->isWide())
1832218893Sdim    RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
1833198092Srdivacky
1834212904Sdim  std::string Str = E->getString().str();
1835193326Sed  Str.resize(RealLen, '\0');
1836198092Srdivacky
1837193326Sed  return Str;
1838193326Sed}
1839193326Sed
1840193326Sed/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1841193326Sed/// constant array for the given string literal.
1842193326Sedllvm::Constant *
1843193326SedCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1844193326Sed  // FIXME: This can be more efficient.
1845199482Srdivacky  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1846199482Srdivacky  llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1847199482Srdivacky  if (S->isWide()) {
1848199482Srdivacky    llvm::Type *DestTy =
1849199482Srdivacky        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1850199482Srdivacky    C = llvm::ConstantExpr::getBitCast(C, DestTy);
1851199482Srdivacky  }
1852199482Srdivacky  return C;
1853193326Sed}
1854193326Sed
1855193326Sed/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1856193326Sed/// array for the given ObjCEncodeExpr node.
1857193326Sedllvm::Constant *
1858193326SedCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1859193326Sed  std::string Str;
1860193326Sed  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1861193326Sed
1862193326Sed  return GetAddrOfConstantCString(Str);
1863193326Sed}
1864193326Sed
1865193326Sed
1866193326Sed/// GenerateWritableString -- Creates storage for a string literal.
1867221345Sdimstatic llvm::Constant *GenerateStringLiteral(llvm::StringRef str,
1868193326Sed                                             bool constant,
1869193326Sed                                             CodeGenModule &CGM,
1870193326Sed                                             const char *GlobalName) {
1871193326Sed  // Create Constant for this string literal. Don't add a '\0'.
1872198092Srdivacky  llvm::Constant *C =
1873198092Srdivacky      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1874198092Srdivacky
1875193326Sed  // Create a global variable for this string
1876218893Sdim  llvm::GlobalVariable *GV =
1877218893Sdim    new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1878218893Sdim                             llvm::GlobalValue::PrivateLinkage,
1879218893Sdim                             C, GlobalName);
1880218893Sdim  GV->setUnnamedAddr(true);
1881218893Sdim  return GV;
1882193326Sed}
1883193326Sed
1884193326Sed/// GetAddrOfConstantString - Returns a pointer to a character array
1885193326Sed/// containing the literal. This contents are exactly that of the
1886193326Sed/// given string, i.e. it will not be null terminated automatically;
1887193326Sed/// see GetAddrOfConstantCString. Note that whether the result is
1888193326Sed/// actually a pointer to an LLVM constant depends on
1889193326Sed/// Feature.WriteableStrings.
1890193326Sed///
1891193326Sed/// The result has pointer to array type.
1892221345Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantString(llvm::StringRef Str,
1893193326Sed                                                       const char *GlobalName) {
1894193326Sed  bool IsConstant = !Features.WritableStrings;
1895193326Sed
1896193326Sed  // Get the default prefix if a name wasn't specified.
1897193326Sed  if (!GlobalName)
1898198092Srdivacky    GlobalName = ".str";
1899193326Sed
1900193326Sed  // Don't share any string literals if strings aren't constant.
1901193326Sed  if (!IsConstant)
1902221345Sdim    return GenerateStringLiteral(Str, false, *this, GlobalName);
1903193326Sed
1904198092Srdivacky  llvm::StringMapEntry<llvm::Constant *> &Entry =
1905221345Sdim    ConstantStringMap.GetOrCreateValue(Str);
1906198092Srdivacky
1907193326Sed  if (Entry.getValue())
1908193326Sed    return Entry.getValue();
1909193326Sed
1910193326Sed  // Create a global variable for this.
1911221345Sdim  llvm::Constant *C = GenerateStringLiteral(Str, true, *this, GlobalName);
1912193326Sed  Entry.setValue(C);
1913193326Sed  return C;
1914193326Sed}
1915193326Sed
1916193326Sed/// GetAddrOfConstantCString - Returns a pointer to a character
1917221345Sdim/// array containing the literal and a terminating '\0'
1918193326Sed/// character. The result has pointer to array type.
1919221345Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
1920193326Sed                                                        const char *GlobalName){
1921221345Sdim  llvm::StringRef StrWithNull(Str.c_str(), Str.size() + 1);
1922221345Sdim  return GetAddrOfConstantString(StrWithNull, GlobalName);
1923193326Sed}
1924193326Sed
1925193326Sed/// EmitObjCPropertyImplementations - Emit information for synthesized
1926193326Sed/// properties for an implementation.
1927198092Srdivackyvoid CodeGenModule::EmitObjCPropertyImplementations(const
1928193326Sed                                                    ObjCImplementationDecl *D) {
1929198092Srdivacky  for (ObjCImplementationDecl::propimpl_iterator
1930195341Sed         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1931193326Sed    ObjCPropertyImplDecl *PID = *i;
1932198092Srdivacky
1933193326Sed    // Dynamic is just for type-checking.
1934193326Sed    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1935193326Sed      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1936193326Sed
1937193326Sed      // Determine which methods need to be implemented, some may have
1938193326Sed      // been overridden. Note that ::isSynthesized is not the method
1939193326Sed      // we want, that just indicates if the decl came from a
1940193326Sed      // property. What we want to know is if the method is defined in
1941193326Sed      // this implementation.
1942195341Sed      if (!D->getInstanceMethod(PD->getGetterName()))
1943193326Sed        CodeGenFunction(*this).GenerateObjCGetter(
1944193326Sed                                 const_cast<ObjCImplementationDecl *>(D), PID);
1945193326Sed      if (!PD->isReadOnly() &&
1946195341Sed          !D->getInstanceMethod(PD->getSetterName()))
1947193326Sed        CodeGenFunction(*this).GenerateObjCSetter(
1948193326Sed                                 const_cast<ObjCImplementationDecl *>(D), PID);
1949193326Sed    }
1950193326Sed  }
1951193326Sed}
1952193326Sed
1953221345Sdimstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
1954221345Sdim  ObjCInterfaceDecl *iface
1955221345Sdim    = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
1956221345Sdim  for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1957221345Sdim       ivar; ivar = ivar->getNextIvar())
1958221345Sdim    if (ivar->getType().isDestructedType())
1959221345Sdim      return true;
1960221345Sdim
1961221345Sdim  return false;
1962221345Sdim}
1963221345Sdim
1964207619Srdivacky/// EmitObjCIvarInitializations - Emit information for ivar initialization
1965207619Srdivacky/// for an implementation.
1966207619Srdivackyvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1967221345Sdim  // We might need a .cxx_destruct even if we don't have any ivar initializers.
1968221345Sdim  if (needsDestructMethod(D)) {
1969221345Sdim    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1970221345Sdim    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1971221345Sdim    ObjCMethodDecl *DTORMethod =
1972221345Sdim      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
1973221345Sdim                             cxxSelector, getContext().VoidTy, 0, D, true,
1974221345Sdim                             false, true, false, ObjCMethodDecl::Required);
1975221345Sdim    D->addInstanceMethod(DTORMethod);
1976221345Sdim    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1977221345Sdim  }
1978221345Sdim
1979221345Sdim  // If the implementation doesn't have any ivar initializers, we don't need
1980221345Sdim  // a .cxx_construct.
1981221345Sdim  if (D->getNumIvarInitializers() == 0)
1982207619Srdivacky    return;
1983221345Sdim
1984221345Sdim  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
1985207619Srdivacky  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1986207619Srdivacky  // The constructor returns 'self'.
1987207619Srdivacky  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1988207619Srdivacky                                                D->getLocation(),
1989207619Srdivacky                                                D->getLocation(), cxxSelector,
1990207619Srdivacky                                                getContext().getObjCIdType(), 0,
1991221345Sdim                                                D, true, false, true, false,
1992207619Srdivacky                                                ObjCMethodDecl::Required);
1993207619Srdivacky  D->addInstanceMethod(CTORMethod);
1994207619Srdivacky  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1995207619Srdivacky}
1996207619Srdivacky
1997193326Sed/// EmitNamespace - Emit all declarations in a namespace.
1998193326Sedvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1999195341Sed  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2000193326Sed       I != E; ++I)
2001193326Sed    EmitTopLevelDecl(*I);
2002193326Sed}
2003193326Sed
2004193326Sed// EmitLinkageSpec - Emit all declarations in a linkage spec.
2005193326Sedvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2006198092Srdivacky  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2007198092Srdivacky      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2008193326Sed    ErrorUnsupported(LSD, "linkage spec");
2009193326Sed    return;
2010193326Sed  }
2011193326Sed
2012195341Sed  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2013193326Sed       I != E; ++I)
2014193326Sed    EmitTopLevelDecl(*I);
2015193326Sed}
2016193326Sed
2017193326Sed/// EmitTopLevelDecl - Emit code for a single top level declaration.
2018193326Sedvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
2019193326Sed  // If an error has occurred, stop code generation, but continue
2020193326Sed  // parsing and semantic analysis (to ensure all warnings and errors
2021193326Sed  // are emitted).
2022193326Sed  if (Diags.hasErrorOccurred())
2023193326Sed    return;
2024193326Sed
2025195341Sed  // Ignore dependent declarations.
2026195341Sed  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2027195341Sed    return;
2028198092Srdivacky
2029193326Sed  switch (D->getKind()) {
2030198092Srdivacky  case Decl::CXXConversion:
2031193326Sed  case Decl::CXXMethod:
2032193326Sed  case Decl::Function:
2033195341Sed    // Skip function templates
2034221345Sdim    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2035221345Sdim        cast<FunctionDecl>(D)->isLateTemplateParsed())
2036195341Sed      return;
2037198092Srdivacky
2038198092Srdivacky    EmitGlobal(cast<FunctionDecl>(D));
2039198092Srdivacky    break;
2040195341Sed
2041193326Sed  case Decl::Var:
2042198092Srdivacky    EmitGlobal(cast<VarDecl>(D));
2043193326Sed    break;
2044193326Sed
2045221345Sdim  // Indirect fields from global anonymous structs and unions can be
2046221345Sdim  // ignored; only the actual variable requires IR gen support.
2047221345Sdim  case Decl::IndirectField:
2048221345Sdim    break;
2049221345Sdim
2050193326Sed  // C++ Decls
2051193326Sed  case Decl::Namespace:
2052193326Sed    EmitNamespace(cast<NamespaceDecl>(D));
2053193326Sed    break;
2054194613Sed    // No code generation needed.
2055199482Srdivacky  case Decl::UsingShadow:
2056194613Sed  case Decl::Using:
2057198092Srdivacky  case Decl::UsingDirective:
2058195341Sed  case Decl::ClassTemplate:
2059195341Sed  case Decl::FunctionTemplate:
2060198092Srdivacky  case Decl::NamespaceAlias:
2061194613Sed    break;
2062193326Sed  case Decl::CXXConstructor:
2063199990Srdivacky    // Skip function templates
2064221345Sdim    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2065221345Sdim        cast<FunctionDecl>(D)->isLateTemplateParsed())
2066199990Srdivacky      return;
2067199990Srdivacky
2068193326Sed    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2069193326Sed    break;
2070193326Sed  case Decl::CXXDestructor:
2071221345Sdim    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2072221345Sdim      return;
2073193326Sed    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2074193326Sed    break;
2075194179Sed
2076194179Sed  case Decl::StaticAssert:
2077194179Sed    // Nothing to do.
2078194179Sed    break;
2079194179Sed
2080193326Sed  // Objective-C Decls
2081198092Srdivacky
2082193326Sed  // Forward declarations, no (immediate) code generation.
2083193326Sed  case Decl::ObjCClass:
2084193326Sed  case Decl::ObjCForwardProtocol:
2085193326Sed  case Decl::ObjCInterface:
2086193326Sed    break;
2087212904Sdim
2088221345Sdim  case Decl::ObjCCategory: {
2089221345Sdim    ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2090221345Sdim    if (CD->IsClassExtension() && CD->hasSynthBitfield())
2091221345Sdim      Context.ResetObjCLayout(CD->getClassInterface());
2092221345Sdim    break;
2093221345Sdim  }
2094193326Sed
2095193326Sed  case Decl::ObjCProtocol:
2096193326Sed    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2097193326Sed    break;
2098193326Sed
2099193326Sed  case Decl::ObjCCategoryImpl:
2100193326Sed    // Categories have properties but don't support synthesize so we
2101193326Sed    // can ignore them here.
2102193326Sed    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2103193326Sed    break;
2104193326Sed
2105193326Sed  case Decl::ObjCImplementation: {
2106193326Sed    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2107212904Sdim    if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2108212904Sdim      Context.ResetObjCLayout(OMD->getClassInterface());
2109193326Sed    EmitObjCPropertyImplementations(OMD);
2110207619Srdivacky    EmitObjCIvarInitializations(OMD);
2111193326Sed    Runtime->GenerateClass(OMD);
2112193326Sed    break;
2113198092Srdivacky  }
2114193326Sed  case Decl::ObjCMethod: {
2115193326Sed    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2116193326Sed    // If this is not a prototype, emit the body.
2117195341Sed    if (OMD->getBody())
2118193326Sed      CodeGenFunction(*this).GenerateObjCMethod(OMD);
2119193326Sed    break;
2120193326Sed  }
2121198092Srdivacky  case Decl::ObjCCompatibleAlias:
2122193326Sed    // compatibility-alias is a directive and has no code gen.
2123193326Sed    break;
2124193326Sed
2125193326Sed  case Decl::LinkageSpec:
2126193326Sed    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2127193326Sed    break;
2128193326Sed
2129193326Sed  case Decl::FileScopeAsm: {
2130193326Sed    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2131200583Srdivacky    llvm::StringRef AsmString = AD->getAsmString()->getString();
2132198092Srdivacky
2133193326Sed    const std::string &S = getModule().getModuleInlineAsm();
2134193326Sed    if (S.empty())
2135193326Sed      getModule().setModuleInlineAsm(AsmString);
2136193326Sed    else
2137200583Srdivacky      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2138193326Sed    break;
2139193326Sed  }
2140198092Srdivacky
2141198092Srdivacky  default:
2142193326Sed    // Make sure we handled everything we should, every other kind is a
2143193326Sed    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2144193326Sed    // function. Need to recode Decl::Kind to do that easily.
2145193326Sed    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2146193326Sed  }
2147193326Sed}
2148210299Sed
2149210299Sed/// Turns the given pointer into a constant.
2150210299Sedstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2151210299Sed                                          const void *Ptr) {
2152210299Sed  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2153210299Sed  const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2154210299Sed  return llvm::ConstantInt::get(i64, PtrInt);
2155210299Sed}
2156210299Sed
2157210299Sedstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2158210299Sed                                   llvm::NamedMDNode *&GlobalMetadata,
2159210299Sed                                   GlobalDecl D,
2160210299Sed                                   llvm::GlobalValue *Addr) {
2161210299Sed  if (!GlobalMetadata)
2162210299Sed    GlobalMetadata =
2163210299Sed      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2164210299Sed
2165210299Sed  // TODO: should we report variant information for ctors/dtors?
2166210299Sed  llvm::Value *Ops[] = {
2167210299Sed    Addr,
2168210299Sed    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2169210299Sed  };
2170221345Sdim  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2171210299Sed}
2172210299Sed
2173210299Sed/// Emits metadata nodes associating all the global values in the
2174210299Sed/// current module with the Decls they came from.  This is useful for
2175210299Sed/// projects using IR gen as a subroutine.
2176210299Sed///
2177210299Sed/// Since there's currently no way to associate an MDNode directly
2178210299Sed/// with an llvm::GlobalValue, we create a global named metadata
2179210299Sed/// with the name 'clang.global.decl.ptrs'.
2180210299Sedvoid CodeGenModule::EmitDeclMetadata() {
2181210299Sed  llvm::NamedMDNode *GlobalMetadata = 0;
2182210299Sed
2183210299Sed  // StaticLocalDeclMap
2184210299Sed  for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2185210299Sed         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2186210299Sed       I != E; ++I) {
2187210299Sed    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2188210299Sed    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2189210299Sed  }
2190210299Sed}
2191210299Sed
2192210299Sed/// Emits metadata nodes for all the local variables in the current
2193210299Sed/// function.
2194210299Sedvoid CodeGenFunction::EmitDeclMetadata() {
2195210299Sed  if (LocalDeclMap.empty()) return;
2196210299Sed
2197210299Sed  llvm::LLVMContext &Context = getLLVMContext();
2198210299Sed
2199210299Sed  // Find the unique metadata ID for this name.
2200210299Sed  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2201210299Sed
2202210299Sed  llvm::NamedMDNode *GlobalMetadata = 0;
2203210299Sed
2204210299Sed  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2205210299Sed         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2206210299Sed    const Decl *D = I->first;
2207210299Sed    llvm::Value *Addr = I->second;
2208210299Sed
2209210299Sed    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2210210299Sed      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2211221345Sdim      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2212210299Sed    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2213210299Sed      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2214210299Sed      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2215210299Sed    }
2216210299Sed  }
2217210299Sed}
2218212904Sdim
2219212904Sdim///@name Custom Runtime Function Interfaces
2220212904Sdim///@{
2221212904Sdim//
2222212904Sdim// FIXME: These can be eliminated once we can have clients just get the required
2223212904Sdim// AST nodes from the builtin tables.
2224212904Sdim
2225212904Sdimllvm::Constant *CodeGenModule::getBlockObjectDispose() {
2226212904Sdim  if (BlockObjectDispose)
2227212904Sdim    return BlockObjectDispose;
2228212904Sdim
2229212904Sdim  // If we saw an explicit decl, use that.
2230212904Sdim  if (BlockObjectDisposeDecl) {
2231212904Sdim    return BlockObjectDispose = GetAddrOfFunction(
2232212904Sdim      BlockObjectDisposeDecl,
2233212904Sdim      getTypes().GetFunctionType(BlockObjectDisposeDecl));
2234212904Sdim  }
2235212904Sdim
2236212904Sdim  // Otherwise construct the function by hand.
2237212904Sdim  const llvm::FunctionType *FTy;
2238212904Sdim  std::vector<const llvm::Type*> ArgTys;
2239212904Sdim  const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2240218893Sdim  ArgTys.push_back(Int8PtrTy);
2241212904Sdim  ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2242212904Sdim  FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2243212904Sdim  return BlockObjectDispose =
2244212904Sdim    CreateRuntimeFunction(FTy, "_Block_object_dispose");
2245212904Sdim}
2246212904Sdim
2247212904Sdimllvm::Constant *CodeGenModule::getBlockObjectAssign() {
2248212904Sdim  if (BlockObjectAssign)
2249212904Sdim    return BlockObjectAssign;
2250212904Sdim
2251212904Sdim  // If we saw an explicit decl, use that.
2252212904Sdim  if (BlockObjectAssignDecl) {
2253212904Sdim    return BlockObjectAssign = GetAddrOfFunction(
2254212904Sdim      BlockObjectAssignDecl,
2255212904Sdim      getTypes().GetFunctionType(BlockObjectAssignDecl));
2256212904Sdim  }
2257212904Sdim
2258212904Sdim  // Otherwise construct the function by hand.
2259212904Sdim  const llvm::FunctionType *FTy;
2260212904Sdim  std::vector<const llvm::Type*> ArgTys;
2261212904Sdim  const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2262218893Sdim  ArgTys.push_back(Int8PtrTy);
2263218893Sdim  ArgTys.push_back(Int8PtrTy);
2264212904Sdim  ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2265212904Sdim  FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2266212904Sdim  return BlockObjectAssign =
2267212904Sdim    CreateRuntimeFunction(FTy, "_Block_object_assign");
2268212904Sdim}
2269212904Sdim
2270212904Sdimllvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2271212904Sdim  if (NSConcreteGlobalBlock)
2272212904Sdim    return NSConcreteGlobalBlock;
2273212904Sdim
2274212904Sdim  // If we saw an explicit decl, use that.
2275212904Sdim  if (NSConcreteGlobalBlockDecl) {
2276212904Sdim    return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2277212904Sdim      NSConcreteGlobalBlockDecl,
2278212904Sdim      getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2279212904Sdim  }
2280212904Sdim
2281212904Sdim  // Otherwise construct the variable by hand.
2282218893Sdim  return NSConcreteGlobalBlock =
2283218893Sdim    CreateRuntimeVariable(Int8PtrTy, "_NSConcreteGlobalBlock");
2284212904Sdim}
2285212904Sdim
2286212904Sdimllvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2287212904Sdim  if (NSConcreteStackBlock)
2288212904Sdim    return NSConcreteStackBlock;
2289212904Sdim
2290212904Sdim  // If we saw an explicit decl, use that.
2291212904Sdim  if (NSConcreteStackBlockDecl) {
2292212904Sdim    return NSConcreteStackBlock = GetAddrOfGlobalVar(
2293212904Sdim      NSConcreteStackBlockDecl,
2294212904Sdim      getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2295212904Sdim  }
2296212904Sdim
2297212904Sdim  // Otherwise construct the variable by hand.
2298218893Sdim  return NSConcreteStackBlock =
2299218893Sdim    CreateRuntimeVariable(Int8PtrTy, "_NSConcreteStackBlock");
2300212904Sdim}
2301212904Sdim
2302212904Sdim///@}
2303