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"
15226890Sdim#include "CGCUDARuntime.h"
16212904Sdim#include "CGCXXABI.h"
17252723Sdim#include "CGCall.h"
18252723Sdim#include "CGDebugInfo.h"
19193326Sed#include "CGObjCRuntime.h"
20226890Sdim#include "CGOpenCLRuntime.h"
21252723Sdim#include "CodeGenFunction.h"
22252723Sdim#include "CodeGenTBAA.h"
23202379Srdivacky#include "TargetInfo.h"
24193326Sed#include "clang/AST/ASTContext.h"
25203955Srdivacky#include "clang/AST/CharUnits.h"
26252723Sdim#include "clang/AST/DeclCXX.h"
27193326Sed#include "clang/AST/DeclObjC.h"
28210299Sed#include "clang/AST/DeclTemplate.h"
29218893Sdim#include "clang/AST/Mangle.h"
30199990Srdivacky#include "clang/AST/RecordLayout.h"
31229042Sdim#include "clang/AST/RecursiveASTVisitor.h"
32235633Sdim#include "clang/Basic/Builtins.h"
33252723Sdim#include "clang/Basic/CharInfo.h"
34193326Sed#include "clang/Basic/Diagnostic.h"
35252723Sdim#include "clang/Basic/Module.h"
36193326Sed#include "clang/Basic/SourceManager.h"
37193326Sed#include "clang/Basic/TargetInfo.h"
38263509Sdim#include "clang/Basic/Version.h"
39252723Sdim#include "clang/Frontend/CodeGenOptions.h"
40263509Sdim#include "clang/Sema/SemaDiagnostic.h"
41235633Sdim#include "llvm/ADT/APSInt.h"
42204793Srdivacky#include "llvm/ADT/Triple.h"
43252723Sdim#include "llvm/IR/CallingConv.h"
44252723Sdim#include "llvm/IR/DataLayout.h"
45252723Sdim#include "llvm/IR/Intrinsics.h"
46252723Sdim#include "llvm/IR/LLVMContext.h"
47252723Sdim#include "llvm/IR/Module.h"
48207619Srdivacky#include "llvm/Support/CallSite.h"
49252723Sdim#include "llvm/Support/ConvertUTF.h"
50199482Srdivacky#include "llvm/Support/ErrorHandling.h"
51252723Sdim#include "llvm/Target/Mangler.h"
52252723Sdim
53193326Sedusing namespace clang;
54193326Sedusing namespace CodeGen;
55193326Sed
56226890Sdimstatic const char AnnotationSection[] = "llvm.metadata";
57226890Sdim
58212904Sdimstatic CGCXXABI &createCXXABI(CodeGenModule &CGM) {
59252723Sdim  switch (CGM.getTarget().getCXXABI().getKind()) {
60252723Sdim  case TargetCXXABI::GenericAArch64:
61252723Sdim  case TargetCXXABI::GenericARM:
62252723Sdim  case TargetCXXABI::iOS:
63252723Sdim  case TargetCXXABI::GenericItanium:
64252723Sdim    return *CreateItaniumCXXABI(CGM);
65252723Sdim  case TargetCXXABI::Microsoft:
66252723Sdim    return *CreateMicrosoftCXXABI(CGM);
67212904Sdim  }
68193326Sed
69212904Sdim  llvm_unreachable("invalid C++ ABI kind");
70212904Sdim}
71212904Sdim
72199482SrdivackyCodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
73245431Sdim                             llvm::Module &M, const llvm::DataLayout &TD,
74226890Sdim                             DiagnosticsEngine &diags)
75263509Sdim    : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
76263509Sdim      Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
77263509Sdim      ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
78263509Sdim      TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
79263509Sdim      OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
80263509Sdim      NoObjCARCExceptionsMetadata(0), RRData(0), CFConstantStringClassRef(0),
81263509Sdim      ConstantStringClassRef(0), NSConstantStringType(0),
82263509Sdim      NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
83263509Sdim      BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
84263509Sdim      LifetimeStartFn(0), LifetimeEndFn(0),
85263509Sdim      SanitizerBlacklist(
86263509Sdim          llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
87263509Sdim      SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
88263509Sdim                                          : LangOpts.Sanitize) {
89252723Sdim
90235633Sdim  // Initialize the type cache.
91235633Sdim  llvm::LLVMContext &LLVMContext = M.getContext();
92235633Sdim  VoidTy = llvm::Type::getVoidTy(LLVMContext);
93235633Sdim  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
94235633Sdim  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
95235633Sdim  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
96235633Sdim  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
97235633Sdim  FloatTy = llvm::Type::getFloatTy(LLVMContext);
98235633Sdim  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
99235633Sdim  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
100235633Sdim  PointerAlignInBytes =
101235633Sdim  C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
102235633Sdim  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
103235633Sdim  IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
104235633Sdim  Int8PtrTy = Int8Ty->getPointerTo(0);
105235633Sdim  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
106235633Sdim
107252723Sdim  RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
108252723Sdim
109235633Sdim  if (LangOpts.ObjC1)
110226890Sdim    createObjCRuntime();
111235633Sdim  if (LangOpts.OpenCL)
112226890Sdim    createOpenCLRuntime();
113235633Sdim  if (LangOpts.CUDA)
114226890Sdim    createCUDARuntime();
115193326Sed
116245431Sdim  // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
117252723Sdim  if (SanOpts.Thread ||
118245431Sdim      (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
119245431Sdim    TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
120218893Sdim                           ABI.getMangleContext());
121218893Sdim
122221345Sdim  // If debug info or coverage generation is enabled, create the CGDebugInfo
123221345Sdim  // object.
124245431Sdim  if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
125245431Sdim      CodeGenOpts.EmitGcovArcs ||
126221345Sdim      CodeGenOpts.EmitGcovNotes)
127221345Sdim    DebugInfo = new CGDebugInfo(*this);
128218893Sdim
129218893Sdim  Block.GlobalUniqueCount = 0;
130218893Sdim
131235633Sdim  if (C.getLangOpts().ObjCAutoRefCount)
132224145Sdim    ARCData = new ARCEntrypoints();
133224145Sdim  RRData = new RREntrypoints();
134193326Sed}
135193326Sed
136193326SedCodeGenModule::~CodeGenModule() {
137226890Sdim  delete ObjCRuntime;
138226890Sdim  delete OpenCLRuntime;
139226890Sdim  delete CUDARuntime;
140226890Sdim  delete TheTargetCodeGenInfo;
141212904Sdim  delete &ABI;
142218893Sdim  delete TBAA;
143193326Sed  delete DebugInfo;
144224145Sdim  delete ARCData;
145224145Sdim  delete RRData;
146193326Sed}
147193326Sed
148202879Srdivackyvoid CodeGenModule::createObjCRuntime() {
149245431Sdim  // This is just isGNUFamily(), but we want to force implementors of
150245431Sdim  // new ABIs to decide how best to do this.
151245431Sdim  switch (LangOpts.ObjCRuntime.getKind()) {
152245431Sdim  case ObjCRuntime::GNUstep:
153245431Sdim  case ObjCRuntime::GCC:
154245431Sdim  case ObjCRuntime::ObjFW:
155226890Sdim    ObjCRuntime = CreateGNUObjCRuntime(*this);
156245431Sdim    return;
157245431Sdim
158245431Sdim  case ObjCRuntime::FragileMacOSX:
159245431Sdim  case ObjCRuntime::MacOSX:
160245431Sdim  case ObjCRuntime::iOS:
161226890Sdim    ObjCRuntime = CreateMacObjCRuntime(*this);
162245431Sdim    return;
163245431Sdim  }
164245431Sdim  llvm_unreachable("bad runtime kind");
165202879Srdivacky}
166202879Srdivacky
167226890Sdimvoid CodeGenModule::createOpenCLRuntime() {
168226890Sdim  OpenCLRuntime = new CGOpenCLRuntime(*this);
169226890Sdim}
170226890Sdim
171226890Sdimvoid CodeGenModule::createCUDARuntime() {
172226890Sdim  CUDARuntime = CreateNVCUDARuntime(*this);
173226890Sdim}
174226890Sdim
175263509Sdimvoid CodeGenModule::applyReplacements() {
176263509Sdim  for (ReplacementsTy::iterator I = Replacements.begin(),
177263509Sdim                                E = Replacements.end();
178263509Sdim       I != E; ++I) {
179263509Sdim    StringRef MangledName = I->first();
180263509Sdim    llvm::Constant *Replacement = I->second;
181263509Sdim    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
182263509Sdim    if (!Entry)
183263509Sdim      continue;
184263509Sdim    llvm::Function *OldF = cast<llvm::Function>(Entry);
185263509Sdim    llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
186263509Sdim    if (!NewF) {
187263509Sdim      llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
188263509Sdim      assert(CE->getOpcode() == llvm::Instruction::BitCast ||
189263509Sdim             CE->getOpcode() == llvm::Instruction::GetElementPtr);
190263509Sdim      NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
191263509Sdim    }
192263509Sdim
193263509Sdim    // Replace old with new, but keep the old order.
194263509Sdim    OldF->replaceAllUsesWith(Replacement);
195263509Sdim    if (NewF) {
196263509Sdim      NewF->removeFromParent();
197263509Sdim      OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
198263509Sdim    }
199263509Sdim    OldF->eraseFromParent();
200263509Sdim  }
201263509Sdim}
202263509Sdim
203263509Sdimvoid CodeGenModule::checkAliases() {
204263509Sdim  bool Error = false;
205263509Sdim  for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
206263509Sdim         E = Aliases.end(); I != E; ++I) {
207263509Sdim    const GlobalDecl &GD = *I;
208263509Sdim    const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
209263509Sdim    const AliasAttr *AA = D->getAttr<AliasAttr>();
210263509Sdim    StringRef MangledName = getMangledName(GD);
211263509Sdim    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
212263509Sdim    llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
213263509Sdim    llvm::GlobalValue *GV = Alias->getAliasedGlobal();
214263509Sdim    if (GV->isDeclaration()) {
215263509Sdim      Error = true;
216263509Sdim      getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
217263509Sdim    } else if (!Alias->resolveAliasedGlobal(/*stopOnWeak*/ false)) {
218263509Sdim      Error = true;
219263509Sdim      getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
220263509Sdim    }
221263509Sdim  }
222263509Sdim  if (!Error)
223263509Sdim    return;
224263509Sdim
225263509Sdim  for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
226263509Sdim         E = Aliases.end(); I != E; ++I) {
227263509Sdim    const GlobalDecl &GD = *I;
228263509Sdim    StringRef MangledName = getMangledName(GD);
229263509Sdim    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
230263509Sdim    llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
231263509Sdim    Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
232263509Sdim    Alias->eraseFromParent();
233263509Sdim  }
234263509Sdim}
235263509Sdim
236193326Sedvoid CodeGenModule::Release() {
237202379Srdivacky  EmitDeferred();
238263509Sdim  applyReplacements();
239263509Sdim  checkAliases();
240198092Srdivacky  EmitCXXGlobalInitFunc();
241205408Srdivacky  EmitCXXGlobalDtorFunc();
242252723Sdim  EmitCXXThreadLocalInitFunc();
243226890Sdim  if (ObjCRuntime)
244226890Sdim    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
245193326Sed      AddGlobalCtor(ObjCInitFunction);
246193326Sed  EmitCtorList(GlobalCtors, "llvm.global_ctors");
247193326Sed  EmitCtorList(GlobalDtors, "llvm.global_dtors");
248226890Sdim  EmitGlobalAnnotations();
249252723Sdim  EmitStaticExternCAliases();
250193326Sed  EmitLLVMUsed();
251210299Sed
252263509Sdim  if (CodeGenOpts.Autolink &&
253263509Sdim      (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
254252723Sdim    EmitModuleLinkOptions();
255252723Sdim  }
256263509Sdim  if (CodeGenOpts.DwarfVersion)
257263509Sdim    // We actually want the latest version when there are conflicts.
258263509Sdim    // We can change from Warning to Latest if such mode is supported.
259263509Sdim    getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
260263509Sdim                              CodeGenOpts.DwarfVersion);
261263509Sdim  if (DebugInfo)
262263509Sdim    // We support a single version in the linked module: error out when
263263509Sdim    // modules do not have the same version. We are going to implement dropping
264263509Sdim    // debug info when the version number is not up-to-date. Once that is
265263509Sdim    // done, the bitcode linker is not going to see modules with different
266263509Sdim    // version numbers.
267263509Sdim    getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
268263509Sdim                              llvm::DEBUG_METADATA_VERSION);
269252723Sdim
270218893Sdim  SimplifyPersonality();
271218893Sdim
272210299Sed  if (getCodeGenOpts().EmitDeclMetadata)
273210299Sed    EmitDeclMetadata();
274223017Sdim
275223017Sdim  if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
276223017Sdim    EmitCoverageFile();
277226890Sdim
278226890Sdim  if (DebugInfo)
279226890Sdim    DebugInfo->finalize();
280263509Sdim
281263509Sdim  EmitVersionIdentMetadata();
282193326Sed}
283193326Sed
284221345Sdimvoid CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
285221345Sdim  // Make sure that this type is translated.
286221345Sdim  Types.UpdateCompletedType(TD);
287221345Sdim}
288221345Sdim
289218893Sdimllvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
290218893Sdim  if (!TBAA)
291218893Sdim    return 0;
292218893Sdim  return TBAA->getTBAAInfo(QTy);
293218893Sdim}
294218893Sdim
295235633Sdimllvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
296235633Sdim  if (!TBAA)
297235633Sdim    return 0;
298235633Sdim  return TBAA->getTBAAInfoForVTablePtr();
299235633Sdim}
300235633Sdim
301245431Sdimllvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
302245431Sdim  if (!TBAA)
303245431Sdim    return 0;
304245431Sdim  return TBAA->getTBAAStructInfo(QTy);
305245431Sdim}
306245431Sdim
307252723Sdimllvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
308252723Sdim  if (!TBAA)
309252723Sdim    return 0;
310252723Sdim  return TBAA->getTBAAStructTypeInfo(QTy);
311218893Sdim}
312218893Sdim
313252723Sdimllvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
314252723Sdim                                                  llvm::MDNode *AccessN,
315252723Sdim                                                  uint64_t O) {
316252723Sdim  if (!TBAA)
317252723Sdim    return 0;
318252723Sdim  return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
319204793Srdivacky}
320204793Srdivacky
321263509Sdim/// Decorate the instruction with a TBAA tag. For both scalar TBAA
322263509Sdim/// and struct-path aware TBAA, the tag has the same format:
323263509Sdim/// base type, access type and offset.
324252723Sdim/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
325252723Sdimvoid CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
326252723Sdim                                        llvm::MDNode *TBAAInfo,
327252723Sdim                                        bool ConvertTypeToTag) {
328263509Sdim  if (ConvertTypeToTag && TBAA)
329252723Sdim    Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
330252723Sdim                      TBAA->getTBAAScalarTagInfo(TBAAInfo));
331252723Sdim  else
332252723Sdim    Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
333252723Sdim}
334252723Sdim
335226890Sdimvoid CodeGenModule::Error(SourceLocation loc, StringRef error) {
336226890Sdim  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
337221345Sdim  getDiags().Report(Context.getFullLoc(loc), diagID);
338221345Sdim}
339221345Sdim
340193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the
341193326Sed/// specified stmt yet.
342263509Sdimvoid CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
343226890Sdim  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
344193326Sed                                               "cannot compile this %0 yet");
345193326Sed  std::string Msg = Type;
346193326Sed  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
347193326Sed    << Msg << S->getSourceRange();
348193326Sed}
349193326Sed
350193326Sed/// ErrorUnsupported - Print out an error that codegen doesn't support the
351193326Sed/// specified decl yet.
352263509Sdimvoid CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
353226890Sdim  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
354193326Sed                                               "cannot compile this %0 yet");
355193326Sed  std::string Msg = Type;
356193326Sed  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
357193326Sed}
358193326Sed
359224145Sdimllvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
360224145Sdim  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
361224145Sdim}
362224145Sdim
363198092Srdivackyvoid CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
364218893Sdim                                        const NamedDecl *D) const {
365193326Sed  // Internal definitions always have default visibility.
366193326Sed  if (GV->hasLocalLinkage()) {
367193326Sed    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
368193326Sed    return;
369193326Sed  }
370193326Sed
371218893Sdim  // Set visibility for definitions.
372252723Sdim  LinkageInfo LV = D->getLinkageAndVisibility();
373252723Sdim  if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
374252723Sdim    GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
375193326Sed}
376193326Sed
377245431Sdimstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
378245431Sdim  return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
379245431Sdim      .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
380245431Sdim      .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
381245431Sdim      .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
382245431Sdim      .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
383245431Sdim}
384245431Sdim
385245431Sdimstatic llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
386245431Sdim    CodeGenOptions::TLSModel M) {
387245431Sdim  switch (M) {
388245431Sdim  case CodeGenOptions::GeneralDynamicTLSModel:
389245431Sdim    return llvm::GlobalVariable::GeneralDynamicTLSModel;
390245431Sdim  case CodeGenOptions::LocalDynamicTLSModel:
391245431Sdim    return llvm::GlobalVariable::LocalDynamicTLSModel;
392245431Sdim  case CodeGenOptions::InitialExecTLSModel:
393245431Sdim    return llvm::GlobalVariable::InitialExecTLSModel;
394245431Sdim  case CodeGenOptions::LocalExecTLSModel:
395245431Sdim    return llvm::GlobalVariable::LocalExecTLSModel;
396245431Sdim  }
397245431Sdim  llvm_unreachable("Invalid TLS model!");
398245431Sdim}
399245431Sdim
400245431Sdimvoid CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
401245431Sdim                               const VarDecl &D) const {
402252723Sdim  assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
403245431Sdim
404245431Sdim  llvm::GlobalVariable::ThreadLocalMode TLM;
405245431Sdim  TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
406245431Sdim
407245431Sdim  // Override the TLS model if it is explicitly specified.
408245431Sdim  if (D.hasAttr<TLSModelAttr>()) {
409245431Sdim    const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
410245431Sdim    TLM = GetLLVMTLSModel(Attr->getModel());
411245431Sdim  }
412245431Sdim
413245431Sdim  GV->setThreadLocalMode(TLM);
414245431Sdim}
415245431Sdim
416212904Sdim/// Set the symbol visibility of type information (vtable and RTTI)
417212904Sdim/// associated with the given type.
418212904Sdimvoid CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
419212904Sdim                                      const CXXRecordDecl *RD,
420218893Sdim                                      TypeVisibilityKind TVK) const {
421212904Sdim  setGlobalVisibility(GV, RD);
422212904Sdim
423212904Sdim  if (!CodeGenOpts.HiddenWeakVTables)
424212904Sdim    return;
425212904Sdim
426218893Sdim  // We never want to drop the visibility for RTTI names.
427218893Sdim  if (TVK == TVK_ForRTTIName)
428218893Sdim    return;
429218893Sdim
430212904Sdim  // We want to drop the visibility to hidden for weak type symbols.
431212904Sdim  // This isn't possible if there might be unresolved references
432212904Sdim  // elsewhere that rely on this symbol being visible.
433212904Sdim
434212904Sdim  // This should be kept roughly in sync with setThunkVisibility
435212904Sdim  // in CGVTables.cpp.
436212904Sdim
437212904Sdim  // Preconditions.
438218893Sdim  if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
439212904Sdim      GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
440212904Sdim    return;
441212904Sdim
442212904Sdim  // Don't override an explicit visibility attribute.
443252723Sdim  if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
444212904Sdim    return;
445212904Sdim
446212904Sdim  switch (RD->getTemplateSpecializationKind()) {
447212904Sdim  // We have to disable the optimization if this is an EI definition
448212904Sdim  // because there might be EI declarations in other shared objects.
449212904Sdim  case TSK_ExplicitInstantiationDefinition:
450212904Sdim  case TSK_ExplicitInstantiationDeclaration:
451212904Sdim    return;
452212904Sdim
453212904Sdim  // Every use of a non-template class's type information has to emit it.
454212904Sdim  case TSK_Undeclared:
455212904Sdim    break;
456212904Sdim
457212904Sdim  // In theory, implicit instantiations can ignore the possibility of
458212904Sdim  // an explicit instantiation declaration because there necessarily
459212904Sdim  // must be an EI definition somewhere with default visibility.  In
460212904Sdim  // practice, it's possible to have an explicit instantiation for
461212904Sdim  // an arbitrary template class, and linkers aren't necessarily able
462212904Sdim  // to deal with mixed-visibility symbols.
463212904Sdim  case TSK_ExplicitSpecialization:
464212904Sdim  case TSK_ImplicitInstantiation:
465245431Sdim    return;
466212904Sdim  }
467212904Sdim
468212904Sdim  // If there's a key function, there may be translation units
469212904Sdim  // that don't have the key function's definition.  But ignore
470212904Sdim  // this if we're emitting RTTI under -fno-rtti.
471235633Sdim  if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
472252723Sdim    // FIXME: what should we do if we "lose" the key function during
473252723Sdim    // the emission of the file?
474252723Sdim    if (Context.getCurrentKeyFunction(RD))
475212904Sdim      return;
476218893Sdim  }
477212904Sdim
478212904Sdim  // Otherwise, drop the visibility to hidden.
479212904Sdim  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
480218893Sdim  GV->setUnnamedAddr(true);
481212904Sdim}
482212904Sdim
483226890SdimStringRef CodeGenModule::getMangledName(GlobalDecl GD) {
484198092Srdivacky  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
485198092Srdivacky
486226890Sdim  StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
487210299Sed  if (!Str.empty())
488210299Sed    return Str;
489198092Srdivacky
490212904Sdim  if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
491210299Sed    IdentifierInfo *II = ND->getIdentifier();
492210299Sed    assert(II && "Attempt to mangle unnamed decl.");
493193326Sed
494210299Sed    Str = II->getName();
495210299Sed    return Str;
496193326Sed  }
497210299Sed
498235633Sdim  SmallString<256> Buffer;
499218893Sdim  llvm::raw_svector_ostream Out(Buffer);
500210299Sed  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
501218893Sdim    getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
502210299Sed  else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
503218893Sdim    getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
504210299Sed  else
505218893Sdim    getCXXABI().getMangleContext().mangleName(ND, Out);
506198092Srdivacky
507210299Sed  // Allocate space for the mangled name.
508218893Sdim  Out.flush();
509210299Sed  size_t Length = Buffer.size();
510210299Sed  char *Name = MangledNamesAllocator.Allocate<char>(Length);
511210299Sed  std::copy(Buffer.begin(), Buffer.end(), Name);
512210299Sed
513226890Sdim  Str = StringRef(Name, Length);
514210299Sed
515210299Sed  return Str;
516193326Sed}
517193326Sed
518218893Sdimvoid CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
519218893Sdim                                        const BlockDecl *BD) {
520218893Sdim  MangleContext &MangleCtx = getCXXABI().getMangleContext();
521218893Sdim  const Decl *D = GD.getDecl();
522218893Sdim  llvm::raw_svector_ostream Out(Buffer.getBuffer());
523218893Sdim  if (D == 0)
524245431Sdim    MangleCtx.mangleGlobalBlock(BD,
525245431Sdim      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
526218893Sdim  else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
527218893Sdim    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
528218893Sdim  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
529218893Sdim    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
530218893Sdim  else
531218893Sdim    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
532210299Sed}
533210299Sed
534226890Sdimllvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
535205408Srdivacky  return getModule().getNamedValue(Name);
536193326Sed}
537193326Sed
538193326Sed/// AddGlobalCtor - Add a function to the list that will be called before
539193326Sed/// main() runs.
540193326Sedvoid CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
541193326Sed  // FIXME: Type coercion of void()* types.
542193326Sed  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
543193326Sed}
544193326Sed
545193326Sed/// AddGlobalDtor - Add a function to the list that will be called
546193326Sed/// when the module is unloaded.
547193326Sedvoid CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
548193326Sed  // FIXME: Type coercion of void()* types.
549193326Sed  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
550193326Sed}
551193326Sed
552193326Sedvoid CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
553193326Sed  // Ctor function type is void()*.
554223017Sdim  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
555193326Sed  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
556193326Sed
557193326Sed  // Get the type of a ctor entry, { i32, void ()* }.
558224145Sdim  llvm::StructType *CtorStructTy =
559235633Sdim    llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
560193326Sed
561193326Sed  // Construct the constructor and destructor arrays.
562235633Sdim  SmallVector<llvm::Constant*, 8> Ctors;
563193326Sed  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
564235633Sdim    llvm::Constant *S[] = {
565235633Sdim      llvm::ConstantInt::get(Int32Ty, I->second, false),
566235633Sdim      llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
567235633Sdim    };
568193326Sed    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
569193326Sed  }
570193326Sed
571193326Sed  if (!Ctors.empty()) {
572193326Sed    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
573198092Srdivacky    new llvm::GlobalVariable(TheModule, AT, false,
574193326Sed                             llvm::GlobalValue::AppendingLinkage,
575193326Sed                             llvm::ConstantArray::get(AT, Ctors),
576198092Srdivacky                             GlobalName);
577193326Sed  }
578193326Sed}
579193326Sed
580204643Srdivackyllvm::GlobalValue::LinkageTypes
581263509SdimCodeGenModule::getFunctionLinkage(GlobalDecl GD) {
582263509Sdim  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
583263509Sdim
584263509Sdim  if (isa<CXXDestructorDecl>(D) &&
585263509Sdim      getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
586263509Sdim                                         GD.getDtorType()))
587263509Sdim    return llvm::Function::LinkOnceODRLinkage;
588263509Sdim
589212904Sdim  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
590193326Sed
591210299Sed  if (Linkage == GVA_Internal)
592204643Srdivacky    return llvm::Function::InternalLinkage;
593210299Sed
594210299Sed  if (D->hasAttr<DLLExportAttr>())
595204643Srdivacky    return llvm::Function::DLLExportLinkage;
596210299Sed
597210299Sed  if (D->hasAttr<WeakAttr>())
598204643Srdivacky    return llvm::Function::WeakAnyLinkage;
599210299Sed
600210299Sed  // In C99 mode, 'inline' functions are guaranteed to have a strong
601210299Sed  // definition somewhere else, so we can use available_externally linkage.
602210299Sed  if (Linkage == GVA_C99Inline)
603204643Srdivacky    return llvm::Function::AvailableExternallyLinkage;
604226890Sdim
605226890Sdim  // Note that Apple's kernel linker doesn't support symbol
606226890Sdim  // coalescing, so we need to avoid linkonce and weak linkages there.
607226890Sdim  // Normally, this means we just map to internal, but for explicit
608226890Sdim  // instantiations we'll map to external.
609226890Sdim
610210299Sed  // In C++, the compiler has to emit a definition in every translation unit
611210299Sed  // that references the function.  We should use linkonce_odr because
612210299Sed  // a) if all references in this translation unit are optimized away, we
613210299Sed  // don't need to codegen it.  b) if the function persists, it needs to be
614210299Sed  // merged with other definitions. c) C++ has the ODR, so we know the
615210299Sed  // definition is dependable.
616210299Sed  if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
617235633Sdim    return !Context.getLangOpts().AppleKext
618218893Sdim             ? llvm::Function::LinkOnceODRLinkage
619218893Sdim             : llvm::Function::InternalLinkage;
620210299Sed
621210299Sed  // An explicit instantiation of a template has weak linkage, since
622210299Sed  // explicit instantiations can occur in multiple translation units
623210299Sed  // and must all be equivalent. However, we are not allowed to
624210299Sed  // throw away these explicit instantiations.
625210299Sed  if (Linkage == GVA_ExplicitTemplateInstantiation)
626235633Sdim    return !Context.getLangOpts().AppleKext
627218893Sdim             ? llvm::Function::WeakODRLinkage
628226890Sdim             : llvm::Function::ExternalLinkage;
629210299Sed
630210299Sed  // Otherwise, we have strong external linkage.
631210299Sed  assert(Linkage == GVA_StrongExternal);
632210299Sed  return llvm::Function::ExternalLinkage;
633204643Srdivacky}
634193326Sed
635204643Srdivacky
636204643Srdivacky/// SetFunctionDefinitionAttributes - Set attributes for a global.
637204643Srdivacky///
638204643Srdivacky/// FIXME: This is currently only done for aliases and functions, but not for
639204643Srdivacky/// variables (these details are set in EmitGlobalVarDefinition for variables).
640204643Srdivackyvoid CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
641204643Srdivacky                                                    llvm::GlobalValue *GV) {
642193326Sed  SetCommonAttributes(D, GV);
643193326Sed}
644193326Sed
645193326Sedvoid CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
646198092Srdivacky                                              const CGFunctionInfo &Info,
647193326Sed                                              llvm::Function *F) {
648198092Srdivacky  unsigned CallingConv;
649193326Sed  AttributeListType AttributeList;
650252723Sdim  ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
651252723Sdim  F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
652198092Srdivacky  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
653193326Sed}
654193326Sed
655226890Sdim/// Determines whether the language options require us to model
656226890Sdim/// unwind exceptions.  We treat -fexceptions as mandating this
657226890Sdim/// except under the fragile ObjC ABI with only ObjC exceptions
658226890Sdim/// enabled.  This means, for example, that C with -fexceptions
659226890Sdim/// enables this.
660235633Sdimstatic bool hasUnwindExceptions(const LangOptions &LangOpts) {
661226890Sdim  // If exceptions are completely disabled, obviously this is false.
662235633Sdim  if (!LangOpts.Exceptions) return false;
663226890Sdim
664226890Sdim  // If C++ exceptions are enabled, this is true.
665235633Sdim  if (LangOpts.CXXExceptions) return true;
666226890Sdim
667226890Sdim  // If ObjC exceptions are enabled, this depends on the ABI.
668235633Sdim  if (LangOpts.ObjCExceptions) {
669245431Sdim    return LangOpts.ObjCRuntime.hasUnwindExceptions();
670226890Sdim  }
671226890Sdim
672226890Sdim  return true;
673226890Sdim}
674226890Sdim
675193326Sedvoid CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
676193326Sed                                                           llvm::Function *F) {
677263509Sdim  llvm::AttrBuilder B;
678263509Sdim
679223017Sdim  if (CodeGenOpts.UnwindTables)
680263509Sdim    B.addAttribute(llvm::Attribute::UWTable);
681223017Sdim
682235633Sdim  if (!hasUnwindExceptions(LangOpts))
683263509Sdim    B.addAttribute(llvm::Attribute::NoUnwind);
684193326Sed
685226890Sdim  if (D->hasAttr<NakedAttr>()) {
686226890Sdim    // Naked implies noinline: we should not be inlining such functions.
687263509Sdim    B.addAttribute(llvm::Attribute::Naked);
688263509Sdim    B.addAttribute(llvm::Attribute::NoInline);
689263509Sdim  } else if (D->hasAttr<NoInlineAttr>()) {
690263509Sdim    B.addAttribute(llvm::Attribute::NoInline);
691263509Sdim  } else if ((D->hasAttr<AlwaysInlineAttr>() ||
692263509Sdim              D->hasAttr<ForceInlineAttr>()) &&
693263509Sdim             !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
694263509Sdim                                              llvm::Attribute::NoInline)) {
695263509Sdim    // (noinline wins over always_inline, and we can't specify both in IR)
696263509Sdim    B.addAttribute(llvm::Attribute::AlwaysInline);
697226890Sdim  }
698218893Sdim
699263509Sdim  if (D->hasAttr<ColdAttr>()) {
700263509Sdim    B.addAttribute(llvm::Attribute::OptimizeForSize);
701263509Sdim    B.addAttribute(llvm::Attribute::Cold);
702263509Sdim  }
703198092Srdivacky
704245431Sdim  if (D->hasAttr<MinSizeAttr>())
705263509Sdim    B.addAttribute(llvm::Attribute::MinSize);
706245431Sdim
707235633Sdim  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
708263509Sdim    B.addAttribute(llvm::Attribute::StackProtect);
709235633Sdim  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
710263509Sdim    B.addAttribute(llvm::Attribute::StackProtectReq);
711252723Sdim
712252723Sdim  // Add sanitizer attributes if function is not blacklisted.
713263509Sdim  if (!SanitizerBlacklist->isIn(*F)) {
714252723Sdim    // When AddressSanitizer is enabled, set SanitizeAddress attribute
715252723Sdim    // unless __attribute__((no_sanitize_address)) is used.
716252723Sdim    if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
717263509Sdim      B.addAttribute(llvm::Attribute::SanitizeAddress);
718252723Sdim    // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
719252723Sdim    if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
720263509Sdim      B.addAttribute(llvm::Attribute::SanitizeThread);
721252723Sdim    }
722252723Sdim    // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
723252723Sdim    if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
724263509Sdim      B.addAttribute(llvm::Attribute::SanitizeMemory);
725235633Sdim  }
726235633Sdim
727263509Sdim  F->addAttributes(llvm::AttributeSet::FunctionIndex,
728263509Sdim                   llvm::AttributeSet::get(
729263509Sdim                       F->getContext(), llvm::AttributeSet::FunctionIndex, B));
730263509Sdim
731263509Sdim  if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
732263509Sdim    F->setUnnamedAddr(true);
733263509Sdim  else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
734263509Sdim    if (MD->isVirtual())
735263509Sdim      F->setUnnamedAddr(true);
736263509Sdim
737212904Sdim  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
738212904Sdim  if (alignment)
739212904Sdim    F->setAlignment(alignment);
740212904Sdim
741198092Srdivacky  // C++ ABI requires 2-byte alignment for member functions.
742198092Srdivacky  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
743198092Srdivacky    F->setAlignment(2);
744193326Sed}
745193326Sed
746198092Srdivackyvoid CodeGenModule::SetCommonAttributes(const Decl *D,
747193326Sed                                        llvm::GlobalValue *GV) {
748218893Sdim  if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
749218893Sdim    setGlobalVisibility(GV, ND);
750218893Sdim  else
751218893Sdim    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
752193326Sed
753195341Sed  if (D->hasAttr<UsedAttr>())
754193326Sed    AddUsedGlobal(GV);
755193326Sed
756195341Sed  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
757193326Sed    GV->setSection(SA->getName());
758202379Srdivacky
759252723Sdim  // Alias cannot have attributes. Filter them here.
760252723Sdim  if (!isa<llvm::GlobalAlias>(GV))
761252723Sdim    getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
762193326Sed}
763193326Sed
764193326Sedvoid CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
765193326Sed                                                  llvm::Function *F,
766193326Sed                                                  const CGFunctionInfo &FI) {
767193326Sed  SetLLVMFunctionAttributes(D, FI, F);
768193326Sed  SetLLVMFunctionAttributesForDefinition(D, F);
769193326Sed
770193326Sed  F->setLinkage(llvm::Function::InternalLinkage);
771193326Sed
772193326Sed  SetCommonAttributes(D, F);
773193326Sed}
774193326Sed
775203955Srdivackyvoid CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
776193326Sed                                          llvm::Function *F,
777193326Sed                                          bool IsIncompleteFunction) {
778221345Sdim  if (unsigned IID = F->getIntrinsicID()) {
779221345Sdim    // If this is an intrinsic function, set the function's attributes
780221345Sdim    // to the intrinsic's attributes.
781245431Sdim    F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
782245431Sdim                                                    (llvm::Intrinsic::ID)IID));
783221345Sdim    return;
784221345Sdim  }
785221345Sdim
786203955Srdivacky  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
787203955Srdivacky
788193326Sed  if (!IsIncompleteFunction)
789235633Sdim    SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
790198092Srdivacky
791263509Sdim  if (getCXXABI().HasThisReturn(GD)) {
792263509Sdim    assert(!F->arg_empty() &&
793263509Sdim           F->arg_begin()->getType()
794263509Sdim             ->canLosslesslyBitCastTo(F->getReturnType()) &&
795263509Sdim           "unexpected this return");
796263509Sdim    F->addAttribute(1, llvm::Attribute::Returned);
797263509Sdim  }
798263509Sdim
799193326Sed  // Only a few attributes are set on declarations; these may later be
800193326Sed  // overridden by a definition.
801198092Srdivacky
802195341Sed  if (FD->hasAttr<DLLImportAttr>()) {
803193326Sed    F->setLinkage(llvm::Function::DLLImportLinkage);
804198092Srdivacky  } else if (FD->hasAttr<WeakAttr>() ||
805221345Sdim             FD->isWeakImported()) {
806193326Sed    // "extern_weak" is overloaded in LLVM; we probably should have
807198092Srdivacky    // separate linkage types for this.
808193326Sed    F->setLinkage(llvm::Function::ExternalWeakLinkage);
809193326Sed  } else {
810198092Srdivacky    F->setLinkage(llvm::Function::ExternalLinkage);
811218893Sdim
812252723Sdim    LinkageInfo LV = FD->getLinkageAndVisibility();
813252723Sdim    if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
814252723Sdim      F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
815218893Sdim    }
816193326Sed  }
817193326Sed
818195341Sed  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
819193326Sed    F->setSection(SA->getName());
820263509Sdim
821263509Sdim  // A replaceable global allocation function does not act like a builtin by
822263509Sdim  // default, only if it is invoked by a new-expression or delete-expression.
823263509Sdim  if (FD->isReplaceableGlobalAllocationFunction())
824263509Sdim    F->addAttribute(llvm::AttributeSet::FunctionIndex,
825263509Sdim                    llvm::Attribute::NoBuiltin);
826193326Sed}
827193326Sed
828193326Sedvoid CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
829198092Srdivacky  assert(!GV->isDeclaration() &&
830193326Sed         "Only globals with definition can force usage.");
831193326Sed  LLVMUsed.push_back(GV);
832193326Sed}
833193326Sed
834193326Sedvoid CodeGenModule::EmitLLVMUsed() {
835193326Sed  // Don't create llvm.used if there is no need.
836198092Srdivacky  if (LLVMUsed.empty())
837193326Sed    return;
838193326Sed
839193326Sed  // Convert LLVMUsed to what ConstantArray needs.
840235633Sdim  SmallVector<llvm::Constant*, 8> UsedArray;
841193326Sed  UsedArray.resize(LLVMUsed.size());
842193326Sed  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
843198092Srdivacky    UsedArray[i] =
844198092Srdivacky     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
845235633Sdim                                    Int8PtrTy);
846193326Sed  }
847198092Srdivacky
848195099Sed  if (UsedArray.empty())
849195099Sed    return;
850235633Sdim  llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
851198092Srdivacky
852198092Srdivacky  llvm::GlobalVariable *GV =
853198092Srdivacky    new llvm::GlobalVariable(getModule(), ATy, false,
854193326Sed                             llvm::GlobalValue::AppendingLinkage,
855193326Sed                             llvm::ConstantArray::get(ATy, UsedArray),
856198092Srdivacky                             "llvm.used");
857193326Sed
858193326Sed  GV->setSection("llvm.metadata");
859193326Sed}
860193326Sed
861263509Sdimvoid CodeGenModule::AppendLinkerOptions(StringRef Opts) {
862263509Sdim  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
863263509Sdim  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
864263509Sdim}
865263509Sdim
866263509Sdimvoid CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
867263509Sdim  llvm::SmallString<32> Opt;
868263509Sdim  getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
869263509Sdim  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
870263509Sdim  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
871263509Sdim}
872263509Sdim
873263509Sdimvoid CodeGenModule::AddDependentLib(StringRef Lib) {
874263509Sdim  llvm::SmallString<24> Opt;
875263509Sdim  getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
876263509Sdim  llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
877263509Sdim  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
878263509Sdim}
879263509Sdim
880252723Sdim/// \brief Add link options implied by the given module, including modules
881252723Sdim/// it depends on, using a postorder walk.
882263509Sdimstatic void addLinkOptionsPostorder(CodeGenModule &CGM,
883252723Sdim                                    Module *Mod,
884252723Sdim                                    SmallVectorImpl<llvm::Value *> &Metadata,
885252723Sdim                                    llvm::SmallPtrSet<Module *, 16> &Visited) {
886252723Sdim  // Import this module's parent.
887252723Sdim  if (Mod->Parent && Visited.insert(Mod->Parent)) {
888263509Sdim    addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
889252723Sdim  }
890252723Sdim
891252723Sdim  // Import this module's dependencies.
892252723Sdim  for (unsigned I = Mod->Imports.size(); I > 0; --I) {
893252723Sdim    if (Visited.insert(Mod->Imports[I-1]))
894263509Sdim      addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
895252723Sdim  }
896252723Sdim
897252723Sdim  // Add linker options to link against the libraries/frameworks
898252723Sdim  // described by this module.
899263509Sdim  llvm::LLVMContext &Context = CGM.getLLVMContext();
900252723Sdim  for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
901263509Sdim    // Link against a framework.  Frameworks are currently Darwin only, so we
902263509Sdim    // don't to ask TargetCodeGenInfo for the spelling of the linker option.
903252723Sdim    if (Mod->LinkLibraries[I-1].IsFramework) {
904252723Sdim      llvm::Value *Args[2] = {
905252723Sdim        llvm::MDString::get(Context, "-framework"),
906252723Sdim        llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
907252723Sdim      };
908252723Sdim
909252723Sdim      Metadata.push_back(llvm::MDNode::get(Context, Args));
910252723Sdim      continue;
911252723Sdim    }
912252723Sdim
913252723Sdim    // Link against a library.
914263509Sdim    llvm::SmallString<24> Opt;
915263509Sdim    CGM.getTargetCodeGenInfo().getDependentLibraryOption(
916263509Sdim      Mod->LinkLibraries[I-1].Library, Opt);
917263509Sdim    llvm::Value *OptString = llvm::MDString::get(Context, Opt);
918252723Sdim    Metadata.push_back(llvm::MDNode::get(Context, OptString));
919252723Sdim  }
920252723Sdim}
921252723Sdim
922252723Sdimvoid CodeGenModule::EmitModuleLinkOptions() {
923252723Sdim  // Collect the set of all of the modules we want to visit to emit link
924252723Sdim  // options, which is essentially the imported modules and all of their
925252723Sdim  // non-explicit child modules.
926252723Sdim  llvm::SetVector<clang::Module *> LinkModules;
927252723Sdim  llvm::SmallPtrSet<clang::Module *, 16> Visited;
928252723Sdim  SmallVector<clang::Module *, 16> Stack;
929252723Sdim
930252723Sdim  // Seed the stack with imported modules.
931252723Sdim  for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
932252723Sdim                                               MEnd = ImportedModules.end();
933252723Sdim       M != MEnd; ++M) {
934252723Sdim    if (Visited.insert(*M))
935252723Sdim      Stack.push_back(*M);
936252723Sdim  }
937252723Sdim
938252723Sdim  // Find all of the modules to import, making a little effort to prune
939252723Sdim  // non-leaf modules.
940252723Sdim  while (!Stack.empty()) {
941263509Sdim    clang::Module *Mod = Stack.pop_back_val();
942252723Sdim
943252723Sdim    bool AnyChildren = false;
944252723Sdim
945252723Sdim    // Visit the submodules of this module.
946252723Sdim    for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
947252723Sdim                                        SubEnd = Mod->submodule_end();
948252723Sdim         Sub != SubEnd; ++Sub) {
949252723Sdim      // Skip explicit children; they need to be explicitly imported to be
950252723Sdim      // linked against.
951252723Sdim      if ((*Sub)->IsExplicit)
952252723Sdim        continue;
953252723Sdim
954252723Sdim      if (Visited.insert(*Sub)) {
955252723Sdim        Stack.push_back(*Sub);
956252723Sdim        AnyChildren = true;
957252723Sdim      }
958252723Sdim    }
959252723Sdim
960252723Sdim    // We didn't find any children, so add this module to the list of
961252723Sdim    // modules to link against.
962252723Sdim    if (!AnyChildren) {
963252723Sdim      LinkModules.insert(Mod);
964252723Sdim    }
965252723Sdim  }
966252723Sdim
967252723Sdim  // Add link options for all of the imported modules in reverse topological
968263509Sdim  // order.  We don't do anything to try to order import link flags with respect
969263509Sdim  // to linker options inserted by things like #pragma comment().
970252723Sdim  SmallVector<llvm::Value *, 16> MetadataArgs;
971252723Sdim  Visited.clear();
972252723Sdim  for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
973252723Sdim                                               MEnd = LinkModules.end();
974252723Sdim       M != MEnd; ++M) {
975252723Sdim    if (Visited.insert(*M))
976263509Sdim      addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
977252723Sdim  }
978252723Sdim  std::reverse(MetadataArgs.begin(), MetadataArgs.end());
979263509Sdim  LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
980252723Sdim
981252723Sdim  // Add the linker options metadata flag.
982252723Sdim  getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
983263509Sdim                            llvm::MDNode::get(getLLVMContext(),
984263509Sdim                                              LinkerOptionsMetadata));
985252723Sdim}
986252723Sdim
987193326Sedvoid CodeGenModule::EmitDeferred() {
988193326Sed  // Emit code for any potentially referenced deferred decls.  Since a
989193326Sed  // previously unused static decl may become used during the generation of code
990226890Sdim  // for a static function, iterate until no changes are made.
991204962Srdivacky
992252723Sdim  while (true) {
993207619Srdivacky    if (!DeferredVTables.empty()) {
994252723Sdim      EmitDeferredVTables();
995252723Sdim
996252723Sdim      // Emitting a v-table doesn't directly cause more v-tables to
997252723Sdim      // become deferred, although it can cause functions to be
998252723Sdim      // emitted that then need those v-tables.
999252723Sdim      assert(DeferredVTables.empty());
1000204962Srdivacky    }
1001204962Srdivacky
1002252723Sdim    // Stop if we're out of both deferred v-tables and deferred declarations.
1003252723Sdim    if (DeferredDeclsToEmit.empty()) break;
1004252723Sdim
1005193326Sed    GlobalDecl D = DeferredDeclsToEmit.back();
1006193326Sed    DeferredDeclsToEmit.pop_back();
1007193326Sed
1008208600Srdivacky    // Check to see if we've already emitted this.  This is necessary
1009208600Srdivacky    // for a couple of reasons: first, decls can end up in the
1010208600Srdivacky    // deferred-decls queue multiple times, and second, decls can end
1011208600Srdivacky    // up with definitions in unusual ways (e.g. by an extern inline
1012208600Srdivacky    // function acquiring a strong function redefinition).  Just
1013208600Srdivacky    // ignore these cases.
1014208600Srdivacky    //
1015208600Srdivacky    // TODO: That said, looking this up multiple times is very wasteful.
1016226890Sdim    StringRef Name = getMangledName(D);
1017205408Srdivacky    llvm::GlobalValue *CGRef = GetGlobalValue(Name);
1018193326Sed    assert(CGRef && "Deferred decl wasn't referenced?");
1019198092Srdivacky
1020193326Sed    if (!CGRef->isDeclaration())
1021193326Sed      continue;
1022198092Srdivacky
1023208600Srdivacky    // GlobalAlias::isDeclaration() defers to the aliasee, but for our
1024208600Srdivacky    // purposes an alias counts as a definition.
1025208600Srdivacky    if (isa<llvm::GlobalAlias>(CGRef))
1026208600Srdivacky      continue;
1027208600Srdivacky
1028193326Sed    // Otherwise, emit the definition and move on to the next one.
1029193326Sed    EmitGlobalDefinition(D);
1030193326Sed  }
1031193326Sed}
1032193326Sed
1033226890Sdimvoid CodeGenModule::EmitGlobalAnnotations() {
1034226890Sdim  if (Annotations.empty())
1035226890Sdim    return;
1036226890Sdim
1037226890Sdim  // Create a new global variable for the ConstantStruct in the Module.
1038226890Sdim  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1039226890Sdim    Annotations[0]->getType(), Annotations.size()), Annotations);
1040226890Sdim  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
1041226890Sdim    Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
1042226890Sdim    "llvm.global.annotations");
1043226890Sdim  gv->setSection(AnnotationSection);
1044226890Sdim}
1045226890Sdim
1046252723Sdimllvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1047263509Sdim  llvm::Constant *&AStr = AnnotationStrings[Str];
1048263509Sdim  if (AStr)
1049263509Sdim    return AStr;
1050226890Sdim
1051226890Sdim  // Not found yet, create a new global.
1052235633Sdim  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1053226890Sdim  llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1054226890Sdim    true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1055226890Sdim  gv->setSection(AnnotationSection);
1056226890Sdim  gv->setUnnamedAddr(true);
1057263509Sdim  AStr = gv;
1058226890Sdim  return gv;
1059226890Sdim}
1060226890Sdim
1061226890Sdimllvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1062226890Sdim  SourceManager &SM = getContext().getSourceManager();
1063226890Sdim  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1064226890Sdim  if (PLoc.isValid())
1065226890Sdim    return EmitAnnotationString(PLoc.getFilename());
1066226890Sdim  return EmitAnnotationString(SM.getBufferName(Loc));
1067226890Sdim}
1068226890Sdim
1069226890Sdimllvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1070226890Sdim  SourceManager &SM = getContext().getSourceManager();
1071226890Sdim  PresumedLoc PLoc = SM.getPresumedLoc(L);
1072226890Sdim  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1073226890Sdim    SM.getExpansionLineNumber(L);
1074226890Sdim  return llvm::ConstantInt::get(Int32Ty, LineNo);
1075226890Sdim}
1076226890Sdim
1077198092Srdivackyllvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1078193326Sed                                                const AnnotateAttr *AA,
1079226890Sdim                                                SourceLocation L) {
1080226890Sdim  // Get the globals for file name, annotation, and the line number.
1081226890Sdim  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1082226890Sdim                 *UnitGV = EmitAnnotationUnit(L),
1083226890Sdim                 *LineNoCst = EmitAnnotationLineNo(L);
1084193326Sed
1085193326Sed  // Create the ConstantStruct for the global annotation.
1086193326Sed  llvm::Constant *Fields[4] = {
1087226890Sdim    llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1088226890Sdim    llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1089226890Sdim    llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1090226890Sdim    LineNoCst
1091193326Sed  };
1092224145Sdim  return llvm::ConstantStruct::getAnon(Fields);
1093193326Sed}
1094193326Sed
1095226890Sdimvoid CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1096226890Sdim                                         llvm::GlobalValue *GV) {
1097226890Sdim  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1098226890Sdim  // Get the struct elements for these annotations.
1099226890Sdim  for (specific_attr_iterator<AnnotateAttr>
1100226890Sdim       ai = D->specific_attr_begin<AnnotateAttr>(),
1101226890Sdim       ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1102226890Sdim    Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
1103226890Sdim}
1104226890Sdim
1105193326Sedbool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1106212904Sdim  // Never defer when EmitAllDecls is specified.
1107235633Sdim  if (LangOpts.EmitAllDecls)
1108193326Sed    return false;
1109193326Sed
1110212904Sdim  return !getContext().DeclMustBeEmitted(Global);
1111193326Sed}
1112193326Sed
1113245431Sdimllvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1114245431Sdim    const CXXUuidofExpr* E) {
1115245431Sdim  // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1116245431Sdim  // well-formed.
1117263509Sdim  StringRef Uuid = E->getUuidAsStringRef(Context);
1118263509Sdim  std::string Name = "_GUID_" + Uuid.lower();
1119263509Sdim  std::replace(Name.begin(), Name.end(), '-', '_');
1120245431Sdim
1121245431Sdim  // Look for an existing global.
1122245431Sdim  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1123245431Sdim    return GV;
1124245431Sdim
1125245431Sdim  llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1126245431Sdim  assert(Init && "failed to initialize as constant");
1127245431Sdim
1128263509Sdim  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1129263509Sdim      getModule(), Init->getType(),
1130263509Sdim      /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1131245431Sdim  return GV;
1132245431Sdim}
1133245431Sdim
1134204793Srdivackyllvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1135204793Srdivacky  const AliasAttr *AA = VD->getAttr<AliasAttr>();
1136204793Srdivacky  assert(AA && "No alias?");
1137204793Srdivacky
1138226890Sdim  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1139204793Srdivacky
1140204793Srdivacky  // See if there is already something with the target's name in the module.
1141205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1142245431Sdim  if (Entry) {
1143245431Sdim    unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1144245431Sdim    return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1145245431Sdim  }
1146204793Srdivacky
1147204793Srdivacky  llvm::Constant *Aliasee;
1148204793Srdivacky  if (isa<llvm::FunctionType>(DeclTy))
1149245431Sdim    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1150245431Sdim                                      GlobalDecl(cast<FunctionDecl>(VD)),
1151218893Sdim                                      /*ForVTable=*/false);
1152204793Srdivacky  else
1153205408Srdivacky    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1154204793Srdivacky                                    llvm::PointerType::getUnqual(DeclTy), 0);
1155204793Srdivacky
1156245431Sdim  llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1157245431Sdim  F->setLinkage(llvm::Function::ExternalWeakLinkage);
1158245431Sdim  WeakRefReferences.insert(F);
1159245431Sdim
1160204793Srdivacky  return Aliasee;
1161204793Srdivacky}
1162204793Srdivacky
1163193326Sedvoid CodeGenModule::EmitGlobal(GlobalDecl GD) {
1164198092Srdivacky  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1165198092Srdivacky
1166204793Srdivacky  // Weak references don't produce any output by themselves.
1167204793Srdivacky  if (Global->hasAttr<WeakRefAttr>())
1168204793Srdivacky    return;
1169204793Srdivacky
1170193326Sed  // If this is an alias definition (which otherwise looks like a declaration)
1171193326Sed  // emit it now.
1172195341Sed  if (Global->hasAttr<AliasAttr>())
1173205408Srdivacky    return EmitAliasDefinition(GD);
1174193326Sed
1175226890Sdim  // If this is CUDA, be selective about which declarations we emit.
1176235633Sdim  if (LangOpts.CUDA) {
1177226890Sdim    if (CodeGenOpts.CUDAIsDevice) {
1178226890Sdim      if (!Global->hasAttr<CUDADeviceAttr>() &&
1179226890Sdim          !Global->hasAttr<CUDAGlobalAttr>() &&
1180226890Sdim          !Global->hasAttr<CUDAConstantAttr>() &&
1181226890Sdim          !Global->hasAttr<CUDASharedAttr>())
1182226890Sdim        return;
1183226890Sdim    } else {
1184226890Sdim      if (!Global->hasAttr<CUDAHostAttr>() && (
1185226890Sdim            Global->hasAttr<CUDADeviceAttr>() ||
1186226890Sdim            Global->hasAttr<CUDAConstantAttr>() ||
1187226890Sdim            Global->hasAttr<CUDASharedAttr>()))
1188226890Sdim        return;
1189226890Sdim    }
1190226890Sdim  }
1191226890Sdim
1192193326Sed  // Ignore declarations, they will be emitted on their first use.
1193193326Sed  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1194226890Sdim    // Forward declarations are emitted lazily on first use.
1195226890Sdim    if (!FD->doesThisDeclarationHaveABody()) {
1196226890Sdim      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1197226890Sdim        return;
1198212904Sdim
1199226890Sdim      const FunctionDecl *InlineDefinition = 0;
1200226890Sdim      FD->getBody(InlineDefinition);
1201226890Sdim
1202226890Sdim      StringRef MangledName = getMangledName(GD);
1203235633Sdim      DeferredDecls.erase(MangledName);
1204226890Sdim      EmitGlobalDefinition(InlineDefinition);
1205193326Sed      return;
1206226890Sdim    }
1207193326Sed  } else {
1208193326Sed    const VarDecl *VD = cast<VarDecl>(Global);
1209193326Sed    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1210193326Sed
1211203955Srdivacky    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1212193326Sed      return;
1213193326Sed  }
1214193326Sed
1215193326Sed  // Defer code generation when possible if this is a static definition, inline
1216193326Sed  // function etc.  These we only want to emit if they are used.
1217207619Srdivacky  if (!MayDeferGeneration(Global)) {
1218207619Srdivacky    // Emit the definition if it can't be deferred.
1219207619Srdivacky    EmitGlobalDefinition(GD);
1220193326Sed    return;
1221193326Sed  }
1222212904Sdim
1223212904Sdim  // If we're deferring emission of a C++ variable with an
1224212904Sdim  // initializer, remember the order in which it appeared in the file.
1225235633Sdim  if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1226212904Sdim      cast<VarDecl>(Global)->hasInit()) {
1227212904Sdim    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1228212904Sdim    CXXGlobalInits.push_back(0);
1229212904Sdim  }
1230207619Srdivacky
1231207619Srdivacky  // If the value has already been used, add it directly to the
1232207619Srdivacky  // DeferredDeclsToEmit list.
1233226890Sdim  StringRef MangledName = getMangledName(GD);
1234207619Srdivacky  if (GetGlobalValue(MangledName))
1235207619Srdivacky    DeferredDeclsToEmit.push_back(GD);
1236207619Srdivacky  else {
1237207619Srdivacky    // Otherwise, remember that we saw a deferred decl with this name.  The
1238207619Srdivacky    // first use of the mangled name will cause it to move into
1239207619Srdivacky    // DeferredDeclsToEmit.
1240207619Srdivacky    DeferredDecls[MangledName] = GD;
1241207619Srdivacky  }
1242193326Sed}
1243193326Sed
1244229042Sdimnamespace {
1245229042Sdim  struct FunctionIsDirectlyRecursive :
1246229042Sdim    public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1247229042Sdim    const StringRef Name;
1248235633Sdim    const Builtin::Context &BI;
1249229042Sdim    bool Result;
1250235633Sdim    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1251235633Sdim      Name(N), BI(C), Result(false) {
1252229042Sdim    }
1253229042Sdim    typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1254229042Sdim
1255229042Sdim    bool TraverseCallExpr(CallExpr *E) {
1256235633Sdim      const FunctionDecl *FD = E->getDirectCallee();
1257235633Sdim      if (!FD)
1258229042Sdim        return true;
1259235633Sdim      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1260235633Sdim      if (Attr && Name == Attr->getLabel()) {
1261235633Sdim        Result = true;
1262235633Sdim        return false;
1263235633Sdim      }
1264235633Sdim      unsigned BuiltinID = FD->getBuiltinID();
1265235633Sdim      if (!BuiltinID)
1266229042Sdim        return true;
1267235633Sdim      StringRef BuiltinName = BI.GetName(BuiltinID);
1268235633Sdim      if (BuiltinName.startswith("__builtin_") &&
1269235633Sdim          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1270229042Sdim        Result = true;
1271229042Sdim        return false;
1272229042Sdim      }
1273229042Sdim      return true;
1274229042Sdim    }
1275229042Sdim  };
1276229042Sdim}
1277229042Sdim
1278235633Sdim// isTriviallyRecursive - Check if this function calls another
1279235633Sdim// decl that, because of the asm attribute or the other decl being a builtin,
1280235633Sdim// ends up pointing to itself.
1281229042Sdimbool
1282235633SdimCodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1283235633Sdim  StringRef Name;
1284235633Sdim  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1285235633Sdim    // asm labels are a special kind of mangling we have to support.
1286235633Sdim    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1287235633Sdim    if (!Attr)
1288235633Sdim      return false;
1289235633Sdim    Name = Attr->getLabel();
1290235633Sdim  } else {
1291235633Sdim    Name = FD->getName();
1292235633Sdim  }
1293229042Sdim
1294235633Sdim  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1295235633Sdim  Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1296229042Sdim  return Walker.Result;
1297229042Sdim}
1298229042Sdim
1299229042Sdimbool
1300263509SdimCodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1301263509Sdim  if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1302229042Sdim    return true;
1303263509Sdim  const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
1304229042Sdim  if (CodeGenOpts.OptimizationLevel == 0 &&
1305245431Sdim      !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
1306229042Sdim    return false;
1307229042Sdim  // PR9614. Avoid cases where the source code is lying to us. An available
1308229042Sdim  // externally function should have an equivalent function somewhere else,
1309229042Sdim  // but a function that calls itself is clearly not equivalent to the real
1310229042Sdim  // implementation.
1311229042Sdim  // This happens in glibc's btowc and in some configure checks.
1312235633Sdim  return !isTriviallyRecursive(F);
1313229042Sdim}
1314229042Sdim
1315263509Sdim/// If the type for the method's class was generated by
1316263509Sdim/// CGDebugInfo::createContextChain(), the cache contains only a
1317263509Sdim/// limited DIType without any declarations. Since EmitFunctionStart()
1318263509Sdim/// needs to find the canonical declaration for each method, we need
1319263509Sdim/// to construct the complete type prior to emitting the method.
1320263509Sdimvoid CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1321263509Sdim  if (!D->isInstance())
1322263509Sdim    return;
1323263509Sdim
1324263509Sdim  if (CGDebugInfo *DI = getModuleDebugInfo())
1325263509Sdim    if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1326263509Sdim      const PointerType *ThisPtr =
1327263509Sdim        cast<PointerType>(D->getThisType(getContext()));
1328263509Sdim      DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1329263509Sdim    }
1330263509Sdim}
1331263509Sdim
1332193326Sedvoid CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
1333198092Srdivacky  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1334198092Srdivacky
1335207619Srdivacky  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1336198893Srdivacky                                 Context.getSourceManager(),
1337198893Srdivacky                                 "Generating code for declaration");
1338198893Srdivacky
1339263509Sdim  if (isa<FunctionDecl>(D)) {
1340210299Sed    // At -O0, don't generate IR for functions with available_externally
1341210299Sed    // linkage.
1342263509Sdim    if (!shouldEmitFunction(GD))
1343210299Sed      return;
1344206084Srdivacky
1345210299Sed    if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1346263509Sdim      CompleteDIClassType(Method);
1347223017Sdim      // Make sure to emit the definition(s) before we emit the thunks.
1348223017Sdim      // This is necessary for the generation of certain thunks.
1349223017Sdim      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1350223017Sdim        EmitCXXConstructor(CD, GD.getCtorType());
1351223017Sdim      else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1352223017Sdim        EmitCXXDestructor(DD, GD.getDtorType());
1353223017Sdim      else
1354223017Sdim        EmitGlobalFunctionDefinition(GD);
1355223017Sdim
1356210299Sed      if (Method->isVirtual())
1357210299Sed        getVTables().EmitThunks(GD);
1358210299Sed
1359223017Sdim      return;
1360210299Sed    }
1361207619Srdivacky
1362207619Srdivacky    return EmitGlobalFunctionDefinition(GD);
1363210299Sed  }
1364207619Srdivacky
1365207619Srdivacky  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1366207619Srdivacky    return EmitGlobalVarDefinition(VD);
1367207619Srdivacky
1368226890Sdim  llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1369193326Sed}
1370193326Sed
1371193326Sed/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1372193326Sed/// module, create and return an llvm Function with the specified type. If there
1373193326Sed/// is something in the module with the specified name, return it potentially
1374193326Sed/// bitcasted to the right type.
1375193326Sed///
1376193326Sed/// If D is non-null, it specifies a decl that correspond to this.  This is used
1377193326Sed/// to set the attributes on the function when it is first created.
1378205408Srdivackyllvm::Constant *
1379226890SdimCodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1380226890Sdim                                       llvm::Type *Ty,
1381263509Sdim                                       GlobalDecl GD, bool ForVTable,
1382252723Sdim                                       llvm::AttributeSet ExtraAttrs) {
1383263509Sdim  const Decl *D = GD.getDecl();
1384263509Sdim
1385193326Sed  // Lookup the entry, lazily creating it if necessary.
1386205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1387193326Sed  if (Entry) {
1388245431Sdim    if (WeakRefReferences.erase(Entry)) {
1389263509Sdim      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1390204793Srdivacky      if (FD && !FD->hasAttr<WeakAttr>())
1391206084Srdivacky        Entry->setLinkage(llvm::Function::ExternalLinkage);
1392204793Srdivacky    }
1393204793Srdivacky
1394193326Sed    if (Entry->getType()->getElementType() == Ty)
1395193326Sed      return Entry;
1396198092Srdivacky
1397193326Sed    // Make sure the result is of the correct type.
1398224145Sdim    return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1399193326Sed  }
1400198092Srdivacky
1401263509Sdim  // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1402263509Sdim  // each other bottoming out with the base dtor.  Therefore we emit non-base
1403263509Sdim  // dtors on usage, even if there is no dtor definition in the TU.
1404263509Sdim  if (D && isa<CXXDestructorDecl>(D) &&
1405263509Sdim      getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1406263509Sdim                                         GD.getDtorType()))
1407263509Sdim    DeferredDeclsToEmit.push_back(GD);
1408263509Sdim
1409199482Srdivacky  // This function doesn't have a complete type (for example, the return
1410199482Srdivacky  // type is an incomplete struct). Use a fake type instead, and make
1411199482Srdivacky  // sure not to try to set attributes.
1412199482Srdivacky  bool IsIncompleteFunction = false;
1413207619Srdivacky
1414226890Sdim  llvm::FunctionType *FTy;
1415207619Srdivacky  if (isa<llvm::FunctionType>(Ty)) {
1416207619Srdivacky    FTy = cast<llvm::FunctionType>(Ty);
1417207619Srdivacky  } else {
1418223017Sdim    FTy = llvm::FunctionType::get(VoidTy, false);
1419199482Srdivacky    IsIncompleteFunction = true;
1420199482Srdivacky  }
1421210299Sed
1422207619Srdivacky  llvm::Function *F = llvm::Function::Create(FTy,
1423199482Srdivacky                                             llvm::Function::ExternalLinkage,
1424205408Srdivacky                                             MangledName, &getModule());
1425205408Srdivacky  assert(F->getName() == MangledName && "name was uniqued!");
1426263509Sdim  if (D)
1427263509Sdim    SetFunctionAttributes(GD, F, IsIncompleteFunction);
1428252723Sdim  if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1429252723Sdim    llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1430252723Sdim    F->addAttributes(llvm::AttributeSet::FunctionIndex,
1431252723Sdim                     llvm::AttributeSet::get(VMContext,
1432252723Sdim                                             llvm::AttributeSet::FunctionIndex,
1433252723Sdim                                             B));
1434252723Sdim  }
1435199482Srdivacky
1436193326Sed  // This is the first use or definition of a mangled name.  If there is a
1437193326Sed  // deferred decl with this name, remember that we need to emit it at the end
1438193326Sed  // of the file.
1439205408Srdivacky  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1440193326Sed  if (DDI != DeferredDecls.end()) {
1441193326Sed    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1442193326Sed    // list, and remove it from DeferredDecls (since we don't need it anymore).
1443193326Sed    DeferredDeclsToEmit.push_back(DDI->second);
1444193326Sed    DeferredDecls.erase(DDI);
1445218893Sdim
1446263509Sdim  // Otherwise, if this is a sized deallocation function, emit a weak definition
1447263509Sdim  // for it at the end of the translation unit.
1448263509Sdim  } else if (D && cast<FunctionDecl>(D)
1449263509Sdim                      ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1450263509Sdim    DeferredDeclsToEmit.push_back(GD);
1451263509Sdim
1452218893Sdim  // Otherwise, there are cases we have to worry about where we're
1453218893Sdim  // using a declaration for which we must emit a definition but where
1454218893Sdim  // we might not find a top-level definition:
1455218893Sdim  //   - member functions defined inline in their classes
1456218893Sdim  //   - friend functions defined inline in some class
1457218893Sdim  //   - special member functions with implicit definitions
1458218893Sdim  // If we ever change our AST traversal to walk into class methods,
1459218893Sdim  // this will be unnecessary.
1460218893Sdim  //
1461218893Sdim  // We also don't emit a definition for a function if it's going to be an entry
1462218893Sdim  // in a vtable, unless it's already marked as used.
1463263509Sdim  } else if (getLangOpts().CPlusPlus && D) {
1464218893Sdim    // Look for a declaration that's lexically in a record.
1465263509Sdim    const FunctionDecl *FD = cast<FunctionDecl>(D);
1466245431Sdim    FD = FD->getMostRecentDecl();
1467218893Sdim    do {
1468218893Sdim      if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1469218893Sdim        if (FD->isImplicit() && !ForVTable) {
1470218893Sdim          assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1471263509Sdim          DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1472218893Sdim          break;
1473223017Sdim        } else if (FD->doesThisDeclarationHaveABody()) {
1474263509Sdim          DeferredDeclsToEmit.push_back(GD.getWithDecl(FD));
1475218893Sdim          break;
1476218893Sdim        }
1477204643Srdivacky      }
1478235633Sdim      FD = FD->getPreviousDecl();
1479218893Sdim    } while (FD);
1480193326Sed  }
1481198092Srdivacky
1482207619Srdivacky  // Make sure the result is of the requested type.
1483207619Srdivacky  if (!IsIncompleteFunction) {
1484207619Srdivacky    assert(F->getType()->getElementType() == Ty);
1485207619Srdivacky    return F;
1486207619Srdivacky  }
1487207619Srdivacky
1488224145Sdim  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1489207619Srdivacky  return llvm::ConstantExpr::getBitCast(F, PTy);
1490193326Sed}
1491193326Sed
1492193326Sed/// GetAddrOfFunction - Return the address of the given function.  If Ty is
1493193326Sed/// non-null, then this function will use the specified type if it has to
1494193326Sed/// create it (this occurs when we see a definition of the function).
1495193326Sedllvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1496226890Sdim                                                 llvm::Type *Ty,
1497218893Sdim                                                 bool ForVTable) {
1498193326Sed  // If there was no specific requested type, just convert it now.
1499193326Sed  if (!Ty)
1500198092Srdivacky    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1501210299Sed
1502226890Sdim  StringRef MangledName = getMangledName(GD);
1503218893Sdim  return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1504193326Sed}
1505193326Sed
1506193326Sed/// CreateRuntimeFunction - Create a new runtime function with the specified
1507193326Sed/// type and name.
1508193326Sedllvm::Constant *
1509226890SdimCodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1510226890Sdim                                     StringRef Name,
1511252723Sdim                                     llvm::AttributeSet ExtraAttrs) {
1512252723Sdim  llvm::Constant *C
1513252723Sdim    = GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1514252723Sdim                              ExtraAttrs);
1515252723Sdim  if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1516252723Sdim    if (F->empty())
1517252723Sdim      F->setCallingConv(getRuntimeCC());
1518252723Sdim  return C;
1519193326Sed}
1520193326Sed
1521235633Sdim/// isTypeConstant - Determine whether an object of this type can be emitted
1522235633Sdim/// as a constant.
1523235633Sdim///
1524235633Sdim/// If ExcludeCtor is true, the duration when the object's constructor runs
1525235633Sdim/// will not be considered. The caller will need to verify that the object is
1526235633Sdim/// not written to during its construction.
1527235633Sdimbool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1528235633Sdim  if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1529200583Srdivacky    return false;
1530235633Sdim
1531235633Sdim  if (Context.getLangOpts().CPlusPlus) {
1532235633Sdim    if (const CXXRecordDecl *Record
1533235633Sdim          = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1534235633Sdim      return ExcludeCtor && !Record->hasMutableFields() &&
1535235633Sdim             Record->hasTrivialDestructor();
1536200583Srdivacky  }
1537235633Sdim
1538200583Srdivacky  return true;
1539200583Srdivacky}
1540200583Srdivacky
1541193326Sed/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1542193326Sed/// create and return an llvm GlobalVariable with the specified type.  If there
1543193326Sed/// is something in the module with the specified name, return it potentially
1544193326Sed/// bitcasted to the right type.
1545193326Sed///
1546193326Sed/// If D is non-null, it specifies a decl that correspond to this.  This is used
1547193326Sed/// to set the attributes on the global when it is first created.
1548205408Srdivackyllvm::Constant *
1549226890SdimCodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1550226890Sdim                                     llvm::PointerType *Ty,
1551218893Sdim                                     const VarDecl *D,
1552218893Sdim                                     bool UnnamedAddr) {
1553193326Sed  // Lookup the entry, lazily creating it if necessary.
1554205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1555193326Sed  if (Entry) {
1556245431Sdim    if (WeakRefReferences.erase(Entry)) {
1557204793Srdivacky      if (D && !D->hasAttr<WeakAttr>())
1558206084Srdivacky        Entry->setLinkage(llvm::Function::ExternalLinkage);
1559204793Srdivacky    }
1560204793Srdivacky
1561218893Sdim    if (UnnamedAddr)
1562218893Sdim      Entry->setUnnamedAddr(true);
1563218893Sdim
1564193326Sed    if (Entry->getType() == Ty)
1565193326Sed      return Entry;
1566198092Srdivacky
1567193326Sed    // Make sure the result is of the correct type.
1568263509Sdim    if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1569263509Sdim      return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1570263509Sdim
1571193326Sed    return llvm::ConstantExpr::getBitCast(Entry, Ty);
1572193326Sed  }
1573198092Srdivacky
1574193326Sed  // This is the first use or definition of a mangled name.  If there is a
1575193326Sed  // deferred decl with this name, remember that we need to emit it at the end
1576193326Sed  // of the file.
1577205408Srdivacky  llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1578193326Sed  if (DDI != DeferredDecls.end()) {
1579193326Sed    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1580193326Sed    // list, and remove it from DeferredDecls (since we don't need it anymore).
1581193326Sed    DeferredDeclsToEmit.push_back(DDI->second);
1582193326Sed    DeferredDecls.erase(DDI);
1583193326Sed  }
1584198092Srdivacky
1585245431Sdim  unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1586198092Srdivacky  llvm::GlobalVariable *GV =
1587198092Srdivacky    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1588193326Sed                             llvm::GlobalValue::ExternalLinkage,
1589205408Srdivacky                             0, MangledName, 0,
1590245431Sdim                             llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1591193326Sed
1592193326Sed  // Handle things which are present even on external declarations.
1593193326Sed  if (D) {
1594193326Sed    // FIXME: This code is overly simple and should be merged with other global
1595193326Sed    // handling.
1596235633Sdim    GV->setConstant(isTypeConstant(D->getType(), false));
1597193326Sed
1598218893Sdim    // Set linkage and visibility in case we never see a definition.
1599252723Sdim    LinkageInfo LV = D->getLinkageAndVisibility();
1600252723Sdim    if (LV.getLinkage() != ExternalLinkage) {
1601218893Sdim      // Don't set internal linkage on declarations.
1602218893Sdim    } else {
1603218893Sdim      if (D->hasAttr<DLLImportAttr>())
1604218893Sdim        GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1605221345Sdim      else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1606218893Sdim        GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1607193326Sed
1608218893Sdim      // Set visibility on a declaration only if it's explicit.
1609252723Sdim      if (LV.isVisibilityExplicit())
1610252723Sdim        GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1611218893Sdim    }
1612193326Sed
1613252723Sdim    if (D->getTLSKind()) {
1614252723Sdim      if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1615252723Sdim        CXXThreadLocals.push_back(std::make_pair(D, GV));
1616245431Sdim      setTLSMode(GV, *D);
1617252723Sdim    }
1618263509Sdim
1619263509Sdim    // If required by the ABI, treat declarations of static data members with
1620263509Sdim    // inline initializers as definitions.
1621263509Sdim    if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1622263509Sdim        D->isStaticDataMember() && D->hasInit() &&
1623263509Sdim        !D->isThisDeclarationADefinition())
1624263509Sdim      EmitGlobalVarDefinition(D);
1625193326Sed  }
1626198092Srdivacky
1627245431Sdim  if (AddrSpace != Ty->getAddressSpace())
1628263509Sdim    return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1629263509Sdim
1630263509Sdim  return GV;
1631193326Sed}
1632193326Sed
1633193326Sed
1634218893Sdimllvm::GlobalVariable *
1635226890SdimCodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1636226890Sdim                                      llvm::Type *Ty,
1637218893Sdim                                      llvm::GlobalValue::LinkageTypes Linkage) {
1638218893Sdim  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1639218893Sdim  llvm::GlobalVariable *OldGV = 0;
1640218893Sdim
1641218893Sdim
1642218893Sdim  if (GV) {
1643218893Sdim    // Check if the variable has the right type.
1644218893Sdim    if (GV->getType()->getElementType() == Ty)
1645218893Sdim      return GV;
1646218893Sdim
1647218893Sdim    // Because C++ name mangling, the only way we can end up with an already
1648218893Sdim    // existing global with the same name is if it has been declared extern "C".
1649245431Sdim    assert(GV->isDeclaration() && "Declaration has wrong type!");
1650218893Sdim    OldGV = GV;
1651218893Sdim  }
1652218893Sdim
1653218893Sdim  // Create a new variable.
1654218893Sdim  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1655218893Sdim                                Linkage, 0, Name);
1656218893Sdim
1657218893Sdim  if (OldGV) {
1658218893Sdim    // Replace occurrences of the old variable if needed.
1659218893Sdim    GV->takeName(OldGV);
1660218893Sdim
1661218893Sdim    if (!OldGV->use_empty()) {
1662218893Sdim      llvm::Constant *NewPtrForOldDecl =
1663218893Sdim      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1664218893Sdim      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1665218893Sdim    }
1666218893Sdim
1667218893Sdim    OldGV->eraseFromParent();
1668218893Sdim  }
1669218893Sdim
1670218893Sdim  return GV;
1671218893Sdim}
1672218893Sdim
1673193326Sed/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1674193326Sed/// given global variable.  If Ty is non-null and if the global doesn't exist,
1675235633Sdim/// then it will be created with the specified type instead of whatever the
1676193326Sed/// normal requested type would be.
1677193326Sedllvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1678226890Sdim                                                  llvm::Type *Ty) {
1679193326Sed  assert(D->hasGlobalStorage() && "Not a global variable");
1680193326Sed  QualType ASTTy = D->getType();
1681193326Sed  if (Ty == 0)
1682193326Sed    Ty = getTypes().ConvertTypeForMem(ASTTy);
1683198092Srdivacky
1684226890Sdim  llvm::PointerType *PTy =
1685221345Sdim    llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1686205408Srdivacky
1687226890Sdim  StringRef MangledName = getMangledName(D);
1688205408Srdivacky  return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1689193326Sed}
1690193326Sed
1691193326Sed/// CreateRuntimeVariable - Create a new runtime global variable with the
1692193326Sed/// specified type and name.
1693193326Sedllvm::Constant *
1694226890SdimCodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1695226890Sdim                                     StringRef Name) {
1696221345Sdim  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1697218893Sdim                               true);
1698193326Sed}
1699193326Sed
1700193326Sedvoid CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1701193326Sed  assert(!D->getInit() && "Cannot emit definite definitions here!");
1702193326Sed
1703193326Sed  if (MayDeferGeneration(D)) {
1704193326Sed    // If we have not seen a reference to this variable yet, place it
1705193326Sed    // into the deferred declarations table to be emitted if needed
1706193326Sed    // later.
1707226890Sdim    StringRef MangledName = getMangledName(D);
1708205408Srdivacky    if (!GetGlobalValue(MangledName)) {
1709198092Srdivacky      DeferredDecls[MangledName] = D;
1710193326Sed      return;
1711193326Sed    }
1712193326Sed  }
1713193326Sed
1714193326Sed  // The tentative definition is the only definition.
1715193326Sed  EmitGlobalVarDefinition(D);
1716193326Sed}
1717193326Sed
1718226890SdimCharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1719218893Sdim    return Context.toCharUnitsFromBits(
1720245431Sdim      TheDataLayout.getTypeStoreSizeInBits(Ty));
1721203955Srdivacky}
1722203955Srdivacky
1723245431Sdimunsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1724245431Sdim                                                 unsigned AddrSpace) {
1725245431Sdim  if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1726245431Sdim    if (D->hasAttr<CUDAConstantAttr>())
1727245431Sdim      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1728245431Sdim    else if (D->hasAttr<CUDASharedAttr>())
1729245431Sdim      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1730245431Sdim    else
1731245431Sdim      AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1732245431Sdim  }
1733245431Sdim
1734245431Sdim  return AddrSpace;
1735245431Sdim}
1736245431Sdim
1737252723Sdimtemplate<typename SomeDecl>
1738252723Sdimvoid CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1739252723Sdim                                               llvm::GlobalValue *GV) {
1740252723Sdim  if (!getLangOpts().CPlusPlus)
1741252723Sdim    return;
1742252723Sdim
1743252723Sdim  // Must have 'used' attribute, or else inline assembly can't rely on
1744252723Sdim  // the name existing.
1745252723Sdim  if (!D->template hasAttr<UsedAttr>())
1746252723Sdim    return;
1747252723Sdim
1748252723Sdim  // Must have internal linkage and an ordinary name.
1749263509Sdim  if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1750252723Sdim    return;
1751252723Sdim
1752252723Sdim  // Must be in an extern "C" context. Entities declared directly within
1753252723Sdim  // a record are not extern "C" even if the record is in such a context.
1754263509Sdim  const SomeDecl *First = D->getFirstDecl();
1755252723Sdim  if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1756252723Sdim    return;
1757252723Sdim
1758252723Sdim  // OK, this is an internal linkage entity inside an extern "C" linkage
1759252723Sdim  // specification. Make a note of that so we can give it the "expected"
1760252723Sdim  // mangled name if nothing else is using that name.
1761252723Sdim  std::pair<StaticExternCMap::iterator, bool> R =
1762252723Sdim      StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1763252723Sdim
1764252723Sdim  // If we have multiple internal linkage entities with the same name
1765252723Sdim  // in extern "C" regions, none of them gets that name.
1766252723Sdim  if (!R.second)
1767252723Sdim    R.first->second = 0;
1768252723Sdim}
1769252723Sdim
1770193326Sedvoid CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1771193326Sed  llvm::Constant *Init = 0;
1772193326Sed  QualType ASTTy = D->getType();
1773235633Sdim  CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1774235633Sdim  bool NeedsGlobalCtor = false;
1775235633Sdim  bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1776198092Srdivacky
1777235633Sdim  const VarDecl *InitDecl;
1778235633Sdim  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1779235633Sdim
1780203955Srdivacky  if (!InitExpr) {
1781193326Sed    // This is a tentative definition; tentative definitions are
1782193326Sed    // implicitly initialized with { 0 }.
1783193326Sed    //
1784193326Sed    // Note that tentative definitions are only emitted at the end of
1785193326Sed    // a translation unit, so they should never have incomplete
1786193326Sed    // type. In addition, EmitTentativeDefinition makes sure that we
1787193326Sed    // never attempt to emit a tentative definition if a real one
1788193326Sed    // exists. A use may still exists, however, so we still may need
1789193326Sed    // to do a RAUW.
1790193326Sed    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1791198092Srdivacky    Init = EmitNullConstant(D->getType());
1792193326Sed  } else {
1793263509Sdim    initializedGlobalDecl = GlobalDecl(D);
1794263509Sdim    Init = EmitConstantInit(*InitDecl);
1795235633Sdim
1796245431Sdim    if (!Init) {
1797203955Srdivacky      QualType T = InitExpr->getType();
1798208600Srdivacky      if (D->getType()->isReferenceType())
1799208600Srdivacky        T = D->getType();
1800235633Sdim
1801235633Sdim      if (getLangOpts().CPlusPlus) {
1802198092Srdivacky        Init = EmitNullConstant(T);
1803235633Sdim        NeedsGlobalCtor = true;
1804198092Srdivacky      } else {
1805198092Srdivacky        ErrorUnsupported(D, "static initializer");
1806198092Srdivacky        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1807198092Srdivacky      }
1808212904Sdim    } else {
1809212904Sdim      // We don't need an initializer, so remove the entry for the delayed
1810235633Sdim      // initializer position (just in case this entry was delayed) if we
1811235633Sdim      // also don't need to register a destructor.
1812235633Sdim      if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1813212904Sdim        DelayedCXXInitPosition.erase(D);
1814193326Sed    }
1815193326Sed  }
1816193326Sed
1817226890Sdim  llvm::Type* InitType = Init->getType();
1818193326Sed  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1819198092Srdivacky
1820193326Sed  // Strip off a bitcast if we got one back.
1821193326Sed  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1822198092Srdivacky    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1823263509Sdim           CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1824263509Sdim           // All zero index gep.
1825198092Srdivacky           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1826193326Sed    Entry = CE->getOperand(0);
1827193326Sed  }
1828198092Srdivacky
1829193326Sed  // Entry is now either a Function or GlobalVariable.
1830193326Sed  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1831198092Srdivacky
1832193326Sed  // We have a definition after a declaration with the wrong type.
1833193326Sed  // We must make a new GlobalVariable* and update everything that used OldGV
1834193326Sed  // (a declaration or tentative definition) with the new GlobalVariable*
1835193326Sed  // (which will be a definition).
1836193326Sed  //
1837193326Sed  // This happens if there is a prototype for a global (e.g.
1838193326Sed  // "extern int x[];") and then a definition of a different type (e.g.
1839193326Sed  // "int x[10];"). This also happens when an initializer has a different type
1840193326Sed  // from the type of the global (this happens with unions).
1841193326Sed  if (GV == 0 ||
1842193326Sed      GV->getType()->getElementType() != InitType ||
1843221345Sdim      GV->getType()->getAddressSpace() !=
1844245431Sdim       GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1845198092Srdivacky
1846205408Srdivacky    // Move the old entry aside so that we'll create a new one.
1847226890Sdim    Entry->setName(StringRef());
1848193326Sed
1849193326Sed    // Make a new global with the correct type, this is now guaranteed to work.
1850193326Sed    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1851193326Sed
1852193326Sed    // Replace all uses of the old global with the new global
1853198092Srdivacky    llvm::Constant *NewPtrForOldDecl =
1854193326Sed        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1855193326Sed    Entry->replaceAllUsesWith(NewPtrForOldDecl);
1856193326Sed
1857193326Sed    // Erase the old global, since it is no longer used.
1858193326Sed    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1859193326Sed  }
1860193326Sed
1861252723Sdim  MaybeHandleStaticInExternC(D, GV);
1862252723Sdim
1863226890Sdim  if (D->hasAttr<AnnotateAttr>())
1864226890Sdim    AddGlobalAnnotations(D, GV);
1865193326Sed
1866193326Sed  GV->setInitializer(Init);
1867198092Srdivacky
1868198092Srdivacky  // If it is safe to mark the global 'constant', do so now.
1869235633Sdim  GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1870235633Sdim                  isTypeConstant(D->getType(), true));
1871198092Srdivacky
1872203955Srdivacky  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1873235633Sdim
1874218893Sdim  // Set the llvm linkage type as appropriate.
1875218893Sdim  llvm::GlobalValue::LinkageTypes Linkage =
1876263509Sdim    GetLLVMLinkageVarDefinition(D, GV->isConstant());
1877218893Sdim  GV->setLinkage(Linkage);
1878263509Sdim
1879263509Sdim  // If required by the ABI, give definitions of static data members with inline
1880263509Sdim  // initializers linkonce_odr linkage.
1881263509Sdim  if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1882263509Sdim      D->isStaticDataMember() && InitExpr &&
1883263509Sdim      !InitDecl->isThisDeclarationADefinition())
1884263509Sdim    GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1885263509Sdim
1886218893Sdim  if (Linkage == llvm::GlobalVariable::CommonLinkage)
1887218893Sdim    // common vars aren't constant even if declared const.
1888218893Sdim    GV->setConstant(false);
1889193326Sed
1890218893Sdim  SetCommonAttributes(D, GV);
1891218893Sdim
1892218893Sdim  // Emit the initializer function if necessary.
1893235633Sdim  if (NeedsGlobalCtor || NeedsGlobalDtor)
1894235633Sdim    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1895218893Sdim
1896245431Sdim  // If we are compiling with ASan, add metadata indicating dynamically
1897245431Sdim  // initialized globals.
1898252723Sdim  if (SanOpts.Address && NeedsGlobalCtor) {
1899245431Sdim    llvm::Module &M = getModule();
1900245431Sdim
1901245431Sdim    llvm::NamedMDNode *DynamicInitializers =
1902245431Sdim        M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1903245431Sdim    llvm::Value *GlobalToAdd[] = { GV };
1904245431Sdim    llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1905245431Sdim    DynamicInitializers->addOperand(ThisGlobal);
1906245431Sdim  }
1907245431Sdim
1908218893Sdim  // Emit global variable debug information.
1909226890Sdim  if (CGDebugInfo *DI = getModuleDebugInfo())
1910245431Sdim    if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1911245431Sdim      DI->EmitGlobalVariable(GV, D);
1912218893Sdim}
1913218893Sdim
1914218893Sdimllvm::GlobalValue::LinkageTypes
1915263509SdimCodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
1916212904Sdim  GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1917198112Srdivacky  if (Linkage == GVA_Internal)
1918218893Sdim    return llvm::Function::InternalLinkage;
1919195341Sed  else if (D->hasAttr<DLLImportAttr>())
1920218893Sdim    return llvm::Function::DLLImportLinkage;
1921195341Sed  else if (D->hasAttr<DLLExportAttr>())
1922218893Sdim    return llvm::Function::DLLExportLinkage;
1923263509Sdim  else if (D->hasAttr<SelectAnyAttr>()) {
1924263509Sdim    // selectany symbols are externally visible, so use weak instead of
1925263509Sdim    // linkonce.  MSVC optimizes away references to const selectany globals, so
1926263509Sdim    // all definitions should be the same and ODR linkage should be used.
1927263509Sdim    // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1928263509Sdim    return llvm::GlobalVariable::WeakODRLinkage;
1929263509Sdim  } else if (D->hasAttr<WeakAttr>()) {
1930263509Sdim    if (isConstant)
1931218893Sdim      return llvm::GlobalVariable::WeakODRLinkage;
1932198092Srdivacky    else
1933218893Sdim      return llvm::GlobalVariable::WeakAnyLinkage;
1934205219Srdivacky  } else if (Linkage == GVA_TemplateInstantiation ||
1935205219Srdivacky             Linkage == GVA_ExplicitTemplateInstantiation)
1936221345Sdim    return llvm::GlobalVariable::WeakODRLinkage;
1937235633Sdim  else if (!getLangOpts().CPlusPlus &&
1938218893Sdim           ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1939218893Sdim             D->getAttr<CommonAttr>()) &&
1940198092Srdivacky           !D->hasExternalStorage() && !D->getInit() &&
1941252723Sdim           !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
1942224145Sdim           !D->getAttr<WeakImportAttr>()) {
1943212904Sdim    // Thread local vars aren't considered common linkage.
1944218893Sdim    return llvm::GlobalVariable::CommonLinkage;
1945252723Sdim  } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1946252723Sdim             getTarget().getTriple().isMacOSX())
1947252723Sdim    // On Darwin, the backing variable for a C++11 thread_local variable always
1948252723Sdim    // has internal linkage; all accesses should just be calls to the
1949252723Sdim    // Itanium-specified entry point, which has the normal linkage of the
1950252723Sdim    // variable.
1951252723Sdim    return llvm::GlobalValue::InternalLinkage;
1952218893Sdim  return llvm::GlobalVariable::ExternalLinkage;
1953193326Sed}
1954193326Sed
1955252723Sdim/// Replace the uses of a function that was declared with a non-proto type.
1956252723Sdim/// We want to silently drop extra arguments from call sites
1957252723Sdimstatic void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1958252723Sdim                                          llvm::Function *newFn) {
1959252723Sdim  // Fast path.
1960252723Sdim  if (old->use_empty()) return;
1961198092Srdivacky
1962252723Sdim  llvm::Type *newRetTy = newFn->getReturnType();
1963252723Sdim  SmallVector<llvm::Value*, 4> newArgs;
1964193326Sed
1965252723Sdim  for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1966252723Sdim         ui != ue; ) {
1967252723Sdim    llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1968252723Sdim    llvm::User *user = *use;
1969198092Srdivacky
1970252723Sdim    // Recognize and replace uses of bitcasts.  Most calls to
1971252723Sdim    // unprototyped functions will use bitcasts.
1972252723Sdim    if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1973252723Sdim      if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1974252723Sdim        replaceUsesOfNonProtoConstant(bitcast, newFn);
1975193326Sed      continue;
1976252723Sdim    }
1977193326Sed
1978252723Sdim    // Recognize calls to the function.
1979252723Sdim    llvm::CallSite callSite(user);
1980252723Sdim    if (!callSite) continue;
1981252723Sdim    if (!callSite.isCallee(use)) continue;
1982226890Sdim
1983252723Sdim    // If the return types don't match exactly, then we can't
1984252723Sdim    // transform this call unless it's dead.
1985252723Sdim    if (callSite->getType() != newRetTy && !callSite->use_empty())
1986252723Sdim      continue;
1987226890Sdim
1988252723Sdim    // Get the call site's attribute list.
1989252723Sdim    SmallVector<llvm::AttributeSet, 8> newAttrs;
1990252723Sdim    llvm::AttributeSet oldAttrs = callSite.getAttributes();
1991226890Sdim
1992252723Sdim    // Collect any return attributes from the call.
1993252723Sdim    if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1994252723Sdim      newAttrs.push_back(
1995252723Sdim        llvm::AttributeSet::get(newFn->getContext(),
1996252723Sdim                                oldAttrs.getRetAttributes()));
1997252723Sdim
1998252723Sdim    // If the function was passed too few arguments, don't transform.
1999252723Sdim    unsigned newNumArgs = newFn->arg_size();
2000252723Sdim    if (callSite.arg_size() < newNumArgs) continue;
2001252723Sdim
2002252723Sdim    // If extra arguments were passed, we silently drop them.
2003252723Sdim    // If any of the types mismatch, we don't transform.
2004252723Sdim    unsigned argNo = 0;
2005252723Sdim    bool dontTransform = false;
2006252723Sdim    for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2007252723Sdim           ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2008252723Sdim      if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2009252723Sdim        dontTransform = true;
2010193326Sed        break;
2011193326Sed      }
2012226890Sdim
2013226890Sdim      // Add any parameter attributes.
2014252723Sdim      if (oldAttrs.hasAttributes(argNo + 1))
2015252723Sdim        newAttrs.
2016252723Sdim          push_back(llvm::
2017252723Sdim                    AttributeSet::get(newFn->getContext(),
2018252723Sdim                                      oldAttrs.getParamAttributes(argNo + 1)));
2019193326Sed    }
2020252723Sdim    if (dontTransform)
2021193326Sed      continue;
2022198092Srdivacky
2023252723Sdim    if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2024252723Sdim      newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2025252723Sdim                                                 oldAttrs.getFnAttributes()));
2026226890Sdim
2027193326Sed    // Okay, we can transform this.  Create the new call instruction and copy
2028193326Sed    // over the required information.
2029252723Sdim    newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2030193326Sed
2031252723Sdim    llvm::CallSite newCall;
2032252723Sdim    if (callSite.isCall()) {
2033252723Sdim      newCall = llvm::CallInst::Create(newFn, newArgs, "",
2034252723Sdim                                       callSite.getInstruction());
2035252723Sdim    } else {
2036252723Sdim      llvm::InvokeInst *oldInvoke =
2037252723Sdim        cast<llvm::InvokeInst>(callSite.getInstruction());
2038252723Sdim      newCall = llvm::InvokeInst::Create(newFn,
2039252723Sdim                                         oldInvoke->getNormalDest(),
2040252723Sdim                                         oldInvoke->getUnwindDest(),
2041252723Sdim                                         newArgs, "",
2042252723Sdim                                         callSite.getInstruction());
2043252723Sdim    }
2044252723Sdim    newArgs.clear(); // for the next iteration
2045252723Sdim
2046252723Sdim    if (!newCall->getType()->isVoidTy())
2047252723Sdim      newCall->takeName(callSite.getInstruction());
2048252723Sdim    newCall.setAttributes(
2049252723Sdim                     llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2050252723Sdim    newCall.setCallingConv(callSite.getCallingConv());
2051252723Sdim
2052193326Sed    // Finally, remove the old call, replacing any uses with the new one.
2053252723Sdim    if (!callSite->use_empty())
2054252723Sdim      callSite->replaceAllUsesWith(newCall.getInstruction());
2055198092Srdivacky
2056206084Srdivacky    // Copy debug location attached to CI.
2057252723Sdim    if (!callSite->getDebugLoc().isUnknown())
2058252723Sdim      newCall->setDebugLoc(callSite->getDebugLoc());
2059252723Sdim    callSite->eraseFromParent();
2060193326Sed  }
2061193326Sed}
2062193326Sed
2063252723Sdim/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2064252723Sdim/// implement a function with no prototype, e.g. "int foo() {}".  If there are
2065252723Sdim/// existing call uses of the old function in the module, this adjusts them to
2066252723Sdim/// call the new function directly.
2067252723Sdim///
2068252723Sdim/// This is not just a cleanup: the always_inline pass requires direct calls to
2069252723Sdim/// functions to be able to inline them.  If there is a bitcast in the way, it
2070252723Sdim/// won't inline them.  Instcombine normally deletes these calls, but it isn't
2071252723Sdim/// run at -O0.
2072252723Sdimstatic void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2073252723Sdim                                                      llvm::Function *NewFn) {
2074252723Sdim  // If we're redefining a global as a function, don't transform it.
2075252723Sdim  if (!isa<llvm::Function>(Old)) return;
2076252723Sdim
2077252723Sdim  replaceUsesOfNonProtoConstant(Old, NewFn);
2078252723Sdim}
2079252723Sdim
2080235633Sdimvoid CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2081235633Sdim  TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2082235633Sdim  // If we have a definition, this might be a deferred decl. If the
2083235633Sdim  // instantiation is explicit, make sure we emit it at the end.
2084235633Sdim  if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2085235633Sdim    GetAddrOfGlobalVar(VD);
2086252723Sdim
2087252723Sdim  EmitTopLevelDecl(VD);
2088235633Sdim}
2089193326Sed
2090193326Sedvoid CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
2091193326Sed  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2092221345Sdim
2093221345Sdim  // Compute the function info and LLVM type.
2094235633Sdim  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2095235633Sdim  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2096221345Sdim
2097193326Sed  // Get or create the prototype for the function.
2098193326Sed  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
2099198092Srdivacky
2100193326Sed  // Strip off a bitcast if we got one back.
2101193326Sed  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2102193326Sed    assert(CE->getOpcode() == llvm::Instruction::BitCast);
2103193326Sed    Entry = CE->getOperand(0);
2104193326Sed  }
2105198092Srdivacky
2106263509Sdim  if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2107263509Sdim    getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2108263509Sdim    return;
2109263509Sdim  }
2110198092Srdivacky
2111193326Sed  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2112193326Sed    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2113198092Srdivacky
2114193326Sed    // If the types mismatch then we have to rewrite the definition.
2115193326Sed    assert(OldFn->isDeclaration() &&
2116193326Sed           "Shouldn't replace non-declaration");
2117193326Sed
2118193326Sed    // F is the Function* for the one with the wrong type, we must make a new
2119193326Sed    // Function* and update everything that used F (a declaration) with the new
2120193326Sed    // Function* (which will be a definition).
2121193326Sed    //
2122193326Sed    // This happens if there is a prototype for a function
2123193326Sed    // (e.g. "int f()") and then a definition of a different type
2124205408Srdivacky    // (e.g. "int f(int x)").  Move the old function aside so that it
2125205408Srdivacky    // doesn't interfere with GetAddrOfFunction.
2126226890Sdim    OldFn->setName(StringRef());
2127193326Sed    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2128198092Srdivacky
2129252723Sdim    // This might be an implementation of a function without a
2130252723Sdim    // prototype, in which case, try to do special replacement of
2131252723Sdim    // calls which match the new prototype.  The really key thing here
2132252723Sdim    // is that we also potentially drop arguments from the call site
2133252723Sdim    // so as to make a direct call, which makes the inliner happier
2134252723Sdim    // and suppresses a number of optimizer warnings (!) about
2135252723Sdim    // dropping arguments.
2136252723Sdim    if (!OldFn->use_empty()) {
2137193326Sed      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2138193326Sed      OldFn->removeDeadConstantUsers();
2139193326Sed    }
2140198092Srdivacky
2141193326Sed    // Replace uses of F with the Function we will endow with a body.
2142193326Sed    if (!Entry->use_empty()) {
2143198092Srdivacky      llvm::Constant *NewPtrForOldDecl =
2144193326Sed        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2145193326Sed      Entry->replaceAllUsesWith(NewPtrForOldDecl);
2146193326Sed    }
2147198092Srdivacky
2148193326Sed    // Ok, delete the old function now, which is dead.
2149193326Sed    OldFn->eraseFromParent();
2150198092Srdivacky
2151193326Sed    Entry = NewFn;
2152193326Sed  }
2153198092Srdivacky
2154218893Sdim  // We need to set linkage and visibility on the function before
2155218893Sdim  // generating code for it because various parts of IR generation
2156218893Sdim  // want to propagate this information down (e.g. to local static
2157218893Sdim  // declarations).
2158193326Sed  llvm::Function *Fn = cast<llvm::Function>(Entry);
2159263509Sdim  setFunctionLinkage(GD, Fn);
2160193326Sed
2161218893Sdim  // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2162218893Sdim  setGlobalVisibility(Fn, D);
2163218893Sdim
2164252723Sdim  MaybeHandleStaticInExternC(D, Fn);
2165252723Sdim
2166221345Sdim  CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2167193326Sed
2168193326Sed  SetFunctionDefinitionAttributes(D, Fn);
2169193326Sed  SetLLVMFunctionAttributesForDefinition(D, Fn);
2170198092Srdivacky
2171195341Sed  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2172193326Sed    AddGlobalCtor(Fn, CA->getPriority());
2173195341Sed  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2174193326Sed    AddGlobalDtor(Fn, DA->getPriority());
2175226890Sdim  if (D->hasAttr<AnnotateAttr>())
2176226890Sdim    AddGlobalAnnotations(D, Fn);
2177193326Sed}
2178193326Sed
2179205408Srdivackyvoid CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2180205408Srdivacky  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2181195341Sed  const AliasAttr *AA = D->getAttr<AliasAttr>();
2182193326Sed  assert(AA && "Not an alias?");
2183193326Sed
2184226890Sdim  StringRef MangledName = getMangledName(GD);
2185205408Srdivacky
2186205408Srdivacky  // If there is a definition in the module, then it wins over the alias.
2187205408Srdivacky  // This is dubious, but allow it to be safe.  Just ignore the alias.
2188205408Srdivacky  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2189205408Srdivacky  if (Entry && !Entry->isDeclaration())
2190205408Srdivacky    return;
2191205408Srdivacky
2192263509Sdim  Aliases.push_back(GD);
2193263509Sdim
2194226890Sdim  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2195198092Srdivacky
2196193326Sed  // Create a reference to the named value.  This ensures that it is emitted
2197193326Sed  // if a deferred decl.
2198193326Sed  llvm::Constant *Aliasee;
2199193326Sed  if (isa<llvm::FunctionType>(DeclTy))
2200245431Sdim    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2201218893Sdim                                      /*ForVTable=*/false);
2202193326Sed  else
2203205408Srdivacky    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2204193326Sed                                    llvm::PointerType::getUnqual(DeclTy), 0);
2205193326Sed
2206193326Sed  // Create the new alias itself, but don't set a name yet.
2207198092Srdivacky  llvm::GlobalValue *GA =
2208193326Sed    new llvm::GlobalAlias(Aliasee->getType(),
2209193326Sed                          llvm::Function::ExternalLinkage,
2210193326Sed                          "", Aliasee, &getModule());
2211198092Srdivacky
2212205408Srdivacky  if (Entry) {
2213205408Srdivacky    assert(Entry->isDeclaration());
2214198092Srdivacky
2215193326Sed    // If there is a declaration in the module, then we had an extern followed
2216193326Sed    // by the alias, as in:
2217193326Sed    //   extern int test6();
2218193326Sed    //   ...
2219193326Sed    //   int test6() __attribute__((alias("test7")));
2220193326Sed    //
2221193326Sed    // Remove it and replace uses of it with the alias.
2222205408Srdivacky    GA->takeName(Entry);
2223198092Srdivacky
2224193326Sed    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2225193326Sed                                                          Entry->getType()));
2226193326Sed    Entry->eraseFromParent();
2227205408Srdivacky  } else {
2228210299Sed    GA->setName(MangledName);
2229193326Sed  }
2230198092Srdivacky
2231193326Sed  // Set attributes which are particular to an alias; this is a
2232193326Sed  // specialization of the attributes which may be set on a global
2233193326Sed  // variable/function.
2234195341Sed  if (D->hasAttr<DLLExportAttr>()) {
2235193326Sed    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2236193326Sed      // The dllexport attribute is ignored for undefined symbols.
2237210299Sed      if (FD->hasBody())
2238193326Sed        GA->setLinkage(llvm::Function::DLLExportLinkage);
2239193326Sed    } else {
2240193326Sed      GA->setLinkage(llvm::Function::DLLExportLinkage);
2241193326Sed    }
2242198092Srdivacky  } else if (D->hasAttr<WeakAttr>() ||
2243204643Srdivacky             D->hasAttr<WeakRefAttr>() ||
2244221345Sdim             D->isWeakImported()) {
2245193326Sed    GA->setLinkage(llvm::Function::WeakAnyLinkage);
2246193326Sed  }
2247193326Sed
2248193326Sed  SetCommonAttributes(D, GA);
2249193326Sed}
2250193326Sed
2251224145Sdimllvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2252226890Sdim                                            ArrayRef<llvm::Type*> Tys) {
2253224145Sdim  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2254224145Sdim                                         Tys);
2255193326Sed}
2256193326Sed
2257198092Srdivackystatic llvm::StringMapEntry<llvm::Constant*> &
2258198092SrdivackyGetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2259198092Srdivacky                         const StringLiteral *Literal,
2260198092Srdivacky                         bool TargetIsLSB,
2261198092Srdivacky                         bool &IsUTF16,
2262198092Srdivacky                         unsigned &StringLength) {
2263226890Sdim  StringRef String = Literal->getString();
2264212904Sdim  unsigned NumBytes = String.size();
2265198092Srdivacky
2266198092Srdivacky  // Check for simple case.
2267198092Srdivacky  if (!Literal->containsNonAsciiOrNull()) {
2268198092Srdivacky    StringLength = NumBytes;
2269212904Sdim    return Map.GetOrCreateValue(String);
2270193326Sed  }
2271198092Srdivacky
2272235633Sdim  // Otherwise, convert the UTF8 literals into a string of shorts.
2273235633Sdim  IsUTF16 = true;
2274235633Sdim
2275235633Sdim  SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2276245431Sdim  const UTF8 *FromPtr = (const UTF8 *)String.data();
2277198092Srdivacky  UTF16 *ToPtr = &ToBuf[0];
2278198092Srdivacky
2279218893Sdim  (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2280218893Sdim                           &ToPtr, ToPtr + NumBytes,
2281218893Sdim                           strictConversion);
2282198092Srdivacky
2283198092Srdivacky  // ConvertUTF8toUTF16 returns the length in ToPtr.
2284198092Srdivacky  StringLength = ToPtr - &ToBuf[0];
2285198092Srdivacky
2286235633Sdim  // Add an explicit null.
2287235633Sdim  *ToPtr = 0;
2288235633Sdim  return Map.
2289235633Sdim    GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2290235633Sdim                               (StringLength + 1) * 2));
2291193326Sed}
2292193326Sed
2293223017Sdimstatic llvm::StringMapEntry<llvm::Constant*> &
2294223017SdimGetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2295235633Sdim                       const StringLiteral *Literal,
2296235633Sdim                       unsigned &StringLength) {
2297235633Sdim  StringRef String = Literal->getString();
2298235633Sdim  StringLength = String.size();
2299235633Sdim  return Map.GetOrCreateValue(String);
2300223017Sdim}
2301223017Sdim
2302198092Srdivackyllvm::Constant *
2303198092SrdivackyCodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2304193326Sed  unsigned StringLength = 0;
2305193326Sed  bool isUTF16 = false;
2306198092Srdivacky  llvm::StringMapEntry<llvm::Constant*> &Entry =
2307198092Srdivacky    GetConstantCFStringEntry(CFConstantStringMap, Literal,
2308245431Sdim                             getDataLayout().isLittleEndian(),
2309198092Srdivacky                             isUTF16, StringLength);
2310198092Srdivacky
2311193326Sed  if (llvm::Constant *C = Entry.getValue())
2312193326Sed    return C;
2313198092Srdivacky
2314235633Sdim  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2315193326Sed  llvm::Constant *Zeros[] = { Zero, Zero };
2316252723Sdim  llvm::Value *V;
2317252723Sdim
2318198092Srdivacky  // If we don't already have it, get __CFConstantStringClassReference.
2319193326Sed  if (!CFConstantStringClassRef) {
2320226890Sdim    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2321193326Sed    Ty = llvm::ArrayType::get(Ty, 0);
2322198092Srdivacky    llvm::Constant *GV = CreateRuntimeVariable(Ty,
2323198092Srdivacky                                           "__CFConstantStringClassReference");
2324193326Sed    // Decay array -> ptr
2325252723Sdim    V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2326252723Sdim    CFConstantStringClassRef = V;
2327193326Sed  }
2328252723Sdim  else
2329252723Sdim    V = CFConstantStringClassRef;
2330198092Srdivacky
2331193326Sed  QualType CFTy = getContext().getCFConstantStringType();
2332193326Sed
2333226890Sdim  llvm::StructType *STy =
2334193326Sed    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2335193326Sed
2336235633Sdim  llvm::Constant *Fields[4];
2337193326Sed
2338193326Sed  // Class pointer.
2339252723Sdim  Fields[0] = cast<llvm::ConstantExpr>(V);
2340198092Srdivacky
2341193326Sed  // Flags.
2342226890Sdim  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2343198092Srdivacky  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2344198092Srdivacky    llvm::ConstantInt::get(Ty, 0x07C8);
2345198092Srdivacky
2346193326Sed  // String pointer.
2347235633Sdim  llvm::Constant *C = 0;
2348235633Sdim  if (isUTF16) {
2349235633Sdim    ArrayRef<uint16_t> Arr =
2350252723Sdim      llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2351252723Sdim                                     const_cast<char *>(Entry.getKey().data())),
2352235633Sdim                                   Entry.getKey().size() / 2);
2353235633Sdim    C = llvm::ConstantDataArray::get(VMContext, Arr);
2354235633Sdim  } else {
2355235633Sdim    C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2356235633Sdim  }
2357193326Sed
2358198092Srdivacky  llvm::GlobalValue::LinkageTypes Linkage;
2359235633Sdim  if (isUTF16)
2360198092Srdivacky    // FIXME: why do utf strings get "_" labels instead of "L" labels?
2361198092Srdivacky    Linkage = llvm::GlobalValue::InternalLinkage;
2362235633Sdim  else
2363221345Sdim    // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2364221345Sdim    // when using private linkage. It is not clear if this is a bug in ld
2365221345Sdim    // or a reasonable new restriction.
2366221345Sdim    Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
2367198092Srdivacky
2368235633Sdim  // Note: -fwritable-strings doesn't make the backing store strings of
2369235633Sdim  // CFStrings writable. (See <rdar://problem/10657500>)
2370198092Srdivacky  llvm::GlobalVariable *GV =
2371235633Sdim    new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2372235633Sdim                             Linkage, C, ".str");
2373218893Sdim  GV->setUnnamedAddr(true);
2374252723Sdim  // Don't enforce the target's minimum global alignment, since the only use
2375252723Sdim  // of the string is via this class initializer.
2376193326Sed  if (isUTF16) {
2377203955Srdivacky    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2378203955Srdivacky    GV->setAlignment(Align.getQuantity());
2379221345Sdim  } else {
2380221345Sdim    CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2381221345Sdim    GV->setAlignment(Align.getQuantity());
2382193326Sed  }
2383235633Sdim
2384235633Sdim  // String.
2385226890Sdim  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2386198092Srdivacky
2387235633Sdim  if (isUTF16)
2388235633Sdim    // Cast the UTF16 string to the correct type.
2389235633Sdim    Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2390235633Sdim
2391193326Sed  // String length.
2392193326Sed  Ty = getTypes().ConvertType(getContext().LongTy);
2393198092Srdivacky  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2394198092Srdivacky
2395193326Sed  // The struct.
2396193326Sed  C = llvm::ConstantStruct::get(STy, Fields);
2397198092Srdivacky  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2398198092Srdivacky                                llvm::GlobalVariable::PrivateLinkage, C,
2399198092Srdivacky                                "_unnamed_cfstring_");
2400252723Sdim  if (const char *Sect = getTarget().getCFStringSection())
2401193326Sed    GV->setSection(Sect);
2402193326Sed  Entry.setValue(GV);
2403198092Srdivacky
2404193326Sed  return GV;
2405193326Sed}
2406193326Sed
2407226890Sdimstatic RecordDecl *
2408226890SdimCreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2409226890Sdim                 DeclContext *DC, IdentifierInfo *Id) {
2410226890Sdim  SourceLocation Loc;
2411235633Sdim  if (Ctx.getLangOpts().CPlusPlus)
2412226890Sdim    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2413226890Sdim  else
2414226890Sdim    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2415226890Sdim}
2416226890Sdim
2417207619Srdivackyllvm::Constant *
2418218893SdimCodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2419207619Srdivacky  unsigned StringLength = 0;
2420207619Srdivacky  llvm::StringMapEntry<llvm::Constant*> &Entry =
2421223017Sdim    GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2422207619Srdivacky
2423207619Srdivacky  if (llvm::Constant *C = Entry.getValue())
2424207619Srdivacky    return C;
2425207619Srdivacky
2426235633Sdim  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2427207619Srdivacky  llvm::Constant *Zeros[] = { Zero, Zero };
2428252723Sdim  llvm::Value *V;
2429207619Srdivacky  // If we don't already have it, get _NSConstantStringClassReference.
2430218893Sdim  if (!ConstantStringClassRef) {
2431235633Sdim    std::string StringClass(getLangOpts().ObjCConstantStringClass);
2432226890Sdim    llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2433218893Sdim    llvm::Constant *GV;
2434245431Sdim    if (LangOpts.ObjCRuntime.isNonFragile()) {
2435223017Sdim      std::string str =
2436223017Sdim        StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2437223017Sdim                            : "OBJC_CLASS_$_" + StringClass;
2438223017Sdim      GV = getObjCRuntime().GetClassGlobal(str);
2439223017Sdim      // Make sure the result is of the correct type.
2440226890Sdim      llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2441252723Sdim      V = llvm::ConstantExpr::getBitCast(GV, PTy);
2442252723Sdim      ConstantStringClassRef = V;
2443223017Sdim    } else {
2444223017Sdim      std::string str =
2445223017Sdim        StringClass.empty() ? "_NSConstantStringClassReference"
2446223017Sdim                            : "_" + StringClass + "ClassReference";
2447226890Sdim      llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2448223017Sdim      GV = CreateRuntimeVariable(PTy, str);
2449223017Sdim      // Decay array -> ptr
2450252723Sdim      V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2451252723Sdim      ConstantStringClassRef = V;
2452218893Sdim    }
2453207619Srdivacky  }
2454252723Sdim  else
2455252723Sdim    V = ConstantStringClassRef;
2456226890Sdim
2457226890Sdim  if (!NSConstantStringType) {
2458226890Sdim    // Construct the type for a constant NSString.
2459226890Sdim    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2460226890Sdim                                     Context.getTranslationUnitDecl(),
2461226890Sdim                                   &Context.Idents.get("__builtin_NSString"));
2462226890Sdim    D->startDefinition();
2463226890Sdim
2464226890Sdim    QualType FieldTypes[3];
2465226890Sdim
2466226890Sdim    // const int *isa;
2467226890Sdim    FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2468226890Sdim    // const char *str;
2469226890Sdim    FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2470226890Sdim    // unsigned int length;
2471226890Sdim    FieldTypes[2] = Context.UnsignedIntTy;
2472226890Sdim
2473226890Sdim    // Create fields
2474226890Sdim    for (unsigned i = 0; i < 3; ++i) {
2475226890Sdim      FieldDecl *Field = FieldDecl::Create(Context, D,
2476226890Sdim                                           SourceLocation(),
2477226890Sdim                                           SourceLocation(), 0,
2478226890Sdim                                           FieldTypes[i], /*TInfo=*/0,
2479226890Sdim                                           /*BitWidth=*/0,
2480226890Sdim                                           /*Mutable=*/false,
2481245431Sdim                                           ICIS_NoInit);
2482226890Sdim      Field->setAccess(AS_public);
2483226890Sdim      D->addDecl(Field);
2484226890Sdim    }
2485226890Sdim
2486226890Sdim    D->completeDefinition();
2487226890Sdim    QualType NSTy = Context.getTagDeclType(D);
2488226890Sdim    NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2489226890Sdim  }
2490207619Srdivacky
2491235633Sdim  llvm::Constant *Fields[3];
2492207619Srdivacky
2493207619Srdivacky  // Class pointer.
2494252723Sdim  Fields[0] = cast<llvm::ConstantExpr>(V);
2495207619Srdivacky
2496207619Srdivacky  // String pointer.
2497235633Sdim  llvm::Constant *C =
2498235633Sdim    llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2499207619Srdivacky
2500207619Srdivacky  llvm::GlobalValue::LinkageTypes Linkage;
2501207619Srdivacky  bool isConstant;
2502223017Sdim  Linkage = llvm::GlobalValue::PrivateLinkage;
2503235633Sdim  isConstant = !LangOpts.WritableStrings;
2504207619Srdivacky
2505207619Srdivacky  llvm::GlobalVariable *GV =
2506207619Srdivacky  new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2507207619Srdivacky                           ".str");
2508218893Sdim  GV->setUnnamedAddr(true);
2509252723Sdim  // Don't enforce the target's minimum global alignment, since the only use
2510252723Sdim  // of the string is via this class initializer.
2511223017Sdim  CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2512223017Sdim  GV->setAlignment(Align.getQuantity());
2513226890Sdim  Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2514207619Srdivacky
2515207619Srdivacky  // String length.
2516226890Sdim  llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2517207619Srdivacky  Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2518207619Srdivacky
2519207619Srdivacky  // The struct.
2520226890Sdim  C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2521207619Srdivacky  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2522207619Srdivacky                                llvm::GlobalVariable::PrivateLinkage, C,
2523207619Srdivacky                                "_unnamed_nsstring_");
2524207619Srdivacky  // FIXME. Fix section.
2525207619Srdivacky  if (const char *Sect =
2526245431Sdim        LangOpts.ObjCRuntime.isNonFragile()
2527252723Sdim          ? getTarget().getNSStringNonFragileABISection()
2528252723Sdim          : getTarget().getNSStringSection())
2529207619Srdivacky    GV->setSection(Sect);
2530207619Srdivacky  Entry.setValue(GV);
2531207619Srdivacky
2532207619Srdivacky  return GV;
2533207619Srdivacky}
2534207619Srdivacky
2535226890SdimQualType CodeGenModule::getObjCFastEnumerationStateType() {
2536226890Sdim  if (ObjCFastEnumerationStateType.isNull()) {
2537226890Sdim    RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2538226890Sdim                                     Context.getTranslationUnitDecl(),
2539226890Sdim                      &Context.Idents.get("__objcFastEnumerationState"));
2540226890Sdim    D->startDefinition();
2541226890Sdim
2542226890Sdim    QualType FieldTypes[] = {
2543226890Sdim      Context.UnsignedLongTy,
2544226890Sdim      Context.getPointerType(Context.getObjCIdType()),
2545226890Sdim      Context.getPointerType(Context.UnsignedLongTy),
2546226890Sdim      Context.getConstantArrayType(Context.UnsignedLongTy,
2547226890Sdim                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2548226890Sdim    };
2549226890Sdim
2550226890Sdim    for (size_t i = 0; i < 4; ++i) {
2551226890Sdim      FieldDecl *Field = FieldDecl::Create(Context,
2552226890Sdim                                           D,
2553226890Sdim                                           SourceLocation(),
2554226890Sdim                                           SourceLocation(), 0,
2555226890Sdim                                           FieldTypes[i], /*TInfo=*/0,
2556226890Sdim                                           /*BitWidth=*/0,
2557226890Sdim                                           /*Mutable=*/false,
2558245431Sdim                                           ICIS_NoInit);
2559226890Sdim      Field->setAccess(AS_public);
2560226890Sdim      D->addDecl(Field);
2561226890Sdim    }
2562226890Sdim
2563226890Sdim    D->completeDefinition();
2564226890Sdim    ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2565226890Sdim  }
2566226890Sdim
2567226890Sdim  return ObjCFastEnumerationStateType;
2568226890Sdim}
2569226890Sdim
2570235633Sdimllvm::Constant *
2571235633SdimCodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2572235633Sdim  assert(!E->getType()->isPointerType() && "Strings are always arrays");
2573235633Sdim
2574235633Sdim  // Don't emit it as the address of the string, emit the string data itself
2575235633Sdim  // as an inline array.
2576235633Sdim  if (E->getCharByteWidth() == 1) {
2577235633Sdim    SmallString<64> Str(E->getString());
2578198092Srdivacky
2579235633Sdim    // Resize the string to the right size, which is indicated by its type.
2580235633Sdim    const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2581235633Sdim    Str.resize(CAT->getSize().getZExtValue());
2582235633Sdim    return llvm::ConstantDataArray::getString(VMContext, Str, false);
2583226890Sdim  }
2584235633Sdim
2585235633Sdim  llvm::ArrayType *AType =
2586235633Sdim    cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2587235633Sdim  llvm::Type *ElemTy = AType->getElementType();
2588235633Sdim  unsigned NumElements = AType->getNumElements();
2589198092Srdivacky
2590235633Sdim  // Wide strings have either 2-byte or 4-byte elements.
2591235633Sdim  if (ElemTy->getPrimitiveSizeInBits() == 16) {
2592235633Sdim    SmallVector<uint16_t, 32> Elements;
2593235633Sdim    Elements.reserve(NumElements);
2594198092Srdivacky
2595235633Sdim    for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2596235633Sdim      Elements.push_back(E->getCodeUnit(i));
2597235633Sdim    Elements.resize(NumElements);
2598235633Sdim    return llvm::ConstantDataArray::get(VMContext, Elements);
2599235633Sdim  }
2600235633Sdim
2601235633Sdim  assert(ElemTy->getPrimitiveSizeInBits() == 32);
2602235633Sdim  SmallVector<uint32_t, 32> Elements;
2603235633Sdim  Elements.reserve(NumElements);
2604235633Sdim
2605235633Sdim  for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2606235633Sdim    Elements.push_back(E->getCodeUnit(i));
2607235633Sdim  Elements.resize(NumElements);
2608235633Sdim  return llvm::ConstantDataArray::get(VMContext, Elements);
2609193326Sed}
2610193326Sed
2611193326Sed/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2612193326Sed/// constant array for the given string literal.
2613193326Sedllvm::Constant *
2614193326SedCodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2615252723Sdim  CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2616235633Sdim  if (S->isAscii() || S->isUTF8()) {
2617235633Sdim    SmallString<64> Str(S->getString());
2618235633Sdim
2619235633Sdim    // Resize the string to the right size, which is indicated by its type.
2620235633Sdim    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2621235633Sdim    Str.resize(CAT->getSize().getZExtValue());
2622235633Sdim    return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2623199482Srdivacky  }
2624235633Sdim
2625235633Sdim  // FIXME: the following does not memoize wide strings.
2626235633Sdim  llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2627235633Sdim  llvm::GlobalVariable *GV =
2628235633Sdim    new llvm::GlobalVariable(getModule(),C->getType(),
2629235633Sdim                             !LangOpts.WritableStrings,
2630235633Sdim                             llvm::GlobalValue::PrivateLinkage,
2631235633Sdim                             C,".str");
2632235633Sdim
2633235633Sdim  GV->setAlignment(Align.getQuantity());
2634235633Sdim  GV->setUnnamedAddr(true);
2635235633Sdim  return GV;
2636193326Sed}
2637193326Sed
2638193326Sed/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2639193326Sed/// array for the given ObjCEncodeExpr node.
2640193326Sedllvm::Constant *
2641193326SedCodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2642193326Sed  std::string Str;
2643193326Sed  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2644193326Sed
2645193326Sed  return GetAddrOfConstantCString(Str);
2646193326Sed}
2647193326Sed
2648193326Sed
2649193326Sed/// GenerateWritableString -- Creates storage for a string literal.
2650226890Sdimstatic llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2651193326Sed                                             bool constant,
2652193326Sed                                             CodeGenModule &CGM,
2653226890Sdim                                             const char *GlobalName,
2654226890Sdim                                             unsigned Alignment) {
2655193326Sed  // Create Constant for this string literal. Don't add a '\0'.
2656198092Srdivacky  llvm::Constant *C =
2657235633Sdim      llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2658198092Srdivacky
2659263509Sdim  // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
2660263509Sdim  unsigned AddrSpace = 0;
2661263509Sdim  if (CGM.getLangOpts().OpenCL)
2662263509Sdim    AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2663263509Sdim
2664193326Sed  // Create a global variable for this string
2665263509Sdim  llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2666263509Sdim      CGM.getModule(), C->getType(), constant,
2667263509Sdim      llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2668263509Sdim      llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2669226890Sdim  GV->setAlignment(Alignment);
2670218893Sdim  GV->setUnnamedAddr(true);
2671218893Sdim  return GV;
2672193326Sed}
2673193326Sed
2674193326Sed/// GetAddrOfConstantString - Returns a pointer to a character array
2675193326Sed/// containing the literal. This contents are exactly that of the
2676193326Sed/// given string, i.e. it will not be null terminated automatically;
2677193326Sed/// see GetAddrOfConstantCString. Note that whether the result is
2678193326Sed/// actually a pointer to an LLVM constant depends on
2679193326Sed/// Feature.WriteableStrings.
2680193326Sed///
2681193326Sed/// The result has pointer to array type.
2682226890Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2683226890Sdim                                                       const char *GlobalName,
2684226890Sdim                                                       unsigned Alignment) {
2685193326Sed  // Get the default prefix if a name wasn't specified.
2686193326Sed  if (!GlobalName)
2687198092Srdivacky    GlobalName = ".str";
2688193326Sed
2689252723Sdim  if (Alignment == 0)
2690252723Sdim    Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2691252723Sdim      .getQuantity();
2692252723Sdim
2693193326Sed  // Don't share any string literals if strings aren't constant.
2694235633Sdim  if (LangOpts.WritableStrings)
2695226890Sdim    return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2696193326Sed
2697226890Sdim  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2698221345Sdim    ConstantStringMap.GetOrCreateValue(Str);
2699198092Srdivacky
2700226890Sdim  if (llvm::GlobalVariable *GV = Entry.getValue()) {
2701226890Sdim    if (Alignment > GV->getAlignment()) {
2702226890Sdim      GV->setAlignment(Alignment);
2703226890Sdim    }
2704226890Sdim    return GV;
2705226890Sdim  }
2706193326Sed
2707193326Sed  // Create a global variable for this.
2708235633Sdim  llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2709235633Sdim                                                   Alignment);
2710226890Sdim  Entry.setValue(GV);
2711226890Sdim  return GV;
2712193326Sed}
2713193326Sed
2714193326Sed/// GetAddrOfConstantCString - Returns a pointer to a character
2715221345Sdim/// array containing the literal and a terminating '\0'
2716193326Sed/// character. The result has pointer to array type.
2717221345Sdimllvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2718226890Sdim                                                        const char *GlobalName,
2719226890Sdim                                                        unsigned Alignment) {
2720226890Sdim  StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2721226890Sdim  return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2722193326Sed}
2723193326Sed
2724263509Sdimllvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2725263509Sdim    const MaterializeTemporaryExpr *E, const Expr *Init) {
2726263509Sdim  assert((E->getStorageDuration() == SD_Static ||
2727263509Sdim          E->getStorageDuration() == SD_Thread) && "not a global temporary");
2728263509Sdim  const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2729263509Sdim
2730263509Sdim  // If we're not materializing a subobject of the temporary, keep the
2731263509Sdim  // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2732263509Sdim  QualType MaterializedType = Init->getType();
2733263509Sdim  if (Init == E->GetTemporaryExpr())
2734263509Sdim    MaterializedType = E->getType();
2735263509Sdim
2736263509Sdim  llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2737263509Sdim  if (Slot)
2738263509Sdim    return Slot;
2739263509Sdim
2740263509Sdim  // FIXME: If an externally-visible declaration extends multiple temporaries,
2741263509Sdim  // we need to give each temporary the same name in every translation unit (and
2742263509Sdim  // we also need to make the temporaries externally-visible).
2743263509Sdim  SmallString<256> Name;
2744263509Sdim  llvm::raw_svector_ostream Out(Name);
2745263509Sdim  getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2746263509Sdim  Out.flush();
2747263509Sdim
2748263509Sdim  APValue *Value = 0;
2749263509Sdim  if (E->getStorageDuration() == SD_Static) {
2750263509Sdim    // We might have a cached constant initializer for this temporary. Note
2751263509Sdim    // that this might have a different value from the value computed by
2752263509Sdim    // evaluating the initializer if the surrounding constant expression
2753263509Sdim    // modifies the temporary.
2754263509Sdim    Value = getContext().getMaterializedTemporaryValue(E, false);
2755263509Sdim    if (Value && Value->isUninit())
2756263509Sdim      Value = 0;
2757263509Sdim  }
2758263509Sdim
2759263509Sdim  // Try evaluating it now, it might have a constant initializer.
2760263509Sdim  Expr::EvalResult EvalResult;
2761263509Sdim  if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2762263509Sdim      !EvalResult.hasSideEffects())
2763263509Sdim    Value = &EvalResult.Val;
2764263509Sdim
2765263509Sdim  llvm::Constant *InitialValue = 0;
2766263509Sdim  bool Constant = false;
2767263509Sdim  llvm::Type *Type;
2768263509Sdim  if (Value) {
2769263509Sdim    // The temporary has a constant initializer, use it.
2770263509Sdim    InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2771263509Sdim    Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2772263509Sdim    Type = InitialValue->getType();
2773263509Sdim  } else {
2774263509Sdim    // No initializer, the initialization will be provided when we
2775263509Sdim    // initialize the declaration which performed lifetime extension.
2776263509Sdim    Type = getTypes().ConvertTypeForMem(MaterializedType);
2777263509Sdim  }
2778263509Sdim
2779263509Sdim  // Create a global variable for this lifetime-extended temporary.
2780263509Sdim  llvm::GlobalVariable *GV =
2781263509Sdim    new llvm::GlobalVariable(getModule(), Type, Constant,
2782263509Sdim                             llvm::GlobalValue::PrivateLinkage,
2783263509Sdim                             InitialValue, Name.c_str());
2784263509Sdim  GV->setAlignment(
2785263509Sdim      getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2786263509Sdim  if (VD->getTLSKind())
2787263509Sdim    setTLSMode(GV, *VD);
2788263509Sdim  Slot = GV;
2789263509Sdim  return GV;
2790263509Sdim}
2791263509Sdim
2792193326Sed/// EmitObjCPropertyImplementations - Emit information for synthesized
2793193326Sed/// properties for an implementation.
2794198092Srdivackyvoid CodeGenModule::EmitObjCPropertyImplementations(const
2795193326Sed                                                    ObjCImplementationDecl *D) {
2796198092Srdivacky  for (ObjCImplementationDecl::propimpl_iterator
2797195341Sed         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2798193326Sed    ObjCPropertyImplDecl *PID = *i;
2799198092Srdivacky
2800193326Sed    // Dynamic is just for type-checking.
2801193326Sed    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2802193326Sed      ObjCPropertyDecl *PD = PID->getPropertyDecl();
2803193326Sed
2804193326Sed      // Determine which methods need to be implemented, some may have
2805245431Sdim      // been overridden. Note that ::isPropertyAccessor is not the method
2806193326Sed      // we want, that just indicates if the decl came from a
2807193326Sed      // property. What we want to know is if the method is defined in
2808193326Sed      // this implementation.
2809195341Sed      if (!D->getInstanceMethod(PD->getGetterName()))
2810193326Sed        CodeGenFunction(*this).GenerateObjCGetter(
2811193326Sed                                 const_cast<ObjCImplementationDecl *>(D), PID);
2812193326Sed      if (!PD->isReadOnly() &&
2813195341Sed          !D->getInstanceMethod(PD->getSetterName()))
2814193326Sed        CodeGenFunction(*this).GenerateObjCSetter(
2815193326Sed                                 const_cast<ObjCImplementationDecl *>(D), PID);
2816193326Sed    }
2817193326Sed  }
2818193326Sed}
2819193326Sed
2820221345Sdimstatic bool needsDestructMethod(ObjCImplementationDecl *impl) {
2821226890Sdim  const ObjCInterfaceDecl *iface = impl->getClassInterface();
2822226890Sdim  for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2823221345Sdim       ivar; ivar = ivar->getNextIvar())
2824221345Sdim    if (ivar->getType().isDestructedType())
2825221345Sdim      return true;
2826221345Sdim
2827221345Sdim  return false;
2828221345Sdim}
2829221345Sdim
2830207619Srdivacky/// EmitObjCIvarInitializations - Emit information for ivar initialization
2831207619Srdivacky/// for an implementation.
2832207619Srdivackyvoid CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2833221345Sdim  // We might need a .cxx_destruct even if we don't have any ivar initializers.
2834221345Sdim  if (needsDestructMethod(D)) {
2835221345Sdim    IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2836221345Sdim    Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2837221345Sdim    ObjCMethodDecl *DTORMethod =
2838221345Sdim      ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2839226890Sdim                             cxxSelector, getContext().VoidTy, 0, D,
2840226890Sdim                             /*isInstance=*/true, /*isVariadic=*/false,
2841245431Sdim                          /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2842226890Sdim                             /*isDefined=*/false, ObjCMethodDecl::Required);
2843221345Sdim    D->addInstanceMethod(DTORMethod);
2844221345Sdim    CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2845245431Sdim    D->setHasDestructors(true);
2846221345Sdim  }
2847221345Sdim
2848221345Sdim  // If the implementation doesn't have any ivar initializers, we don't need
2849221345Sdim  // a .cxx_construct.
2850221345Sdim  if (D->getNumIvarInitializers() == 0)
2851207619Srdivacky    return;
2852221345Sdim
2853221345Sdim  IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2854207619Srdivacky  Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2855207619Srdivacky  // The constructor returns 'self'.
2856207619Srdivacky  ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2857207619Srdivacky                                                D->getLocation(),
2858226890Sdim                                                D->getLocation(),
2859226890Sdim                                                cxxSelector,
2860207619Srdivacky                                                getContext().getObjCIdType(), 0,
2861226890Sdim                                                D, /*isInstance=*/true,
2862226890Sdim                                                /*isVariadic=*/false,
2863245431Sdim                                                /*isPropertyAccessor=*/true,
2864226890Sdim                                                /*isImplicitlyDeclared=*/true,
2865226890Sdim                                                /*isDefined=*/false,
2866207619Srdivacky                                                ObjCMethodDecl::Required);
2867207619Srdivacky  D->addInstanceMethod(CTORMethod);
2868207619Srdivacky  CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2869245431Sdim  D->setHasNonZeroConstructors(true);
2870207619Srdivacky}
2871207619Srdivacky
2872193326Sed/// EmitNamespace - Emit all declarations in a namespace.
2873193326Sedvoid CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2874195341Sed  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2875263509Sdim       I != E; ++I) {
2876263509Sdim    if (const VarDecl *VD = dyn_cast<VarDecl>(*I))
2877263509Sdim      if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2878263509Sdim          VD->getTemplateSpecializationKind() != TSK_Undeclared)
2879263509Sdim        continue;
2880193326Sed    EmitTopLevelDecl(*I);
2881263509Sdim  }
2882193326Sed}
2883193326Sed
2884193326Sed// EmitLinkageSpec - Emit all declarations in a linkage spec.
2885193326Sedvoid CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2886198092Srdivacky  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2887198092Srdivacky      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2888193326Sed    ErrorUnsupported(LSD, "linkage spec");
2889193326Sed    return;
2890193326Sed  }
2891193326Sed
2892195341Sed  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2893245431Sdim       I != E; ++I) {
2894245431Sdim    // Meta-data for ObjC class includes references to implemented methods.
2895245431Sdim    // Generate class's method definitions first.
2896245431Sdim    if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2897245431Sdim      for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2898245431Sdim           MEnd = OID->meth_end();
2899245431Sdim           M != MEnd; ++M)
2900245431Sdim        EmitTopLevelDecl(*M);
2901245431Sdim    }
2902193326Sed    EmitTopLevelDecl(*I);
2903245431Sdim  }
2904193326Sed}
2905193326Sed
2906193326Sed/// EmitTopLevelDecl - Emit code for a single top level declaration.
2907193326Sedvoid CodeGenModule::EmitTopLevelDecl(Decl *D) {
2908195341Sed  // Ignore dependent declarations.
2909195341Sed  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2910195341Sed    return;
2911198092Srdivacky
2912193326Sed  switch (D->getKind()) {
2913198092Srdivacky  case Decl::CXXConversion:
2914193326Sed  case Decl::CXXMethod:
2915193326Sed  case Decl::Function:
2916195341Sed    // Skip function templates
2917221345Sdim    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2918221345Sdim        cast<FunctionDecl>(D)->isLateTemplateParsed())
2919195341Sed      return;
2920198092Srdivacky
2921198092Srdivacky    EmitGlobal(cast<FunctionDecl>(D));
2922198092Srdivacky    break;
2923263509Sdim
2924193326Sed  case Decl::Var:
2925263509Sdim    // Skip variable templates
2926263509Sdim    if (cast<VarDecl>(D)->getDescribedVarTemplate())
2927263509Sdim      return;
2928263509Sdim  case Decl::VarTemplateSpecialization:
2929198092Srdivacky    EmitGlobal(cast<VarDecl>(D));
2930193326Sed    break;
2931193326Sed
2932221345Sdim  // Indirect fields from global anonymous structs and unions can be
2933221345Sdim  // ignored; only the actual variable requires IR gen support.
2934221345Sdim  case Decl::IndirectField:
2935221345Sdim    break;
2936221345Sdim
2937193326Sed  // C++ Decls
2938193326Sed  case Decl::Namespace:
2939193326Sed    EmitNamespace(cast<NamespaceDecl>(D));
2940193326Sed    break;
2941194613Sed    // No code generation needed.
2942199482Srdivacky  case Decl::UsingShadow:
2943194613Sed  case Decl::Using:
2944195341Sed  case Decl::ClassTemplate:
2945263509Sdim  case Decl::VarTemplate:
2946263509Sdim  case Decl::VarTemplatePartialSpecialization:
2947195341Sed  case Decl::FunctionTemplate:
2948223017Sdim  case Decl::TypeAliasTemplate:
2949223017Sdim  case Decl::Block:
2950252723Sdim  case Decl::Empty:
2951194613Sed    break;
2952263509Sdim  case Decl::NamespaceAlias:
2953263509Sdim    if (CGDebugInfo *DI = getModuleDebugInfo())
2954263509Sdim        DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2955263509Sdim    return;
2956252723Sdim  case Decl::UsingDirective: // using namespace X; [C++]
2957252723Sdim    if (CGDebugInfo *DI = getModuleDebugInfo())
2958252723Sdim      DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2959252723Sdim    return;
2960193326Sed  case Decl::CXXConstructor:
2961199990Srdivacky    // Skip function templates
2962221345Sdim    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2963221345Sdim        cast<FunctionDecl>(D)->isLateTemplateParsed())
2964199990Srdivacky      return;
2965199990Srdivacky
2966263509Sdim    getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2967193326Sed    break;
2968193326Sed  case Decl::CXXDestructor:
2969221345Sdim    if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2970221345Sdim      return;
2971263509Sdim    getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2972193326Sed    break;
2973194179Sed
2974194179Sed  case Decl::StaticAssert:
2975194179Sed    // Nothing to do.
2976194179Sed    break;
2977194179Sed
2978193326Sed  // Objective-C Decls
2979198092Srdivacky
2980193326Sed  // Forward declarations, no (immediate) code generation.
2981193326Sed  case Decl::ObjCInterface:
2982245431Sdim  case Decl::ObjCCategory:
2983193326Sed    break;
2984193326Sed
2985235633Sdim  case Decl::ObjCProtocol: {
2986235633Sdim    ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2987235633Sdim    if (Proto->isThisDeclarationADefinition())
2988235633Sdim      ObjCRuntime->GenerateProtocol(Proto);
2989193326Sed    break;
2990235633Sdim  }
2991235633Sdim
2992193326Sed  case Decl::ObjCCategoryImpl:
2993193326Sed    // Categories have properties but don't support synthesize so we
2994193326Sed    // can ignore them here.
2995226890Sdim    ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2996193326Sed    break;
2997193326Sed
2998193326Sed  case Decl::ObjCImplementation: {
2999193326Sed    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
3000193326Sed    EmitObjCPropertyImplementations(OMD);
3001207619Srdivacky    EmitObjCIvarInitializations(OMD);
3002226890Sdim    ObjCRuntime->GenerateClass(OMD);
3003235633Sdim    // Emit global variable debug information.
3004235633Sdim    if (CGDebugInfo *DI = getModuleDebugInfo())
3005252723Sdim      if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3006252723Sdim        DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3007252723Sdim            OMD->getClassInterface()), OMD->getLocation());
3008193326Sed    break;
3009198092Srdivacky  }
3010193326Sed  case Decl::ObjCMethod: {
3011193326Sed    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
3012193326Sed    // If this is not a prototype, emit the body.
3013195341Sed    if (OMD->getBody())
3014193326Sed      CodeGenFunction(*this).GenerateObjCMethod(OMD);
3015193326Sed    break;
3016193326Sed  }
3017198092Srdivacky  case Decl::ObjCCompatibleAlias:
3018235633Sdim    ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3019193326Sed    break;
3020193326Sed
3021193326Sed  case Decl::LinkageSpec:
3022193326Sed    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3023193326Sed    break;
3024193326Sed
3025193326Sed  case Decl::FileScopeAsm: {
3026193326Sed    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
3027226890Sdim    StringRef AsmString = AD->getAsmString()->getString();
3028198092Srdivacky
3029193326Sed    const std::string &S = getModule().getModuleInlineAsm();
3030193326Sed    if (S.empty())
3031193326Sed      getModule().setModuleInlineAsm(AsmString);
3032245431Sdim    else if (S.end()[-1] == '\n')
3033226890Sdim      getModule().setModuleInlineAsm(S + AsmString.str());
3034193326Sed    else
3035200583Srdivacky      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
3036193326Sed    break;
3037193326Sed  }
3038198092Srdivacky
3039252723Sdim  case Decl::Import: {
3040252723Sdim    ImportDecl *Import = cast<ImportDecl>(D);
3041252723Sdim
3042252723Sdim    // Ignore import declarations that come from imported modules.
3043252723Sdim    if (clang::Module *Owner = Import->getOwningModule()) {
3044252723Sdim      if (getLangOpts().CurrentModule.empty() ||
3045252723Sdim          Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3046252723Sdim        break;
3047252723Sdim    }
3048252723Sdim
3049252723Sdim    ImportedModules.insert(Import->getImportedModule());
3050252723Sdim    break;
3051252723Sdim }
3052252723Sdim
3053198092Srdivacky  default:
3054193326Sed    // Make sure we handled everything we should, every other kind is a
3055193326Sed    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3056193326Sed    // function. Need to recode Decl::Kind to do that easily.
3057193326Sed    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3058193326Sed  }
3059193326Sed}
3060210299Sed
3061210299Sed/// Turns the given pointer into a constant.
3062210299Sedstatic llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3063210299Sed                                          const void *Ptr) {
3064210299Sed  uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3065226890Sdim  llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3066210299Sed  return llvm::ConstantInt::get(i64, PtrInt);
3067210299Sed}
3068210299Sed
3069210299Sedstatic void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3070210299Sed                                   llvm::NamedMDNode *&GlobalMetadata,
3071210299Sed                                   GlobalDecl D,
3072210299Sed                                   llvm::GlobalValue *Addr) {
3073210299Sed  if (!GlobalMetadata)
3074210299Sed    GlobalMetadata =
3075210299Sed      CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3076210299Sed
3077210299Sed  // TODO: should we report variant information for ctors/dtors?
3078210299Sed  llvm::Value *Ops[] = {
3079210299Sed    Addr,
3080210299Sed    GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3081210299Sed  };
3082221345Sdim  GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3083210299Sed}
3084210299Sed
3085252723Sdim/// For each function which is declared within an extern "C" region and marked
3086252723Sdim/// as 'used', but has internal linkage, create an alias from the unmangled
3087252723Sdim/// name to the mangled name if possible. People expect to be able to refer
3088252723Sdim/// to such functions with an unmangled name from inline assembly within the
3089252723Sdim/// same translation unit.
3090252723Sdimvoid CodeGenModule::EmitStaticExternCAliases() {
3091252723Sdim  for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3092252723Sdim                                  E = StaticExternCValues.end();
3093252723Sdim       I != E; ++I) {
3094252723Sdim    IdentifierInfo *Name = I->first;
3095252723Sdim    llvm::GlobalValue *Val = I->second;
3096252723Sdim    if (Val && !getModule().getNamedValue(Name->getName()))
3097252723Sdim      AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
3098252723Sdim                                          Name->getName(), Val, &getModule()));
3099252723Sdim  }
3100252723Sdim}
3101252723Sdim
3102210299Sed/// Emits metadata nodes associating all the global values in the
3103210299Sed/// current module with the Decls they came from.  This is useful for
3104210299Sed/// projects using IR gen as a subroutine.
3105210299Sed///
3106210299Sed/// Since there's currently no way to associate an MDNode directly
3107210299Sed/// with an llvm::GlobalValue, we create a global named metadata
3108210299Sed/// with the name 'clang.global.decl.ptrs'.
3109210299Sedvoid CodeGenModule::EmitDeclMetadata() {
3110210299Sed  llvm::NamedMDNode *GlobalMetadata = 0;
3111210299Sed
3112210299Sed  // StaticLocalDeclMap
3113226890Sdim  for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3114210299Sed         I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3115210299Sed       I != E; ++I) {
3116210299Sed    llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3117210299Sed    EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3118210299Sed  }
3119210299Sed}
3120210299Sed
3121210299Sed/// Emits metadata nodes for all the local variables in the current
3122210299Sed/// function.
3123210299Sedvoid CodeGenFunction::EmitDeclMetadata() {
3124210299Sed  if (LocalDeclMap.empty()) return;
3125210299Sed
3126210299Sed  llvm::LLVMContext &Context = getLLVMContext();
3127210299Sed
3128210299Sed  // Find the unique metadata ID for this name.
3129210299Sed  unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3130210299Sed
3131210299Sed  llvm::NamedMDNode *GlobalMetadata = 0;
3132210299Sed
3133210299Sed  for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3134210299Sed         I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3135210299Sed    const Decl *D = I->first;
3136210299Sed    llvm::Value *Addr = I->second;
3137210299Sed
3138210299Sed    if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3139210299Sed      llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3140221345Sdim      Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3141210299Sed    } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3142210299Sed      GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3143210299Sed      EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3144210299Sed    }
3145210299Sed  }
3146210299Sed}
3147212904Sdim
3148263509Sdimvoid CodeGenModule::EmitVersionIdentMetadata() {
3149263509Sdim  llvm::NamedMDNode *IdentMetadata =
3150263509Sdim    TheModule.getOrInsertNamedMetadata("llvm.ident");
3151263509Sdim  std::string Version = getClangFullVersion();
3152263509Sdim  llvm::LLVMContext &Ctx = TheModule.getContext();
3153263509Sdim
3154263509Sdim  llvm::Value *IdentNode[] = {
3155263509Sdim    llvm::MDString::get(Ctx, Version)
3156263509Sdim  };
3157263509Sdim  IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3158263509Sdim}
3159263509Sdim
3160223017Sdimvoid CodeGenModule::EmitCoverageFile() {
3161223017Sdim  if (!getCodeGenOpts().CoverageFile.empty()) {
3162223017Sdim    if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3163223017Sdim      llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3164223017Sdim      llvm::LLVMContext &Ctx = TheModule.getContext();
3165223017Sdim      llvm::MDString *CoverageFile =
3166223017Sdim          llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3167223017Sdim      for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3168223017Sdim        llvm::MDNode *CU = CUNode->getOperand(i);
3169223017Sdim        llvm::Value *node[] = { CoverageFile, CU };
3170223017Sdim        llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3171223017Sdim        GCov->addOperand(N);
3172223017Sdim      }
3173223017Sdim    }
3174223017Sdim  }
3175223017Sdim}
3176245431Sdim
3177245431Sdimllvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3178245431Sdim                                                     QualType GuidType) {
3179245431Sdim  // Sema has checked that all uuid strings are of the form
3180245431Sdim  // "12345678-1234-1234-1234-1234567890ab".
3181245431Sdim  assert(Uuid.size() == 36);
3182263509Sdim  for (unsigned i = 0; i < 36; ++i) {
3183263509Sdim    if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3184263509Sdim    else                                         assert(isHexDigit(Uuid[i]));
3185245431Sdim  }
3186245431Sdim
3187263509Sdim  const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3188245431Sdim
3189263509Sdim  llvm::Constant *Field3[8];
3190263509Sdim  for (unsigned Idx = 0; Idx < 8; ++Idx)
3191263509Sdim    Field3[Idx] = llvm::ConstantInt::get(
3192263509Sdim        Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3193263509Sdim
3194263509Sdim  llvm::Constant *Fields[4] = {
3195263509Sdim    llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3196263509Sdim    llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3197263509Sdim    llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3198263509Sdim    llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3199263509Sdim  };
3200263509Sdim
3201263509Sdim  return llvm::ConstantStruct::getAnon(Fields);
3202245431Sdim}
3203