CodeGenModule.cpp revision 8e51a1f5da6ef4a1a168d14116c6eed3a578a263
1//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
15#include "CGDebugInfo.h"
16#include "CodeGenFunction.h"
17#include "CGCall.h"
18#include "CGObjCRuntime.h"
19#include "Mangle.h"
20#include "TargetInfo.h"
21#include "clang/CodeGen/CodeGenOptions.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/Diagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Basic/ConvertUTF.h"
32#include "llvm/CallingConv.h"
33#include "llvm/Module.h"
34#include "llvm/Intrinsics.h"
35#include "llvm/LLVMContext.h"
36#include "llvm/Target/TargetData.h"
37#include "llvm/Support/ErrorHandling.h"
38using namespace clang;
39using namespace CodeGen;
40
41
42CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
43                             llvm::Module &M, const llvm::TargetData &TD,
44                             Diagnostic &diags)
45  : BlockModule(C, M, TD, Types, *this), Context(C),
46    Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
47    TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
48    Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
49    MangleCtx(C), VtableInfo(*this), Runtime(0),
50    MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0),
51    VMContext(M.getContext()) {
52
53  if (!Features.ObjC1)
54    Runtime = 0;
55  else if (!Features.NeXTRuntime)
56    Runtime = CreateGNUObjCRuntime(*this);
57  else if (Features.ObjCNonFragileABI)
58    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
59  else
60    Runtime = CreateMacObjCRuntime(*this);
61
62  // If debug info generation is enabled, create the CGDebugInfo object.
63  DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
64}
65
66CodeGenModule::~CodeGenModule() {
67  delete Runtime;
68  delete DebugInfo;
69}
70
71void CodeGenModule::createObjCRuntime() {
72  if (!Features.NeXTRuntime)
73    Runtime = CreateGNUObjCRuntime(*this);
74  else if (Features.ObjCNonFragileABI)
75    Runtime = CreateMacNonFragileABIObjCRuntime(*this);
76  else
77    Runtime = CreateMacObjCRuntime(*this);
78}
79
80void CodeGenModule::Release() {
81  EmitDeferred();
82  EmitCXXGlobalInitFunc();
83  if (Runtime)
84    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
85      AddGlobalCtor(ObjCInitFunction);
86  EmitCtorList(GlobalCtors, "llvm.global_ctors");
87  EmitCtorList(GlobalDtors, "llvm.global_dtors");
88  EmitAnnotations();
89  EmitLLVMUsed();
90}
91
92/// ErrorUnsupported - Print out an error that codegen doesn't support the
93/// specified stmt yet.
94void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
95                                     bool OmitOnError) {
96  if (OmitOnError && getDiags().hasErrorOccurred())
97    return;
98  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
99                                               "cannot compile this %0 yet");
100  std::string Msg = Type;
101  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
102    << Msg << S->getSourceRange();
103}
104
105/// ErrorUnsupported - Print out an error that codegen doesn't support the
106/// specified decl yet.
107void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
108                                     bool OmitOnError) {
109  if (OmitOnError && getDiags().hasErrorOccurred())
110    return;
111  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
112                                               "cannot compile this %0 yet");
113  std::string Msg = Type;
114  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
115}
116
117LangOptions::VisibilityMode
118CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
119  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
120    if (VD->getStorageClass() == VarDecl::PrivateExtern)
121      return LangOptions::Hidden;
122
123  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
124    switch (attr->getVisibility()) {
125    default: assert(0 && "Unknown visibility!");
126    case VisibilityAttr::DefaultVisibility:
127      return LangOptions::Default;
128    case VisibilityAttr::HiddenVisibility:
129      return LangOptions::Hidden;
130    case VisibilityAttr::ProtectedVisibility:
131      return LangOptions::Protected;
132    }
133  }
134
135  // This decl should have the same visibility as its parent.
136  if (const DeclContext *DC = D->getDeclContext())
137    return getDeclVisibilityMode(cast<Decl>(DC));
138
139  return getLangOptions().getVisibilityMode();
140}
141
142void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
143                                        const Decl *D) const {
144  // Internal definitions always have default visibility.
145  if (GV->hasLocalLinkage()) {
146    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
147    return;
148  }
149
150  switch (getDeclVisibilityMode(D)) {
151  default: assert(0 && "Unknown visibility!");
152  case LangOptions::Default:
153    return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
154  case LangOptions::Hidden:
155    return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
156  case LangOptions::Protected:
157    return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
158  }
159}
160
161const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
162  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
163
164  if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
165    return getMangledCXXCtorName(D, GD.getCtorType());
166  if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
167    return getMangledCXXDtorName(D, GD.getDtorType());
168
169  return getMangledName(ND);
170}
171
172/// \brief Retrieves the mangled name for the given declaration.
173///
174/// If the given declaration requires a mangled name, returns an
175/// const char* containing the mangled name.  Otherwise, returns
176/// the unmangled name.
177///
178const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
179  if (!getMangleContext().shouldMangleDeclName(ND)) {
180    assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
181    return ND->getNameAsCString();
182  }
183
184  llvm::SmallString<256> Name;
185  getMangleContext().mangleName(ND, Name);
186  Name += '\0';
187  return UniqueMangledName(Name.begin(), Name.end());
188}
189
190const char *CodeGenModule::UniqueMangledName(const char *NameStart,
191                                             const char *NameEnd) {
192  assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
193
194  return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
195}
196
197/// AddGlobalCtor - Add a function to the list that will be called before
198/// main() runs.
199void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
200  // FIXME: Type coercion of void()* types.
201  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
202}
203
204/// AddGlobalDtor - Add a function to the list that will be called
205/// when the module is unloaded.
206void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
207  // FIXME: Type coercion of void()* types.
208  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
209}
210
211void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
212  // Ctor function type is void()*.
213  llvm::FunctionType* CtorFTy =
214    llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
215                            std::vector<const llvm::Type*>(),
216                            false);
217  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
218
219  // Get the type of a ctor entry, { i32, void ()* }.
220  llvm::StructType* CtorStructTy =
221    llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
222                          llvm::PointerType::getUnqual(CtorFTy), NULL);
223
224  // Construct the constructor and destructor arrays.
225  std::vector<llvm::Constant*> Ctors;
226  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
227    std::vector<llvm::Constant*> S;
228    S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
229                I->second, false));
230    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
231    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
232  }
233
234  if (!Ctors.empty()) {
235    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
236    new llvm::GlobalVariable(TheModule, AT, false,
237                             llvm::GlobalValue::AppendingLinkage,
238                             llvm::ConstantArray::get(AT, Ctors),
239                             GlobalName);
240  }
241}
242
243void CodeGenModule::EmitAnnotations() {
244  if (Annotations.empty())
245    return;
246
247  // Create a new global variable for the ConstantStruct in the Module.
248  llvm::Constant *Array =
249  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
250                                                Annotations.size()),
251                           Annotations);
252  llvm::GlobalValue *gv =
253  new llvm::GlobalVariable(TheModule, Array->getType(), false,
254                           llvm::GlobalValue::AppendingLinkage, Array,
255                           "llvm.global.annotations");
256  gv->setSection("llvm.metadata");
257}
258
259static CodeGenModule::GVALinkage
260GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
261                      const LangOptions &Features) {
262  CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
263
264  Linkage L = FD->getLinkage();
265  if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
266      FD->getType()->getLinkage() == UniqueExternalLinkage)
267    L = UniqueExternalLinkage;
268
269  switch (L) {
270  case NoLinkage:
271  case InternalLinkage:
272  case UniqueExternalLinkage:
273    return CodeGenModule::GVA_Internal;
274
275  case ExternalLinkage:
276    switch (FD->getTemplateSpecializationKind()) {
277    case TSK_Undeclared:
278    case TSK_ExplicitSpecialization:
279      External = CodeGenModule::GVA_StrongExternal;
280      break;
281
282    case TSK_ExplicitInstantiationDefinition:
283      // FIXME: explicit instantiation definitions should use weak linkage
284      return CodeGenModule::GVA_StrongExternal;
285
286    case TSK_ExplicitInstantiationDeclaration:
287    case TSK_ImplicitInstantiation:
288      External = CodeGenModule::GVA_TemplateInstantiation;
289      break;
290    }
291  }
292
293  if (!FD->isInlined())
294    return External;
295
296  if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
297    // GNU or C99 inline semantics. Determine whether this symbol should be
298    // externally visible.
299    if (FD->isInlineDefinitionExternallyVisible())
300      return External;
301
302    // C99 inline semantics, where the symbol is not externally visible.
303    return CodeGenModule::GVA_C99Inline;
304  }
305
306  // C++0x [temp.explicit]p9:
307  //   [ Note: The intent is that an inline function that is the subject of
308  //   an explicit instantiation declaration will still be implicitly
309  //   instantiated when used so that the body can be considered for
310  //   inlining, but that no out-of-line copy of the inline function would be
311  //   generated in the translation unit. -- end note ]
312  if (FD->getTemplateSpecializationKind()
313                                       == TSK_ExplicitInstantiationDeclaration)
314    return CodeGenModule::GVA_C99Inline;
315
316  return CodeGenModule::GVA_CXXInline;
317}
318
319/// SetFunctionDefinitionAttributes - Set attributes for a global.
320///
321/// FIXME: This is currently only done for aliases and functions, but not for
322/// variables (these details are set in EmitGlobalVarDefinition for variables).
323void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
324                                                    llvm::GlobalValue *GV) {
325  GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
326
327  if (Linkage == GVA_Internal) {
328    GV->setLinkage(llvm::Function::InternalLinkage);
329  } else if (D->hasAttr<DLLExportAttr>()) {
330    GV->setLinkage(llvm::Function::DLLExportLinkage);
331  } else if (D->hasAttr<WeakAttr>()) {
332    GV->setLinkage(llvm::Function::WeakAnyLinkage);
333  } else if (Linkage == GVA_C99Inline) {
334    // In C99 mode, 'inline' functions are guaranteed to have a strong
335    // definition somewhere else, so we can use available_externally linkage.
336    GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
337  } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
338    // In C++, the compiler has to emit a definition in every translation unit
339    // that references the function.  We should use linkonce_odr because
340    // a) if all references in this translation unit are optimized away, we
341    // don't need to codegen it.  b) if the function persists, it needs to be
342    // merged with other definitions. c) C++ has the ODR, so we know the
343    // definition is dependable.
344    GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
345  } else {
346    assert(Linkage == GVA_StrongExternal);
347    // Otherwise, we have strong external linkage.
348    GV->setLinkage(llvm::Function::ExternalLinkage);
349  }
350
351  SetCommonAttributes(D, GV);
352}
353
354void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
355                                              const CGFunctionInfo &Info,
356                                              llvm::Function *F) {
357  unsigned CallingConv;
358  AttributeListType AttributeList;
359  ConstructAttributeList(Info, D, AttributeList, CallingConv);
360  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
361                                          AttributeList.size()));
362  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
363}
364
365void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
366                                                           llvm::Function *F) {
367  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
368    F->addFnAttr(llvm::Attribute::NoUnwind);
369
370  if (D->hasAttr<AlwaysInlineAttr>())
371    F->addFnAttr(llvm::Attribute::AlwaysInline);
372
373  if (D->hasAttr<NoInlineAttr>())
374    F->addFnAttr(llvm::Attribute::NoInline);
375
376  if (Features.getStackProtectorMode() == LangOptions::SSPOn)
377    F->addFnAttr(llvm::Attribute::StackProtect);
378  else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
379    F->addFnAttr(llvm::Attribute::StackProtectReq);
380
381  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
382    unsigned width = Context.Target.getCharWidth();
383    F->setAlignment(AA->getAlignment() / width);
384    while ((AA = AA->getNext<AlignedAttr>()))
385      F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
386  }
387  // C++ ABI requires 2-byte alignment for member functions.
388  if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
389    F->setAlignment(2);
390}
391
392void CodeGenModule::SetCommonAttributes(const Decl *D,
393                                        llvm::GlobalValue *GV) {
394  setGlobalVisibility(GV, D);
395
396  if (D->hasAttr<UsedAttr>())
397    AddUsedGlobal(GV);
398
399  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
400    GV->setSection(SA->getName());
401
402  getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
403}
404
405void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
406                                                  llvm::Function *F,
407                                                  const CGFunctionInfo &FI) {
408  SetLLVMFunctionAttributes(D, FI, F);
409  SetLLVMFunctionAttributesForDefinition(D, F);
410
411  F->setLinkage(llvm::Function::InternalLinkage);
412
413  SetCommonAttributes(D, F);
414}
415
416void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
417                                          llvm::Function *F,
418                                          bool IsIncompleteFunction) {
419  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
420
421  if (!IsIncompleteFunction)
422    SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
423
424  // Only a few attributes are set on declarations; these may later be
425  // overridden by a definition.
426
427  if (FD->hasAttr<DLLImportAttr>()) {
428    F->setLinkage(llvm::Function::DLLImportLinkage);
429  } else if (FD->hasAttr<WeakAttr>() ||
430             FD->hasAttr<WeakImportAttr>()) {
431    // "extern_weak" is overloaded in LLVM; we probably should have
432    // separate linkage types for this.
433    F->setLinkage(llvm::Function::ExternalWeakLinkage);
434  } else {
435    F->setLinkage(llvm::Function::ExternalLinkage);
436  }
437
438  if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
439    F->setSection(SA->getName());
440}
441
442void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
443  assert(!GV->isDeclaration() &&
444         "Only globals with definition can force usage.");
445  LLVMUsed.push_back(GV);
446}
447
448void CodeGenModule::EmitLLVMUsed() {
449  // Don't create llvm.used if there is no need.
450  if (LLVMUsed.empty())
451    return;
452
453  const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
454
455  // Convert LLVMUsed to what ConstantArray needs.
456  std::vector<llvm::Constant*> UsedArray;
457  UsedArray.resize(LLVMUsed.size());
458  for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
459    UsedArray[i] =
460     llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
461                                      i8PTy);
462  }
463
464  if (UsedArray.empty())
465    return;
466  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
467
468  llvm::GlobalVariable *GV =
469    new llvm::GlobalVariable(getModule(), ATy, false,
470                             llvm::GlobalValue::AppendingLinkage,
471                             llvm::ConstantArray::get(ATy, UsedArray),
472                             "llvm.used");
473
474  GV->setSection("llvm.metadata");
475}
476
477void CodeGenModule::EmitDeferred() {
478  // Emit code for any potentially referenced deferred decls.  Since a
479  // previously unused static decl may become used during the generation of code
480  // for a static function, iterate until no  changes are made.
481  while (!DeferredDeclsToEmit.empty()) {
482    GlobalDecl D = DeferredDeclsToEmit.back();
483    DeferredDeclsToEmit.pop_back();
484
485    // The mangled name for the decl must have been emitted in GlobalDeclMap.
486    // Look it up to see if it was defined with a stronger definition (e.g. an
487    // extern inline function with a strong function redefinition).  If so,
488    // just ignore the deferred decl.
489    llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
490    assert(CGRef && "Deferred decl wasn't referenced?");
491
492    if (!CGRef->isDeclaration())
493      continue;
494
495    // Otherwise, emit the definition and move on to the next one.
496    EmitGlobalDefinition(D);
497  }
498}
499
500/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
501/// annotation information for a given GlobalValue.  The annotation struct is
502/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
503/// GlobalValue being annotated.  The second field is the constant string
504/// created from the AnnotateAttr's annotation.  The third field is a constant
505/// string containing the name of the translation unit.  The fourth field is
506/// the line number in the file of the annotated value declaration.
507///
508/// FIXME: this does not unique the annotation string constants, as llvm-gcc
509///        appears to.
510///
511llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
512                                                const AnnotateAttr *AA,
513                                                unsigned LineNo) {
514  llvm::Module *M = &getModule();
515
516  // get [N x i8] constants for the annotation string, and the filename string
517  // which are the 2nd and 3rd elements of the global annotation structure.
518  const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
519  llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
520                                                  AA->getAnnotation(), true);
521  llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
522                                                  M->getModuleIdentifier(),
523                                                  true);
524
525  // Get the two global values corresponding to the ConstantArrays we just
526  // created to hold the bytes of the strings.
527  llvm::GlobalValue *annoGV =
528    new llvm::GlobalVariable(*M, anno->getType(), false,
529                             llvm::GlobalValue::PrivateLinkage, anno,
530                             GV->getName());
531  // translation unit name string, emitted into the llvm.metadata section.
532  llvm::GlobalValue *unitGV =
533    new llvm::GlobalVariable(*M, unit->getType(), false,
534                             llvm::GlobalValue::PrivateLinkage, unit,
535                             ".str");
536
537  // Create the ConstantStruct for the global annotation.
538  llvm::Constant *Fields[4] = {
539    llvm::ConstantExpr::getBitCast(GV, SBP),
540    llvm::ConstantExpr::getBitCast(annoGV, SBP),
541    llvm::ConstantExpr::getBitCast(unitGV, SBP),
542    llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
543  };
544  return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
545}
546
547bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
548  // Never defer when EmitAllDecls is specified or the decl has
549  // attribute used.
550  if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
551    return false;
552
553  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
554    // Constructors and destructors should never be deferred.
555    if (FD->hasAttr<ConstructorAttr>() ||
556        FD->hasAttr<DestructorAttr>())
557      return false;
558
559    // The key function for a class must never be deferred.
560    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
561      const CXXRecordDecl *RD = MD->getParent();
562      if (MD->isOutOfLine() && RD->isDynamicClass()) {
563        const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
564        if (KeyFunction &&
565            KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
566          return false;
567      }
568    }
569
570    GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
571
572    // static, static inline, always_inline, and extern inline functions can
573    // always be deferred.  Normal inline functions can be deferred in C99/C++.
574    if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
575        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
576      return true;
577    return false;
578  }
579
580  const VarDecl *VD = cast<VarDecl>(Global);
581  assert(VD->isFileVarDecl() && "Invalid decl");
582
583  // We never want to defer structs that have non-trivial constructors or
584  // destructors.
585
586  // FIXME: Handle references.
587  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
588    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
589      if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
590        return false;
591    }
592  }
593
594  // Static data may be deferred, but out-of-line static data members
595  // cannot be.
596  Linkage L = VD->getLinkage();
597  if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus &&
598      VD->getType()->getLinkage() == UniqueExternalLinkage)
599    L = UniqueExternalLinkage;
600
601  switch (L) {
602  case NoLinkage:
603  case InternalLinkage:
604  case UniqueExternalLinkage:
605    // Initializer has side effects?
606    if (VD->getInit() && VD->getInit()->HasSideEffects(Context))
607      return false;
608    return !(VD->isStaticDataMember() && VD->isOutOfLine());
609
610  case ExternalLinkage:
611    break;
612  }
613
614  return false;
615}
616
617void CodeGenModule::EmitGlobal(GlobalDecl GD) {
618  const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
619
620  // If this is an alias definition (which otherwise looks like a declaration)
621  // emit it now.
622  if (Global->hasAttr<AliasAttr>())
623    return EmitAliasDefinition(Global);
624
625  // Ignore declarations, they will be emitted on their first use.
626  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
627    // Forward declarations are emitted lazily on first use.
628    if (!FD->isThisDeclarationADefinition())
629      return;
630  } else {
631    const VarDecl *VD = cast<VarDecl>(Global);
632    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
633
634    if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
635      return;
636  }
637
638  // Defer code generation when possible if this is a static definition, inline
639  // function etc.  These we only want to emit if they are used.
640  if (MayDeferGeneration(Global)) {
641    // If the value has already been used, add it directly to the
642    // DeferredDeclsToEmit list.
643    const char *MangledName = getMangledName(GD);
644    if (GlobalDeclMap.count(MangledName))
645      DeferredDeclsToEmit.push_back(GD);
646    else {
647      // Otherwise, remember that we saw a deferred decl with this name.  The
648      // first use of the mangled name will cause it to move into
649      // DeferredDeclsToEmit.
650      DeferredDecls[MangledName] = GD;
651    }
652    return;
653  }
654
655  // Otherwise emit the definition.
656  EmitGlobalDefinition(GD);
657}
658
659void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
660  const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
661
662  PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(),
663                                 Context.getSourceManager(),
664                                 "Generating code for declaration");
665
666  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
667    getVtableInfo().MaybeEmitVtable(GD);
668    if (MD->isVirtual() && MD->isOutOfLine() &&
669        (!isa<CXXDestructorDecl>(D) || GD.getDtorType() != Dtor_Base)) {
670      if (isa<CXXDestructorDecl>(D)) {
671        GlobalDecl CanonGD(cast<CXXDestructorDecl>(D->getCanonicalDecl()),
672                           GD.getDtorType());
673        BuildThunksForVirtual(CanonGD);
674      } else {
675        BuildThunksForVirtual(MD->getCanonicalDecl());
676      }
677    }
678  }
679
680  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
681    EmitCXXConstructor(CD, GD.getCtorType());
682  else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
683    EmitCXXDestructor(DD, GD.getDtorType());
684  else if (isa<FunctionDecl>(D))
685    EmitGlobalFunctionDefinition(GD);
686  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
687    EmitGlobalVarDefinition(VD);
688  else {
689    assert(0 && "Invalid argument to EmitGlobalDefinition()");
690  }
691}
692
693/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
694/// module, create and return an llvm Function with the specified type. If there
695/// is something in the module with the specified name, return it potentially
696/// bitcasted to the right type.
697///
698/// If D is non-null, it specifies a decl that correspond to this.  This is used
699/// to set the attributes on the function when it is first created.
700llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
701                                                       const llvm::Type *Ty,
702                                                       GlobalDecl D) {
703  // Lookup the entry, lazily creating it if necessary.
704  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
705  if (Entry) {
706    if (Entry->getType()->getElementType() == Ty)
707      return Entry;
708
709    // Make sure the result is of the correct type.
710    const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
711    return llvm::ConstantExpr::getBitCast(Entry, PTy);
712  }
713
714  // This function doesn't have a complete type (for example, the return
715  // type is an incomplete struct). Use a fake type instead, and make
716  // sure not to try to set attributes.
717  bool IsIncompleteFunction = false;
718  if (!isa<llvm::FunctionType>(Ty)) {
719    Ty = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
720                                 std::vector<const llvm::Type*>(), false);
721    IsIncompleteFunction = true;
722  }
723  llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
724                                             llvm::Function::ExternalLinkage,
725                                             "", &getModule());
726  F->setName(MangledName);
727  if (D.getDecl())
728    SetFunctionAttributes(D, F, IsIncompleteFunction);
729  Entry = F;
730
731  // This is the first use or definition of a mangled name.  If there is a
732  // deferred decl with this name, remember that we need to emit it at the end
733  // of the file.
734  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
735    DeferredDecls.find(MangledName);
736  if (DDI != DeferredDecls.end()) {
737    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
738    // list, and remove it from DeferredDecls (since we don't need it anymore).
739    DeferredDeclsToEmit.push_back(DDI->second);
740    DeferredDecls.erase(DDI);
741  } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
742    // If this the first reference to a C++ inline function in a class, queue up
743    // the deferred function body for emission.  These are not seen as
744    // top-level declarations.
745    if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
746      DeferredDeclsToEmit.push_back(D);
747    // A called constructor which has no definition or declaration need be
748    // synthesized.
749    else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
750      if (CD->isImplicit())
751        DeferredDeclsToEmit.push_back(D);
752    } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
753      if (DD->isImplicit())
754        DeferredDeclsToEmit.push_back(D);
755    } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
756      if (MD->isCopyAssignment() && MD->isImplicit())
757        DeferredDeclsToEmit.push_back(D);
758    }
759  }
760
761  return F;
762}
763
764/// GetAddrOfFunction - Return the address of the given function.  If Ty is
765/// non-null, then this function will use the specified type if it has to
766/// create it (this occurs when we see a definition of the function).
767llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
768                                                 const llvm::Type *Ty) {
769  // If there was no specific requested type, just convert it now.
770  if (!Ty)
771    Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
772  return GetOrCreateLLVMFunction(getMangledName(GD), Ty, GD);
773}
774
775/// CreateRuntimeFunction - Create a new runtime function with the specified
776/// type and name.
777llvm::Constant *
778CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
779                                     const char *Name) {
780  // Convert Name to be a uniqued string from the IdentifierInfo table.
781  Name = getContext().Idents.get(Name).getNameStart();
782  return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
783}
784
785static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
786  if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
787    return false;
788  if (Context.getLangOptions().CPlusPlus &&
789      Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
790    // FIXME: We should do something fancier here!
791    return false;
792  }
793  return true;
794}
795
796/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
797/// create and return an llvm GlobalVariable with the specified type.  If there
798/// is something in the module with the specified name, return it potentially
799/// bitcasted to the right type.
800///
801/// If D is non-null, it specifies a decl that correspond to this.  This is used
802/// to set the attributes on the global when it is first created.
803llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
804                                                     const llvm::PointerType*Ty,
805                                                     const VarDecl *D) {
806  // Lookup the entry, lazily creating it if necessary.
807  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
808  if (Entry) {
809    if (Entry->getType() == Ty)
810      return Entry;
811
812    // Make sure the result is of the correct type.
813    return llvm::ConstantExpr::getBitCast(Entry, Ty);
814  }
815
816  // This is the first use or definition of a mangled name.  If there is a
817  // deferred decl with this name, remember that we need to emit it at the end
818  // of the file.
819  llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
820    DeferredDecls.find(MangledName);
821  if (DDI != DeferredDecls.end()) {
822    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
823    // list, and remove it from DeferredDecls (since we don't need it anymore).
824    DeferredDeclsToEmit.push_back(DDI->second);
825    DeferredDecls.erase(DDI);
826  }
827
828  llvm::GlobalVariable *GV =
829    new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
830                             llvm::GlobalValue::ExternalLinkage,
831                             0, "", 0,
832                             false, Ty->getAddressSpace());
833  GV->setName(MangledName);
834
835  // Handle things which are present even on external declarations.
836  if (D) {
837    // FIXME: This code is overly simple and should be merged with other global
838    // handling.
839    GV->setConstant(DeclIsConstantGlobal(Context, D));
840
841    // FIXME: Merge with other attribute handling code.
842    if (D->getStorageClass() == VarDecl::PrivateExtern)
843      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
844
845    if (D->hasAttr<WeakAttr>() ||
846        D->hasAttr<WeakImportAttr>())
847      GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
848
849    GV->setThreadLocal(D->isThreadSpecified());
850  }
851
852  return Entry = GV;
853}
854
855
856/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
857/// given global variable.  If Ty is non-null and if the global doesn't exist,
858/// then it will be greated with the specified type instead of whatever the
859/// normal requested type would be.
860llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
861                                                  const llvm::Type *Ty) {
862  assert(D->hasGlobalStorage() && "Not a global variable");
863  QualType ASTTy = D->getType();
864  if (Ty == 0)
865    Ty = getTypes().ConvertTypeForMem(ASTTy);
866
867  const llvm::PointerType *PTy =
868    llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
869  return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
870}
871
872/// CreateRuntimeVariable - Create a new runtime global variable with the
873/// specified type and name.
874llvm::Constant *
875CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
876                                     const char *Name) {
877  // Convert Name to be a uniqued string from the IdentifierInfo table.
878  Name = getContext().Idents.get(Name).getNameStart();
879  return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
880}
881
882void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
883  assert(!D->getInit() && "Cannot emit definite definitions here!");
884
885  if (MayDeferGeneration(D)) {
886    // If we have not seen a reference to this variable yet, place it
887    // into the deferred declarations table to be emitted if needed
888    // later.
889    const char *MangledName = getMangledName(D);
890    if (GlobalDeclMap.count(MangledName) == 0) {
891      DeferredDecls[MangledName] = D;
892      return;
893    }
894  }
895
896  // The tentative definition is the only definition.
897  EmitGlobalVarDefinition(D);
898}
899
900llvm::GlobalVariable::LinkageTypes
901CodeGenModule::getVtableLinkage(const CXXRecordDecl *RD) {
902  if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
903    return llvm::GlobalVariable::InternalLinkage;
904
905  if (const CXXMethodDecl *KeyFunction
906                                    = RD->getASTContext().getKeyFunction(RD)) {
907    // If this class has a key function, use that to determine the linkage of
908    // the vtable.
909    const FunctionDecl *Def = 0;
910    if (KeyFunction->getBody(Def))
911      KeyFunction = cast<CXXMethodDecl>(Def);
912
913    switch (KeyFunction->getTemplateSpecializationKind()) {
914      case TSK_Undeclared:
915      case TSK_ExplicitSpecialization:
916        if (KeyFunction->isInlined())
917          return llvm::GlobalVariable::WeakODRLinkage;
918
919        return llvm::GlobalVariable::ExternalLinkage;
920
921      case TSK_ImplicitInstantiation:
922      case TSK_ExplicitInstantiationDefinition:
923        return llvm::GlobalVariable::WeakODRLinkage;
924
925      case TSK_ExplicitInstantiationDeclaration:
926        // FIXME: Use available_externally linkage. However, this currently
927        // breaks LLVM's build due to undefined symbols.
928        //      return llvm::GlobalVariable::AvailableExternallyLinkage;
929        return llvm::GlobalVariable::WeakODRLinkage;
930    }
931  }
932
933  switch (RD->getTemplateSpecializationKind()) {
934  case TSK_Undeclared:
935  case TSK_ExplicitSpecialization:
936  case TSK_ImplicitInstantiation:
937  case TSK_ExplicitInstantiationDefinition:
938    return llvm::GlobalVariable::WeakODRLinkage;
939
940  case TSK_ExplicitInstantiationDeclaration:
941    // FIXME: Use available_externally linkage. However, this currently
942    // breaks LLVM's build due to undefined symbols.
943    //   return llvm::GlobalVariable::AvailableExternallyLinkage;
944    return llvm::GlobalVariable::WeakODRLinkage;
945  }
946
947  // Silence GCC warning.
948  return llvm::GlobalVariable::WeakODRLinkage;
949}
950
951static CodeGenModule::GVALinkage
952GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
953  // If this is a static data member, compute the kind of template
954  // specialization. Otherwise, this variable is not part of a
955  // template.
956  TemplateSpecializationKind TSK = TSK_Undeclared;
957  if (VD->isStaticDataMember())
958    TSK = VD->getTemplateSpecializationKind();
959
960  Linkage L = VD->getLinkage();
961  if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
962      VD->getType()->getLinkage() == UniqueExternalLinkage)
963    L = UniqueExternalLinkage;
964
965  switch (L) {
966  case NoLinkage:
967  case InternalLinkage:
968  case UniqueExternalLinkage:
969    return CodeGenModule::GVA_Internal;
970
971  case ExternalLinkage:
972    switch (TSK) {
973    case TSK_Undeclared:
974    case TSK_ExplicitSpecialization:
975
976      // FIXME: ExplicitInstantiationDefinition should be weak!
977    case TSK_ExplicitInstantiationDefinition:
978      return CodeGenModule::GVA_StrongExternal;
979
980    case TSK_ExplicitInstantiationDeclaration:
981      llvm_unreachable("Variable should not be instantiated");
982      // Fall through to treat this like any other instantiation.
983
984    case TSK_ImplicitInstantiation:
985      return CodeGenModule::GVA_TemplateInstantiation;
986    }
987  }
988
989  return CodeGenModule::GVA_StrongExternal;
990}
991
992CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
993    return CharUnits::fromQuantity(
994      TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
995}
996
997void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
998  llvm::Constant *Init = 0;
999  QualType ASTTy = D->getType();
1000  bool NonConstInit = false;
1001
1002  const Expr *InitExpr = D->getAnyInitializer();
1003
1004  if (!InitExpr) {
1005    // This is a tentative definition; tentative definitions are
1006    // implicitly initialized with { 0 }.
1007    //
1008    // Note that tentative definitions are only emitted at the end of
1009    // a translation unit, so they should never have incomplete
1010    // type. In addition, EmitTentativeDefinition makes sure that we
1011    // never attempt to emit a tentative definition if a real one
1012    // exists. A use may still exists, however, so we still may need
1013    // to do a RAUW.
1014    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1015    Init = EmitNullConstant(D->getType());
1016  } else {
1017    Init = EmitConstantExpr(InitExpr, D->getType());
1018
1019    if (!Init) {
1020      QualType T = InitExpr->getType();
1021      if (getLangOptions().CPlusPlus) {
1022        EmitCXXGlobalVarDeclInitFunc(D);
1023        Init = EmitNullConstant(T);
1024        NonConstInit = true;
1025      } else {
1026        ErrorUnsupported(D, "static initializer");
1027        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1028      }
1029    }
1030  }
1031
1032  const llvm::Type* InitType = Init->getType();
1033  llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1034
1035  // Strip off a bitcast if we got one back.
1036  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1037    assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1038           // all zero index gep.
1039           CE->getOpcode() == llvm::Instruction::GetElementPtr);
1040    Entry = CE->getOperand(0);
1041  }
1042
1043  // Entry is now either a Function or GlobalVariable.
1044  llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1045
1046  // We have a definition after a declaration with the wrong type.
1047  // We must make a new GlobalVariable* and update everything that used OldGV
1048  // (a declaration or tentative definition) with the new GlobalVariable*
1049  // (which will be a definition).
1050  //
1051  // This happens if there is a prototype for a global (e.g.
1052  // "extern int x[];") and then a definition of a different type (e.g.
1053  // "int x[10];"). This also happens when an initializer has a different type
1054  // from the type of the global (this happens with unions).
1055  if (GV == 0 ||
1056      GV->getType()->getElementType() != InitType ||
1057      GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1058
1059    // Remove the old entry from GlobalDeclMap so that we'll create a new one.
1060    GlobalDeclMap.erase(getMangledName(D));
1061
1062    // Make a new global with the correct type, this is now guaranteed to work.
1063    GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1064    GV->takeName(cast<llvm::GlobalValue>(Entry));
1065
1066    // Replace all uses of the old global with the new global
1067    llvm::Constant *NewPtrForOldDecl =
1068        llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1069    Entry->replaceAllUsesWith(NewPtrForOldDecl);
1070
1071    // Erase the old global, since it is no longer used.
1072    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1073  }
1074
1075  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1076    SourceManager &SM = Context.getSourceManager();
1077    AddAnnotation(EmitAnnotateAttr(GV, AA,
1078                              SM.getInstantiationLineNumber(D->getLocation())));
1079  }
1080
1081  GV->setInitializer(Init);
1082
1083  // If it is safe to mark the global 'constant', do so now.
1084  GV->setConstant(false);
1085  if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1086    GV->setConstant(true);
1087
1088  GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1089
1090  // Set the llvm linkage type as appropriate.
1091  GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1092  if (Linkage == GVA_Internal)
1093    GV->setLinkage(llvm::Function::InternalLinkage);
1094  else if (D->hasAttr<DLLImportAttr>())
1095    GV->setLinkage(llvm::Function::DLLImportLinkage);
1096  else if (D->hasAttr<DLLExportAttr>())
1097    GV->setLinkage(llvm::Function::DLLExportLinkage);
1098  else if (D->hasAttr<WeakAttr>()) {
1099    if (GV->isConstant())
1100      GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1101    else
1102      GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1103  } else if (Linkage == GVA_TemplateInstantiation)
1104    GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1105  else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
1106           !D->hasExternalStorage() && !D->getInit() &&
1107           !D->getAttr<SectionAttr>()) {
1108    GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1109    // common vars aren't constant even if declared const.
1110    GV->setConstant(false);
1111  } else
1112    GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1113
1114  SetCommonAttributes(D, GV);
1115
1116  // Emit global variable debug information.
1117  if (CGDebugInfo *DI = getDebugInfo()) {
1118    DI->setLocation(D->getLocation());
1119    DI->EmitGlobalVariable(GV, D);
1120  }
1121}
1122
1123/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1124/// implement a function with no prototype, e.g. "int foo() {}".  If there are
1125/// existing call uses of the old function in the module, this adjusts them to
1126/// call the new function directly.
1127///
1128/// This is not just a cleanup: the always_inline pass requires direct calls to
1129/// functions to be able to inline them.  If there is a bitcast in the way, it
1130/// won't inline them.  Instcombine normally deletes these calls, but it isn't
1131/// run at -O0.
1132static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1133                                                      llvm::Function *NewFn) {
1134  // If we're redefining a global as a function, don't transform it.
1135  llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1136  if (OldFn == 0) return;
1137
1138  const llvm::Type *NewRetTy = NewFn->getReturnType();
1139  llvm::SmallVector<llvm::Value*, 4> ArgList;
1140
1141  for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1142       UI != E; ) {
1143    // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1144    unsigned OpNo = UI.getOperandNo();
1145    llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
1146    if (!CI || OpNo != 0) continue;
1147
1148    // If the return types don't match exactly, and if the call isn't dead, then
1149    // we can't transform this call.
1150    if (CI->getType() != NewRetTy && !CI->use_empty())
1151      continue;
1152
1153    // If the function was passed too few arguments, don't transform.  If extra
1154    // arguments were passed, we silently drop them.  If any of the types
1155    // mismatch, we don't transform.
1156    unsigned ArgNo = 0;
1157    bool DontTransform = false;
1158    for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1159         E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1160      if (CI->getNumOperands()-1 == ArgNo ||
1161          CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
1162        DontTransform = true;
1163        break;
1164      }
1165    }
1166    if (DontTransform)
1167      continue;
1168
1169    // Okay, we can transform this.  Create the new call instruction and copy
1170    // over the required information.
1171    ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
1172    llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1173                                                     ArgList.end(), "", CI);
1174    ArgList.clear();
1175    if (!NewCall->getType()->isVoidTy())
1176      NewCall->takeName(CI);
1177    NewCall->setAttributes(CI->getAttributes());
1178    NewCall->setCallingConv(CI->getCallingConv());
1179
1180    // Finally, remove the old call, replacing any uses with the new one.
1181    if (!CI->use_empty())
1182      CI->replaceAllUsesWith(NewCall);
1183
1184    // Copy any custom metadata attached with CI.
1185    if (llvm::MDNode *DbgNode = CI->getMetadata("dbg"))
1186      NewCall->setMetadata("dbg", DbgNode);
1187    CI->eraseFromParent();
1188  }
1189}
1190
1191
1192void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1193  const llvm::FunctionType *Ty;
1194  const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1195
1196  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1197    bool isVariadic = D->getType()->getAs<FunctionProtoType>()->isVariadic();
1198
1199    Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
1200  } else {
1201    Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
1202
1203    // As a special case, make sure that definitions of K&R function
1204    // "type foo()" aren't declared as varargs (which forces the backend
1205    // to do unnecessary work).
1206    if (D->getType()->isFunctionNoProtoType()) {
1207      assert(Ty->isVarArg() && "Didn't lower type as expected");
1208      // Due to stret, the lowered function could have arguments.
1209      // Just create the same type as was lowered by ConvertType
1210      // but strip off the varargs bit.
1211      std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
1212      Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false);
1213    }
1214  }
1215
1216  // Get or create the prototype for the function.
1217  llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1218
1219  // Strip off a bitcast if we got one back.
1220  if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1221    assert(CE->getOpcode() == llvm::Instruction::BitCast);
1222    Entry = CE->getOperand(0);
1223  }
1224
1225
1226  if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1227    llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1228
1229    // If the types mismatch then we have to rewrite the definition.
1230    assert(OldFn->isDeclaration() &&
1231           "Shouldn't replace non-declaration");
1232
1233    // F is the Function* for the one with the wrong type, we must make a new
1234    // Function* and update everything that used F (a declaration) with the new
1235    // Function* (which will be a definition).
1236    //
1237    // This happens if there is a prototype for a function
1238    // (e.g. "int f()") and then a definition of a different type
1239    // (e.g. "int f(int x)").  Start by making a new function of the
1240    // correct type, RAUW, then steal the name.
1241    GlobalDeclMap.erase(getMangledName(D));
1242    llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1243    NewFn->takeName(OldFn);
1244
1245    // If this is an implementation of a function without a prototype, try to
1246    // replace any existing uses of the function (which may be calls) with uses
1247    // of the new function
1248    if (D->getType()->isFunctionNoProtoType()) {
1249      ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1250      OldFn->removeDeadConstantUsers();
1251    }
1252
1253    // Replace uses of F with the Function we will endow with a body.
1254    if (!Entry->use_empty()) {
1255      llvm::Constant *NewPtrForOldDecl =
1256        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1257      Entry->replaceAllUsesWith(NewPtrForOldDecl);
1258    }
1259
1260    // Ok, delete the old function now, which is dead.
1261    OldFn->eraseFromParent();
1262
1263    Entry = NewFn;
1264  }
1265
1266  llvm::Function *Fn = cast<llvm::Function>(Entry);
1267
1268  CodeGenFunction(*this).GenerateCode(D, Fn);
1269
1270  SetFunctionDefinitionAttributes(D, Fn);
1271  SetLLVMFunctionAttributesForDefinition(D, Fn);
1272
1273  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1274    AddGlobalCtor(Fn, CA->getPriority());
1275  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1276    AddGlobalDtor(Fn, DA->getPriority());
1277}
1278
1279void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
1280  const AliasAttr *AA = D->getAttr<AliasAttr>();
1281  assert(AA && "Not an alias?");
1282
1283  const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1284
1285  // Unique the name through the identifier table.
1286  const char *AliaseeName =
1287    getContext().Idents.get(AA->getAliasee()).getNameStart();
1288
1289  // Create a reference to the named value.  This ensures that it is emitted
1290  // if a deferred decl.
1291  llvm::Constant *Aliasee;
1292  if (isa<llvm::FunctionType>(DeclTy))
1293    Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
1294  else
1295    Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1296                                    llvm::PointerType::getUnqual(DeclTy), 0);
1297
1298  // Create the new alias itself, but don't set a name yet.
1299  llvm::GlobalValue *GA =
1300    new llvm::GlobalAlias(Aliasee->getType(),
1301                          llvm::Function::ExternalLinkage,
1302                          "", Aliasee, &getModule());
1303
1304  // See if there is already something with the alias' name in the module.
1305  const char *MangledName = getMangledName(D);
1306  llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1307
1308  if (Entry && !Entry->isDeclaration()) {
1309    // If there is a definition in the module, then it wins over the alias.
1310    // This is dubious, but allow it to be safe.  Just ignore the alias.
1311    GA->eraseFromParent();
1312    return;
1313  }
1314
1315  if (Entry) {
1316    // If there is a declaration in the module, then we had an extern followed
1317    // by the alias, as in:
1318    //   extern int test6();
1319    //   ...
1320    //   int test6() __attribute__((alias("test7")));
1321    //
1322    // Remove it and replace uses of it with the alias.
1323
1324    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1325                                                          Entry->getType()));
1326    Entry->eraseFromParent();
1327  }
1328
1329  // Now we know that there is no conflict, set the name.
1330  Entry = GA;
1331  GA->setName(MangledName);
1332
1333  // Set attributes which are particular to an alias; this is a
1334  // specialization of the attributes which may be set on a global
1335  // variable/function.
1336  if (D->hasAttr<DLLExportAttr>()) {
1337    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1338      // The dllexport attribute is ignored for undefined symbols.
1339      if (FD->getBody())
1340        GA->setLinkage(llvm::Function::DLLExportLinkage);
1341    } else {
1342      GA->setLinkage(llvm::Function::DLLExportLinkage);
1343    }
1344  } else if (D->hasAttr<WeakAttr>() ||
1345             D->hasAttr<WeakImportAttr>()) {
1346    GA->setLinkage(llvm::Function::WeakAnyLinkage);
1347  }
1348
1349  SetCommonAttributes(D, GA);
1350}
1351
1352/// getBuiltinLibFunction - Given a builtin id for a function like
1353/// "__builtin_fabsf", return a Function* for "fabsf".
1354llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1355                                                  unsigned BuiltinID) {
1356  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1357          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1358         "isn't a lib fn");
1359
1360  // Get the name, skip over the __builtin_ prefix (if necessary).
1361  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1362  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1363    Name += 10;
1364
1365  const llvm::FunctionType *Ty =
1366    cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1367
1368  // Unique the name through the identifier table.
1369  Name = getContext().Idents.get(Name).getNameStart();
1370  return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1371}
1372
1373llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1374                                            unsigned NumTys) {
1375  return llvm::Intrinsic::getDeclaration(&getModule(),
1376                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
1377}
1378
1379llvm::Function *CodeGenModule::getMemCpyFn() {
1380  if (MemCpyFn) return MemCpyFn;
1381  const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1382  return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
1383}
1384
1385llvm::Function *CodeGenModule::getMemMoveFn() {
1386  if (MemMoveFn) return MemMoveFn;
1387  const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1388  return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
1389}
1390
1391llvm::Function *CodeGenModule::getMemSetFn() {
1392  if (MemSetFn) return MemSetFn;
1393  const llvm::Type *IntPtr = TheTargetData.getIntPtrType(VMContext);
1394  return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
1395}
1396
1397static llvm::StringMapEntry<llvm::Constant*> &
1398GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1399                         const StringLiteral *Literal,
1400                         bool TargetIsLSB,
1401                         bool &IsUTF16,
1402                         unsigned &StringLength) {
1403  unsigned NumBytes = Literal->getByteLength();
1404
1405  // Check for simple case.
1406  if (!Literal->containsNonAsciiOrNull()) {
1407    StringLength = NumBytes;
1408    return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1409                                                StringLength));
1410  }
1411
1412  // Otherwise, convert the UTF8 literals into a byte string.
1413  llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1414  const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1415  UTF16 *ToPtr = &ToBuf[0];
1416
1417  ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1418                                               &ToPtr, ToPtr + NumBytes,
1419                                               strictConversion);
1420
1421  // Check for conversion failure.
1422  if (Result != conversionOK) {
1423    // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1424    // this duplicate code.
1425    assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1426    StringLength = NumBytes;
1427    return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1428                                                StringLength));
1429  }
1430
1431  // ConvertUTF8toUTF16 returns the length in ToPtr.
1432  StringLength = ToPtr - &ToBuf[0];
1433
1434  // Render the UTF-16 string into a byte array and convert to the target byte
1435  // order.
1436  //
1437  // FIXME: This isn't something we should need to do here.
1438  llvm::SmallString<128> AsBytes;
1439  AsBytes.reserve(StringLength * 2);
1440  for (unsigned i = 0; i != StringLength; ++i) {
1441    unsigned short Val = ToBuf[i];
1442    if (TargetIsLSB) {
1443      AsBytes.push_back(Val & 0xFF);
1444      AsBytes.push_back(Val >> 8);
1445    } else {
1446      AsBytes.push_back(Val >> 8);
1447      AsBytes.push_back(Val & 0xFF);
1448    }
1449  }
1450  // Append one extra null character, the second is automatically added by our
1451  // caller.
1452  AsBytes.push_back(0);
1453
1454  IsUTF16 = true;
1455  return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1456}
1457
1458llvm::Constant *
1459CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1460  unsigned StringLength = 0;
1461  bool isUTF16 = false;
1462  llvm::StringMapEntry<llvm::Constant*> &Entry =
1463    GetConstantCFStringEntry(CFConstantStringMap, Literal,
1464                             getTargetData().isLittleEndian(),
1465                             isUTF16, StringLength);
1466
1467  if (llvm::Constant *C = Entry.getValue())
1468    return C;
1469
1470  llvm::Constant *Zero =
1471      llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1472  llvm::Constant *Zeros[] = { Zero, Zero };
1473
1474  // If we don't already have it, get __CFConstantStringClassReference.
1475  if (!CFConstantStringClassRef) {
1476    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1477    Ty = llvm::ArrayType::get(Ty, 0);
1478    llvm::Constant *GV = CreateRuntimeVariable(Ty,
1479                                           "__CFConstantStringClassReference");
1480    // Decay array -> ptr
1481    CFConstantStringClassRef =
1482      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1483  }
1484
1485  QualType CFTy = getContext().getCFConstantStringType();
1486
1487  const llvm::StructType *STy =
1488    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1489
1490  std::vector<llvm::Constant*> Fields(4);
1491
1492  // Class pointer.
1493  Fields[0] = CFConstantStringClassRef;
1494
1495  // Flags.
1496  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1497  Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1498    llvm::ConstantInt::get(Ty, 0x07C8);
1499
1500  // String pointer.
1501  llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1502
1503  llvm::GlobalValue::LinkageTypes Linkage;
1504  bool isConstant;
1505  if (isUTF16) {
1506    // FIXME: why do utf strings get "_" labels instead of "L" labels?
1507    Linkage = llvm::GlobalValue::InternalLinkage;
1508    // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1509    // does make plain ascii ones writable.
1510    isConstant = true;
1511  } else {
1512    Linkage = llvm::GlobalValue::PrivateLinkage;
1513    isConstant = !Features.WritableStrings;
1514  }
1515
1516  llvm::GlobalVariable *GV =
1517    new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1518                             ".str");
1519  if (isUTF16) {
1520    CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1521    GV->setAlignment(Align.getQuantity());
1522  }
1523  Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1524
1525  // String length.
1526  Ty = getTypes().ConvertType(getContext().LongTy);
1527  Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1528
1529  // The struct.
1530  C = llvm::ConstantStruct::get(STy, Fields);
1531  GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1532                                llvm::GlobalVariable::PrivateLinkage, C,
1533                                "_unnamed_cfstring_");
1534  if (const char *Sect = getContext().Target.getCFStringSection())
1535    GV->setSection(Sect);
1536  Entry.setValue(GV);
1537
1538  return GV;
1539}
1540
1541/// GetStringForStringLiteral - Return the appropriate bytes for a
1542/// string literal, properly padded to match the literal type.
1543std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1544  const char *StrData = E->getStrData();
1545  unsigned Len = E->getByteLength();
1546
1547  const ConstantArrayType *CAT =
1548    getContext().getAsConstantArrayType(E->getType());
1549  assert(CAT && "String isn't pointer or array!");
1550
1551  // Resize the string to the right size.
1552  std::string Str(StrData, StrData+Len);
1553  uint64_t RealLen = CAT->getSize().getZExtValue();
1554
1555  if (E->isWide())
1556    RealLen *= getContext().Target.getWCharWidth()/8;
1557
1558  Str.resize(RealLen, '\0');
1559
1560  return Str;
1561}
1562
1563/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1564/// constant array for the given string literal.
1565llvm::Constant *
1566CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1567  // FIXME: This can be more efficient.
1568  // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1569  llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1570  if (S->isWide()) {
1571    llvm::Type *DestTy =
1572        llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1573    C = llvm::ConstantExpr::getBitCast(C, DestTy);
1574  }
1575  return C;
1576}
1577
1578/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1579/// array for the given ObjCEncodeExpr node.
1580llvm::Constant *
1581CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1582  std::string Str;
1583  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1584
1585  return GetAddrOfConstantCString(Str);
1586}
1587
1588
1589/// GenerateWritableString -- Creates storage for a string literal.
1590static llvm::Constant *GenerateStringLiteral(const std::string &str,
1591                                             bool constant,
1592                                             CodeGenModule &CGM,
1593                                             const char *GlobalName) {
1594  // Create Constant for this string literal. Don't add a '\0'.
1595  llvm::Constant *C =
1596      llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1597
1598  // Create a global variable for this string
1599  return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1600                                  llvm::GlobalValue::PrivateLinkage,
1601                                  C, GlobalName);
1602}
1603
1604/// GetAddrOfConstantString - Returns a pointer to a character array
1605/// containing the literal. This contents are exactly that of the
1606/// given string, i.e. it will not be null terminated automatically;
1607/// see GetAddrOfConstantCString. Note that whether the result is
1608/// actually a pointer to an LLVM constant depends on
1609/// Feature.WriteableStrings.
1610///
1611/// The result has pointer to array type.
1612llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1613                                                       const char *GlobalName) {
1614  bool IsConstant = !Features.WritableStrings;
1615
1616  // Get the default prefix if a name wasn't specified.
1617  if (!GlobalName)
1618    GlobalName = ".str";
1619
1620  // Don't share any string literals if strings aren't constant.
1621  if (!IsConstant)
1622    return GenerateStringLiteral(str, false, *this, GlobalName);
1623
1624  llvm::StringMapEntry<llvm::Constant *> &Entry =
1625    ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1626
1627  if (Entry.getValue())
1628    return Entry.getValue();
1629
1630  // Create a global variable for this.
1631  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1632  Entry.setValue(C);
1633  return C;
1634}
1635
1636/// GetAddrOfConstantCString - Returns a pointer to a character
1637/// array containing the literal and a terminating '\-'
1638/// character. The result has pointer to array type.
1639llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1640                                                        const char *GlobalName){
1641  return GetAddrOfConstantString(str + '\0', GlobalName);
1642}
1643
1644/// EmitObjCPropertyImplementations - Emit information for synthesized
1645/// properties for an implementation.
1646void CodeGenModule::EmitObjCPropertyImplementations(const
1647                                                    ObjCImplementationDecl *D) {
1648  for (ObjCImplementationDecl::propimpl_iterator
1649         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1650    ObjCPropertyImplDecl *PID = *i;
1651
1652    // Dynamic is just for type-checking.
1653    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1654      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1655
1656      // Determine which methods need to be implemented, some may have
1657      // been overridden. Note that ::isSynthesized is not the method
1658      // we want, that just indicates if the decl came from a
1659      // property. What we want to know is if the method is defined in
1660      // this implementation.
1661      if (!D->getInstanceMethod(PD->getGetterName()))
1662        CodeGenFunction(*this).GenerateObjCGetter(
1663                                 const_cast<ObjCImplementationDecl *>(D), PID);
1664      if (!PD->isReadOnly() &&
1665          !D->getInstanceMethod(PD->getSetterName()))
1666        CodeGenFunction(*this).GenerateObjCSetter(
1667                                 const_cast<ObjCImplementationDecl *>(D), PID);
1668    }
1669  }
1670}
1671
1672/// EmitNamespace - Emit all declarations in a namespace.
1673void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1674  for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1675       I != E; ++I)
1676    EmitTopLevelDecl(*I);
1677}
1678
1679// EmitLinkageSpec - Emit all declarations in a linkage spec.
1680void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1681  if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1682      LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1683    ErrorUnsupported(LSD, "linkage spec");
1684    return;
1685  }
1686
1687  for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1688       I != E; ++I)
1689    EmitTopLevelDecl(*I);
1690}
1691
1692/// EmitTopLevelDecl - Emit code for a single top level declaration.
1693void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1694  // If an error has occurred, stop code generation, but continue
1695  // parsing and semantic analysis (to ensure all warnings and errors
1696  // are emitted).
1697  if (Diags.hasErrorOccurred())
1698    return;
1699
1700  // Ignore dependent declarations.
1701  if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1702    return;
1703
1704  switch (D->getKind()) {
1705  case Decl::CXXConversion:
1706  case Decl::CXXMethod:
1707  case Decl::Function:
1708    // Skip function templates
1709    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1710      return;
1711
1712    EmitGlobal(cast<FunctionDecl>(D));
1713    break;
1714
1715  case Decl::Var:
1716    EmitGlobal(cast<VarDecl>(D));
1717    break;
1718
1719  // C++ Decls
1720  case Decl::Namespace:
1721    EmitNamespace(cast<NamespaceDecl>(D));
1722    break;
1723    // No code generation needed.
1724  case Decl::UsingShadow:
1725  case Decl::Using:
1726  case Decl::UsingDirective:
1727  case Decl::ClassTemplate:
1728  case Decl::FunctionTemplate:
1729  case Decl::NamespaceAlias:
1730    break;
1731  case Decl::CXXConstructor:
1732    // Skip function templates
1733    if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1734      return;
1735
1736    EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1737    break;
1738  case Decl::CXXDestructor:
1739    EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1740    break;
1741
1742  case Decl::StaticAssert:
1743    // Nothing to do.
1744    break;
1745
1746  // Objective-C Decls
1747
1748  // Forward declarations, no (immediate) code generation.
1749  case Decl::ObjCClass:
1750  case Decl::ObjCForwardProtocol:
1751  case Decl::ObjCCategory:
1752  case Decl::ObjCInterface:
1753    break;
1754
1755  case Decl::ObjCProtocol:
1756    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1757    break;
1758
1759  case Decl::ObjCCategoryImpl:
1760    // Categories have properties but don't support synthesize so we
1761    // can ignore them here.
1762    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1763    break;
1764
1765  case Decl::ObjCImplementation: {
1766    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1767    EmitObjCPropertyImplementations(OMD);
1768    Runtime->GenerateClass(OMD);
1769    break;
1770  }
1771  case Decl::ObjCMethod: {
1772    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1773    // If this is not a prototype, emit the body.
1774    if (OMD->getBody())
1775      CodeGenFunction(*this).GenerateObjCMethod(OMD);
1776    break;
1777  }
1778  case Decl::ObjCCompatibleAlias:
1779    // compatibility-alias is a directive and has no code gen.
1780    break;
1781
1782  case Decl::LinkageSpec:
1783    EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1784    break;
1785
1786  case Decl::FileScopeAsm: {
1787    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1788    llvm::StringRef AsmString = AD->getAsmString()->getString();
1789
1790    const std::string &S = getModule().getModuleInlineAsm();
1791    if (S.empty())
1792      getModule().setModuleInlineAsm(AsmString);
1793    else
1794      getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
1795    break;
1796  }
1797
1798  default:
1799    // Make sure we handled everything we should, every other kind is a
1800    // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1801    // function. Need to recode Decl::Kind to do that easily.
1802    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1803  }
1804}
1805