CodeGenModule.cpp revision 90a904309c79977fcba2ff0542e2e4cd8e3c3faf
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 "CGDebugInfo.h"
15#include "CodeGenModule.h"
16#include "CodeGenFunction.h"
17#include "CGCall.h"
18#include "CGObjCRuntime.h"
19#include "Mangle.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "llvm/CallingConv.h"
27#include "llvm/Module.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/Target/TargetData.h"
30using namespace clang;
31using namespace CodeGen;
32
33
34CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35                             llvm::Module &M, const llvm::TargetData &TD,
36                             Diagnostic &diags, bool GenerateDebugInfo)
37  : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
38    TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
39    MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
40
41  if (Features.ObjC1) {
42    if (Features.NeXTRuntime) {
43      Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
44                                       : CreateMacObjCRuntime(*this);
45    } else {
46      Runtime = CreateGNUObjCRuntime(*this);
47    }
48  }
49
50  // If debug info generation is enabled, create the CGDebugInfo object.
51  DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
52}
53
54CodeGenModule::~CodeGenModule() {
55  delete Runtime;
56  delete DebugInfo;
57}
58
59void CodeGenModule::Release() {
60  EmitDeferred();
61  EmitAliases();
62  if (Runtime)
63    if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64      AddGlobalCtor(ObjCInitFunction);
65  EmitCtorList(GlobalCtors, "llvm.global_ctors");
66  EmitCtorList(GlobalDtors, "llvm.global_dtors");
67  EmitAnnotations();
68  EmitLLVMUsed();
69  BindRuntimeFunctions();
70}
71
72void CodeGenModule::BindRuntimeFunctions() {
73  // Deal with protecting runtime function names.
74  for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
75    llvm::Function *Fn = RuntimeFunctions[i].first;
76    const std::string &Name = RuntimeFunctions[i].second;
77
78    // Discard unused runtime functions.
79    if (Fn->use_empty()) {
80      Fn->eraseFromParent();
81      continue;
82    }
83
84    // See if there is a conflict against a function.
85    llvm::Function *Conflict = TheModule.getFunction(Name);
86    if (Conflict) {
87      // Decide which version to take. If the conflict is a definition
88      // we are forced to take that, otherwise assume the runtime
89      // knows best.
90      if (!Conflict->isDeclaration()) {
91        llvm::Value *Casted =
92          llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
93        Fn->replaceAllUsesWith(Casted);
94        Fn->eraseFromParent();
95      } else {
96        Fn->takeName(Conflict);
97        llvm::Value *Casted =
98          llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
99        Conflict->replaceAllUsesWith(Casted);
100        Conflict->eraseFromParent();
101      }
102    } else {
103      // FIXME: There still may be conflicts with aliases and
104      // variables.
105      Fn->setName(Name);
106    }
107  }
108}
109
110/// ErrorUnsupported - Print out an error that codegen doesn't support the
111/// specified stmt yet.
112void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
113                                     bool OmitOnError) {
114  if (OmitOnError && getDiags().hasErrorOccurred())
115    return;
116  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
117                                               "cannot compile this %0 yet");
118  std::string Msg = Type;
119  getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
120    << Msg << S->getSourceRange();
121}
122
123/// ErrorUnsupported - Print out an error that codegen doesn't support the
124/// specified decl yet.
125void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
126                                     bool OmitOnError) {
127  if (OmitOnError && getDiags().hasErrorOccurred())
128    return;
129  unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
130                                               "cannot compile this %0 yet");
131  std::string Msg = Type;
132  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
133}
134
135/// setGlobalVisibility - Set the visibility for the given LLVM
136/// GlobalValue according to the given clang AST visibility value.
137static void setGlobalVisibility(llvm::GlobalValue *GV,
138                                VisibilityAttr::VisibilityTypes Vis) {
139  switch (Vis) {
140  default: assert(0 && "Unknown visibility!");
141  case VisibilityAttr::DefaultVisibility:
142    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
143    break;
144  case VisibilityAttr::HiddenVisibility:
145    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
146    break;
147  case VisibilityAttr::ProtectedVisibility:
148    GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
149    break;
150  }
151}
152
153/// \brief Retrieves the mangled name for the given declaration.
154///
155/// If the given declaration requires a mangled name, returns an
156/// IdentifierInfo* containing the mangled name. Otherwise, returns
157/// the name of the declaration as an identifier.
158///
159/// FIXME: Returning an IdentifierInfo* here is a total hack. We
160/// really need some kind of string abstraction that either stores a
161/// mangled name or stores an IdentifierInfo*. This will require
162/// changes to the GlobalDeclMap, too. (I disagree, I think what we
163/// actually need is for Sema to provide some notion of which Decls
164/// refer to the same semantic decl. We shouldn't need to mangle the
165/// names and see what comes out the same to figure this out. - DWD)
166///
167/// FIXME: Performance here is going to be terribly until we start
168/// caching mangled names. However, we should fix the problem above
169/// first.
170const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
171  llvm::SmallString<256> Name;
172  llvm::raw_svector_ostream Out(Name);
173  if (!mangleName(ND, Context, Out))
174    return ND->getIdentifier()->getName();
175
176  Name += '\0';
177  return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
178           .getKeyData();
179}
180
181/// AddGlobalCtor - Add a function to the list that will be called before
182/// main() runs.
183void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
184  // FIXME: Type coercion of void()* types.
185  GlobalCtors.push_back(std::make_pair(Ctor, Priority));
186}
187
188/// AddGlobalDtor - Add a function to the list that will be called
189/// when the module is unloaded.
190void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
191  // FIXME: Type coercion of void()* types.
192  GlobalDtors.push_back(std::make_pair(Dtor, Priority));
193}
194
195void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
196  // Ctor function type is void()*.
197  llvm::FunctionType* CtorFTy =
198    llvm::FunctionType::get(llvm::Type::VoidTy,
199                            std::vector<const llvm::Type*>(),
200                            false);
201  llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
202
203  // Get the type of a ctor entry, { i32, void ()* }.
204  llvm::StructType* CtorStructTy =
205    llvm::StructType::get(llvm::Type::Int32Ty,
206                          llvm::PointerType::getUnqual(CtorFTy), NULL);
207
208  // Construct the constructor and destructor arrays.
209  std::vector<llvm::Constant*> Ctors;
210  for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
211    std::vector<llvm::Constant*> S;
212    S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
213    S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
214    Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
215  }
216
217  if (!Ctors.empty()) {
218    llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
219    new llvm::GlobalVariable(AT, false,
220                             llvm::GlobalValue::AppendingLinkage,
221                             llvm::ConstantArray::get(AT, Ctors),
222                             GlobalName,
223                             &TheModule);
224  }
225}
226
227void CodeGenModule::EmitAnnotations() {
228  if (Annotations.empty())
229    return;
230
231  // Create a new global variable for the ConstantStruct in the Module.
232  llvm::Constant *Array =
233  llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
234                                                Annotations.size()),
235                           Annotations);
236  llvm::GlobalValue *gv =
237  new llvm::GlobalVariable(Array->getType(), false,
238                           llvm::GlobalValue::AppendingLinkage, Array,
239                           "llvm.global.annotations", &TheModule);
240  gv->setSection("llvm.metadata");
241}
242
243void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
244                                             bool IsInternal,
245                                             bool IsInline,
246                                             llvm::GlobalValue *GV,
247                                             bool ForDefinition) {
248  // FIXME: Set up linkage and many other things.  Note, this is a simple
249  // approximation of what we really want.
250  if (!ForDefinition) {
251    // Only a few attributes are set on declarations.
252    if (D->getAttr<DLLImportAttr>()) {
253      // The dllimport attribute is overridden by a subsequent declaration as
254      // dllexport.
255      if (!D->getAttr<DLLExportAttr>()) {
256        // dllimport attribute can be applied only to function decls, not to
257        // definitions.
258        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259          if (!FD->getBody())
260            GV->setLinkage(llvm::Function::DLLImportLinkage);
261        } else
262          GV->setLinkage(llvm::Function::DLLImportLinkage);
263      }
264    } else if (D->getAttr<WeakAttr>())
265      GV->setLinkage(llvm::Function::ExternalWeakLinkage);
266  } else {
267    if (IsInternal) {
268      GV->setLinkage(llvm::Function::InternalLinkage);
269    } else {
270      if (D->getAttr<DLLExportAttr>()) {
271        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
272          // The dllexport attribute is ignored for undefined symbols.
273          if (FD->getBody())
274            GV->setLinkage(llvm::Function::DLLExportLinkage);
275        } else
276          GV->setLinkage(llvm::Function::DLLExportLinkage);
277      } else if (D->getAttr<WeakAttr>() || IsInline)
278        GV->setLinkage(llvm::Function::WeakLinkage);
279    }
280  }
281
282  // FIXME: Figure out the relative priority of the attribute,
283  // -fvisibility, and private_extern.
284  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
285    setGlobalVisibility(GV, attr->getVisibility());
286  // FIXME: else handle -fvisibility
287
288  // Prefaced with special LLVM marker to indicate that the name
289  // should not be munged.
290  if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
291    GV->setName("\01" + ALA->getLabel());
292
293  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
294    GV->setSection(SA->getName());
295
296  // Only add to llvm.used when we see a definition, otherwise we
297  // might add multiple times or risk the value being replaced by a
298  // subsequent RAUW.
299  if (ForDefinition) {
300    if (D->getAttr<UsedAttr>())
301      AddUsedGlobal(GV);
302  }
303}
304
305void CodeGenModule::SetFunctionAttributes(const Decl *D,
306                                          const CGFunctionInfo &Info,
307                                          llvm::Function *F) {
308  AttributeListType AttributeList;
309  ConstructAttributeList(Info, D, AttributeList);
310
311  F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
312                                        AttributeList.size()));
313
314  // Set the appropriate calling convention for the Function.
315  if (D->getAttr<FastCallAttr>())
316    F->setCallingConv(llvm::CallingConv::X86_FastCall);
317
318  if (D->getAttr<StdCallAttr>())
319    F->setCallingConv(llvm::CallingConv::X86_StdCall);
320}
321
322/// SetFunctionAttributesForDefinition - Set function attributes
323/// specific to a function definition.
324void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
325                                                       llvm::Function *F) {
326  if (isa<ObjCMethodDecl>(D)) {
327    SetGlobalValueAttributes(D, true, false, F, true);
328  } else {
329    const FunctionDecl *FD = cast<FunctionDecl>(D);
330    SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
331                             FD->isInline(), F, true);
332  }
333
334  if (!Features.Exceptions && !Features.ObjCNonFragileABI)
335    F->addFnAttr(llvm::Attribute::NoUnwind);
336
337  if (D->getAttr<AlwaysInlineAttr>())
338    F->addFnAttr(llvm::Attribute::AlwaysInline);
339
340  if (D->getAttr<NoinlineAttr>())
341    F->addFnAttr(llvm::Attribute::NoInline);
342}
343
344void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
345                                        llvm::Function *F) {
346  SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
347
348  SetFunctionAttributesForDefinition(MD, F);
349}
350
351void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
352                                          llvm::Function *F) {
353  SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
354
355  SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
356                           FD->isInline(), F, false);
357}
358
359
360void CodeGenModule::EmitAliases() {
361  for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
362    const FunctionDecl *D = Aliases[i];
363    const AliasAttr *AA = D->getAttr<AliasAttr>();
364
365    // This is something of a hack, if the FunctionDecl got overridden
366    // then its attributes will be moved to the new declaration. In
367    // this case the current decl has no alias attribute, but we will
368    // eventually see it.
369    if (!AA)
370      continue;
371
372    const std::string& aliaseeName = AA->getAliasee();
373    llvm::Function *aliasee = getModule().getFunction(aliaseeName);
374    if (!aliasee) {
375      // FIXME: This isn't unsupported, this is just an error, which
376      // sema should catch, but...
377      ErrorUnsupported(D, "alias referencing a missing function");
378      continue;
379    }
380
381    llvm::GlobalValue *GA =
382      new llvm::GlobalAlias(aliasee->getType(),
383                            llvm::Function::ExternalLinkage,
384                            getMangledName(D), aliasee,
385                            &getModule());
386
387    llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
388    if (Entry) {
389      // If we created a dummy function for this then replace it.
390      GA->takeName(Entry);
391
392      llvm::Value *Casted =
393        llvm::ConstantExpr::getBitCast(GA, Entry->getType());
394      Entry->replaceAllUsesWith(Casted);
395      Entry->eraseFromParent();
396
397      Entry = GA;
398    }
399
400    // Alias should never be internal or inline.
401    SetGlobalValueAttributes(D, false, false, GA, true);
402  }
403}
404
405void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
406  assert(!GV->isDeclaration() &&
407         "Only globals with definition can force usage.");
408  llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
409  LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
410}
411
412void CodeGenModule::EmitLLVMUsed() {
413  // Don't create llvm.used if there is no need.
414  if (LLVMUsed.empty())
415    return;
416
417  llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
418                                              LLVMUsed.size());
419  llvm::GlobalVariable *GV =
420    new llvm::GlobalVariable(ATy, false,
421                             llvm::GlobalValue::AppendingLinkage,
422                             llvm::ConstantArray::get(ATy, LLVMUsed),
423                             "llvm.used", &getModule());
424
425  GV->setSection("llvm.metadata");
426}
427
428void CodeGenModule::EmitDeferred() {
429  // Emit code for any deferred decl which was used.  Since a
430  // previously unused static decl may become used during the
431  // generation of code for a static function, iterate until no
432  // changes are made.
433  bool Changed;
434  do {
435    Changed = false;
436
437    for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
438         e = DeferredDecls.end(); i != e; ) {
439      const ValueDecl *D = *i;
440
441      // Check if we have used a decl with the same name
442      // FIXME: The AST should have some sort of aggregate decls or
443      // global symbol map.
444      // FIXME: This is missing some important cases. For example, we
445      // need to check for uses in an alias.
446      if (!GlobalDeclMap.count(getMangledName(D))) {
447        ++i;
448        continue;
449      }
450
451      // Emit the definition.
452      EmitGlobalDefinition(D);
453
454      // Erase the used decl from the list.
455      i = DeferredDecls.erase(i);
456
457      // Remember that we made a change.
458      Changed = true;
459    }
460  } while (Changed);
461}
462
463/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
464/// annotation information for a given GlobalValue.  The annotation struct is
465/// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
466/// GlobalValue being annotated.  The second field is the constant string
467/// created from the AnnotateAttr's annotation.  The third field is a constant
468/// string containing the name of the translation unit.  The fourth field is
469/// the line number in the file of the annotated value declaration.
470///
471/// FIXME: this does not unique the annotation string constants, as llvm-gcc
472///        appears to.
473///
474llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
475                                                const AnnotateAttr *AA,
476                                                unsigned LineNo) {
477  llvm::Module *M = &getModule();
478
479  // get [N x i8] constants for the annotation string, and the filename string
480  // which are the 2nd and 3rd elements of the global annotation structure.
481  const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
482  llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
483  llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
484                                                  true);
485
486  // Get the two global values corresponding to the ConstantArrays we just
487  // created to hold the bytes of the strings.
488  llvm::GlobalValue *annoGV =
489  new llvm::GlobalVariable(anno->getType(), false,
490                           llvm::GlobalValue::InternalLinkage, anno,
491                           GV->getName() + ".str", M);
492  // translation unit name string, emitted into the llvm.metadata section.
493  llvm::GlobalValue *unitGV =
494  new llvm::GlobalVariable(unit->getType(), false,
495                           llvm::GlobalValue::InternalLinkage, unit, ".str", M);
496
497  // Create the ConstantStruct that is the global annotion.
498  llvm::Constant *Fields[4] = {
499    llvm::ConstantExpr::getBitCast(GV, SBP),
500    llvm::ConstantExpr::getBitCast(annoGV, SBP),
501    llvm::ConstantExpr::getBitCast(unitGV, SBP),
502    llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
503  };
504  return llvm::ConstantStruct::get(Fields, 4, false);
505}
506
507bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
508  // Never defer when EmitAllDecls is specified or the decl has
509  // attribute used.
510  if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
511    return false;
512
513  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
514    // Constructors and destructors should never be deferred.
515    if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
516      return false;
517
518    if (FD->getStorageClass() != FunctionDecl::Static)
519      return false;
520  } else {
521    const VarDecl *VD = cast<VarDecl>(Global);
522    assert(VD->isFileVarDecl() && "Invalid decl.");
523
524    if (VD->getStorageClass() != VarDecl::Static)
525      return false;
526  }
527
528  return true;
529}
530
531void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
532  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
533    // Aliases are deferred until code for everything else has been
534    // emitted.
535    if (FD->getAttr<AliasAttr>()) {
536      assert(!FD->isThisDeclarationADefinition() &&
537             "Function alias cannot have a definition!");
538      Aliases.push_back(FD);
539      return;
540    }
541
542    // Forward declarations are emitted lazily on first use.
543    if (!FD->isThisDeclarationADefinition())
544      return;
545  } else {
546    const VarDecl *VD = cast<VarDecl>(Global);
547    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
548
549    // Forward declarations are emitted lazily on first use.
550    if (!VD->getInit() && VD->hasExternalStorage())
551      return;
552  }
553
554  // Defer code generation when possible.
555  if (MayDeferGeneration(Global)) {
556    DeferredDecls.push_back(Global);
557    return;
558  }
559
560  // Otherwise emit the definition.
561  EmitGlobalDefinition(Global);
562}
563
564void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
565  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
566    EmitGlobalFunctionDefinition(FD);
567  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
568    EmitGlobalVarDefinition(VD);
569  } else {
570    assert(0 && "Invalid argument to EmitGlobalDefinition()");
571  }
572}
573
574 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
575  assert(D->hasGlobalStorage() && "Not a global variable");
576
577  QualType ASTTy = D->getType();
578  const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
579  const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
580
581  // Lookup the entry, lazily creating it if necessary.
582  llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
583  if (!Entry) {
584    llvm::GlobalVariable *GV =
585      new llvm::GlobalVariable(Ty, false,
586                               llvm::GlobalValue::ExternalLinkage,
587                               0, getMangledName(D), &getModule(),
588                               0, ASTTy.getAddressSpace());
589    Entry = GV;
590
591    // Handle things which are present even on external declarations.
592
593    // FIXME: This code is overly simple and should be merged with
594    // other global handling.
595
596    GV->setConstant(D->getType().isConstant(Context));
597
598    // FIXME: Merge with other attribute handling code.
599
600    if (D->getStorageClass() == VarDecl::PrivateExtern)
601      setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
602
603    if (D->getAttr<WeakAttr>())
604      GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
605
606    if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
607      // Prefaced with special LLVM marker to indicate that the name
608      // should not be munged.
609      GV->setName("\01" + ALA->getLabel());
610    }
611  }
612
613  // Make sure the result is of the correct type.
614  return llvm::ConstantExpr::getBitCast(Entry, PTy);
615}
616
617void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
618  llvm::Constant *Init = 0;
619  QualType ASTTy = D->getType();
620  const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
621
622  if (D->getInit() == 0) {
623    // This is a tentative definition; tentative definitions are
624    // implicitly initialized with { 0 }
625    const llvm::Type* InitTy;
626    if (ASTTy->isIncompleteArrayType()) {
627      // An incomplete array is normally [ TYPE x 0 ], but we need
628      // to fix it to [ TYPE x 1 ].
629      const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
630      InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
631    } else {
632      InitTy = VarTy;
633    }
634    Init = llvm::Constant::getNullValue(InitTy);
635  } else {
636    Init = EmitConstantExpr(D->getInit());
637    if (!Init) {
638      ErrorUnsupported(D, "static initializer");
639      QualType T = D->getInit()->getType();
640      Init = llvm::UndefValue::get(getTypes().ConvertType(T));
641    }
642  }
643  const llvm::Type* InitType = Init->getType();
644
645  llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
646  llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
647
648  if (!GV) {
649    GV = new llvm::GlobalVariable(InitType, false,
650                                  llvm::GlobalValue::ExternalLinkage,
651                                  0, getMangledName(D),
652                                  &getModule(), 0, ASTTy.getAddressSpace());
653
654  } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
655    // If we already have this global and it has an initializer, then
656    // we are in the rare situation where we emitted the defining
657    // declaration of the global and are now being asked to emit a
658    // definition which would be common. This occurs, for example, in
659    // the following situation because statics can be emitted out of
660    // order:
661    //
662    //  static int x;
663    //  static int *y = &x;
664    //  static int x = 10;
665    //  int **z = &y;
666    //
667    // Bail here so we don't blow away the definition. Note that if we
668    // can't distinguish here if we emitted a definition with a null
669    // initializer, but this case is safe.
670    assert(!D->getInit() && "Emitting multiple definitions of a decl!");
671    return;
672
673  } else if (GV->getType() !=
674             llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
675    // We have a definition after a prototype with the wrong type.
676    // We must make a new GlobalVariable* and update everything that used OldGV
677    // (a declaration or tentative definition) with the new GlobalVariable*
678    // (which will be a definition).
679    //
680    // This happens if there is a prototype for a global (e.g. "extern int x[];")
681    // and then a definition of a different type (e.g. "int x[10];"). This also
682    // happens when an initializer has a different type from the type of the
683    // global (this happens with unions).
684    //
685    // FIXME: This also ends up happening if there's a definition followed by
686    // a tentative definition!  (Although Sema rejects that construct
687    // at the moment.)
688
689    // Save the old global
690    llvm::GlobalVariable *OldGV = GV;
691
692    // Make a new global with the correct type
693    GV = new llvm::GlobalVariable(InitType, false,
694                                  llvm::GlobalValue::ExternalLinkage,
695                                  0, getMangledName(D),
696                                  &getModule(), 0, ASTTy.getAddressSpace());
697    // Steal the name of the old global
698    GV->takeName(OldGV);
699
700    // Replace all uses of the old global with the new global
701    llvm::Constant *NewPtrForOldDecl =
702        llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
703    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
704
705    // Erase the old global, since it is no longer used.
706    OldGV->eraseFromParent();
707  }
708
709  Entry = GV;
710
711  if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
712    SourceManager &SM = Context.getSourceManager();
713    AddAnnotation(EmitAnnotateAttr(GV, AA,
714                              SM.getInstantiationLineNumber(D->getLocation())));
715  }
716
717  GV->setInitializer(Init);
718  GV->setConstant(D->getType().isConstant(Context));
719  GV->setAlignment(getContext().getDeclAlignInBytes(D));
720
721  if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
722    setGlobalVisibility(GV, attr->getVisibility());
723  // FIXME: else handle -fvisibility
724
725  if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
726    // Prefaced with special LLVM marker to indicate that the name
727    // should not be munged.
728    GV->setName("\01" + ALA->getLabel());
729  }
730
731  // Set the llvm linkage type as appropriate.
732  if (D->getStorageClass() == VarDecl::Static)
733    GV->setLinkage(llvm::Function::InternalLinkage);
734  else if (D->getAttr<DLLImportAttr>())
735    GV->setLinkage(llvm::Function::DLLImportLinkage);
736  else if (D->getAttr<DLLExportAttr>())
737    GV->setLinkage(llvm::Function::DLLExportLinkage);
738  else if (D->getAttr<WeakAttr>())
739    GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
740  else {
741    // FIXME: This isn't right.  This should handle common linkage and other
742    // stuff.
743    switch (D->getStorageClass()) {
744    case VarDecl::Static: assert(0 && "This case handled above");
745    case VarDecl::Auto:
746    case VarDecl::Register:
747      assert(0 && "Can't have auto or register globals");
748    case VarDecl::None:
749      if (!D->getInit())
750        GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
751      else
752        GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
753      break;
754    case VarDecl::Extern:
755      // FIXME: common
756      break;
757
758    case VarDecl::PrivateExtern:
759      GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
760      // FIXME: common
761      break;
762    }
763  }
764
765  if (const SectionAttr *SA = D->getAttr<SectionAttr>())
766    GV->setSection(SA->getName());
767
768  if (D->getAttr<UsedAttr>())
769    AddUsedGlobal(GV);
770
771  // Emit global variable debug information.
772  CGDebugInfo *DI = getDebugInfo();
773  if(DI) {
774    DI->setLocation(D->getLocation());
775    DI->EmitGlobalVariable(GV, D);
776  }
777}
778
779llvm::GlobalValue *
780CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
781                                             const llvm::Type *Ty) {
782  if (!Ty)
783    Ty = getTypes().ConvertType(D->getType());
784  llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
785                                             llvm::Function::ExternalLinkage,
786                                             getMangledName(D),
787                                             &getModule());
788  SetFunctionAttributes(D, F);
789  return F;
790}
791
792llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
793  QualType ASTTy = D->getType();
794  const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
795  const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
796
797  // Lookup the entry, lazily creating it if necessary.
798  llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
799  if (!Entry)
800    Entry = EmitForwardFunctionDefinition(D, 0);
801
802  return llvm::ConstantExpr::getBitCast(Entry, PTy);
803}
804
805void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
806  const llvm::FunctionType *Ty =
807    cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
808
809  // As a special case, make sure that definitions of K&R function
810  // "type foo()" aren't declared as varargs (which forces the backend
811  // to do unnecessary work).
812  if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
813    Ty = llvm::FunctionType::get(Ty->getReturnType(),
814                                 std::vector<const llvm::Type*>(),
815                                 false);
816
817  llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
818  if (!Entry) {
819    Entry = EmitForwardFunctionDefinition(D, Ty);
820  } else {
821    // If the types mismatch then we have to rewrite the definition.
822    if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
823      // Otherwise, we have a definition after a prototype with the
824      // wrong type.  F is the Function* for the one with the wrong
825      // type, we must make a new Function* and update everything that
826      // used F (a declaration) with the new Function* (which will be
827      // a definition).
828      //
829      // This happens if there is a prototype for a function
830      // (e.g. "int f()") and then a definition of a different type
831      // (e.g. "int f(int x)").  Start by making a new function of the
832      // correct type, RAUW, then steal the name.
833      llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
834      NewFn->takeName(Entry);
835
836      // Replace uses of F with the Function we will endow with a body.
837      llvm::Constant *NewPtrForOldDecl =
838        llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
839      Entry->replaceAllUsesWith(NewPtrForOldDecl);
840
841      // Ok, delete the old function now, which is dead.
842      assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
843      Entry->eraseFromParent();
844
845      Entry = NewFn;
846    }
847  }
848
849  llvm::Function *Fn = cast<llvm::Function>(Entry);
850  CodeGenFunction(*this).GenerateCode(D, Fn);
851
852  SetFunctionAttributesForDefinition(D, Fn);
853
854  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
855    AddGlobalCtor(Fn, CA->getPriority());
856  } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
857    AddGlobalDtor(Fn, DA->getPriority());
858  }
859}
860
861llvm::Function *
862CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
863                                     const std::string &Name) {
864  llvm::Function *Fn = llvm::Function::Create(FTy,
865                                              llvm::Function::ExternalLinkage,
866                                              "", &TheModule);
867  RuntimeFunctions.push_back(std::make_pair(Fn, Name));
868  return Fn;
869}
870
871void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
872  // Make sure that this type is translated.
873  Types.UpdateCompletedType(TD);
874}
875
876
877/// getBuiltinLibFunction
878llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
879  if (BuiltinID > BuiltinFunctions.size())
880    BuiltinFunctions.resize(BuiltinID);
881
882  // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
883  // a slot for it.
884  assert(BuiltinID && "Invalid Builtin ID");
885  llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
886  if (FunctionSlot)
887    return FunctionSlot;
888
889  assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
890          Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
891         "isn't a lib fn");
892
893  // Get the name, skip over the __builtin_ prefix (if necessary).
894  const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
895  if (Context.BuiltinInfo.isLibFunction(BuiltinID))
896    Name += 10;
897
898  // Get the type for the builtin.
899  Builtin::Context::GetBuiltinTypeError Error;
900  QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
901  assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
902
903  const llvm::FunctionType *Ty =
904    cast<llvm::FunctionType>(getTypes().ConvertType(Type));
905
906  // FIXME: This has a serious problem with code like this:
907  //  void abs() {}
908  //    ... __builtin_abs(x);
909  // The two versions of abs will collide.  The fix is for the builtin to win,
910  // and for the existing one to be turned into a constantexpr cast of the
911  // builtin.  In the case where the existing one is a static function, it
912  // should just be renamed.
913  if (llvm::Function *Existing = getModule().getFunction(Name)) {
914    if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
915      return FunctionSlot = Existing;
916    assert(Existing == 0 && "FIXME: Name collision");
917  }
918
919  llvm::GlobalValue *&ExistingFn =
920    GlobalDeclMap[getContext().Idents.get(Name).getName()];
921  if (ExistingFn)
922    return FunctionSlot = llvm::ConstantExpr::getBitCast(ExistingFn, Ty);
923
924  // FIXME: param attributes for sext/zext etc.
925  return FunctionSlot = ExistingFn =
926    llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
927                           &getModule());
928}
929
930llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
931                                            unsigned NumTys) {
932  return llvm::Intrinsic::getDeclaration(&getModule(),
933                                         (llvm::Intrinsic::ID)IID, Tys, NumTys);
934}
935
936llvm::Function *CodeGenModule::getMemCpyFn() {
937  if (MemCpyFn) return MemCpyFn;
938  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
939  return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
940}
941
942llvm::Function *CodeGenModule::getMemMoveFn() {
943  if (MemMoveFn) return MemMoveFn;
944  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
945  return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
946}
947
948llvm::Function *CodeGenModule::getMemSetFn() {
949  if (MemSetFn) return MemSetFn;
950  const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
951  return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
952}
953
954static void appendFieldAndPadding(CodeGenModule &CGM,
955                                  std::vector<llvm::Constant*>& Fields,
956                                  FieldDecl *FieldD, FieldDecl *NextFieldD,
957                                  llvm::Constant* Field,
958                                  RecordDecl* RD, const llvm::StructType *STy)
959{
960  // Append the field.
961  Fields.push_back(Field);
962
963  int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
964
965  int NextStructFieldNo;
966  if (!NextFieldD) {
967    NextStructFieldNo = STy->getNumElements();
968  } else {
969    NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
970  }
971
972  // Append padding
973  for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
974    llvm::Constant *C =
975      llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
976
977    Fields.push_back(C);
978  }
979}
980
981// We still need to work out the details of handling UTF-16.
982// See: <rdr://2996215>
983llvm::Constant *CodeGenModule::
984GetAddrOfConstantCFString(const std::string &str) {
985  llvm::StringMapEntry<llvm::Constant *> &Entry =
986    CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
987
988  if (Entry.getValue())
989    return Entry.getValue();
990
991  llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
992  llvm::Constant *Zeros[] = { Zero, Zero };
993
994  if (!CFConstantStringClassRef) {
995    const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
996    Ty = llvm::ArrayType::get(Ty, 0);
997
998    // FIXME: This is fairly broken if
999    // __CFConstantStringClassReference is already defined, in that it
1000    // will get renamed and the user will most likely see an opaque
1001    // error message. This is a general issue with relying on
1002    // particular names.
1003    llvm::GlobalVariable *GV =
1004      new llvm::GlobalVariable(Ty, false,
1005                               llvm::GlobalVariable::ExternalLinkage, 0,
1006                               "__CFConstantStringClassReference",
1007                               &getModule());
1008
1009    // Decay array -> ptr
1010    CFConstantStringClassRef =
1011      llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1012  }
1013
1014  QualType CFTy = getContext().getCFConstantStringType();
1015  RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
1016
1017  const llvm::StructType *STy =
1018    cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1019
1020  std::vector<llvm::Constant*> Fields;
1021  RecordDecl::field_iterator Field = CFRD->field_begin();
1022
1023  // Class pointer.
1024  FieldDecl *CurField = *Field++;
1025  FieldDecl *NextField = *Field++;
1026  appendFieldAndPadding(*this, Fields, CurField, NextField,
1027                        CFConstantStringClassRef, CFRD, STy);
1028
1029  // Flags.
1030  CurField = NextField;
1031  NextField = *Field++;
1032  const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1033  appendFieldAndPadding(*this, Fields, CurField, NextField,
1034                        llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
1035
1036  // String pointer.
1037  CurField = NextField;
1038  NextField = *Field++;
1039  llvm::Constant *C = llvm::ConstantArray::get(str);
1040  C = new llvm::GlobalVariable(C->getType(), true,
1041                               llvm::GlobalValue::InternalLinkage,
1042                               C, ".str", &getModule());
1043  appendFieldAndPadding(*this, Fields, CurField, NextField,
1044                        llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1045                        CFRD, STy);
1046
1047  // String length.
1048  CurField = NextField;
1049  NextField = 0;
1050  Ty = getTypes().ConvertType(getContext().LongTy);
1051  appendFieldAndPadding(*this, Fields, CurField, NextField,
1052                        llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
1053
1054  // The struct.
1055  C = llvm::ConstantStruct::get(STy, Fields);
1056  llvm::GlobalVariable *GV =
1057    new llvm::GlobalVariable(C->getType(), true,
1058                             llvm::GlobalVariable::InternalLinkage,
1059                             C, "", &getModule());
1060
1061  GV->setSection("__DATA,__cfstring");
1062  Entry.setValue(GV);
1063
1064  return GV;
1065}
1066
1067/// GetStringForStringLiteral - Return the appropriate bytes for a
1068/// string literal, properly padded to match the literal type.
1069std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1070  const char *StrData = E->getStrData();
1071  unsigned Len = E->getByteLength();
1072
1073  const ConstantArrayType *CAT =
1074    getContext().getAsConstantArrayType(E->getType());
1075  assert(CAT && "String isn't pointer or array!");
1076
1077  // Resize the string to the right size.
1078  std::string Str(StrData, StrData+Len);
1079  uint64_t RealLen = CAT->getSize().getZExtValue();
1080
1081  if (E->isWide())
1082    RealLen *= getContext().Target.getWCharWidth()/8;
1083
1084  Str.resize(RealLen, '\0');
1085
1086  return Str;
1087}
1088
1089/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1090/// constant array for the given string literal.
1091llvm::Constant *
1092CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1093  // FIXME: This can be more efficient.
1094  return GetAddrOfConstantString(GetStringForStringLiteral(S));
1095}
1096
1097/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1098/// array for the given ObjCEncodeExpr node.
1099llvm::Constant *
1100CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1101  std::string Str;
1102  getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1103
1104  llvm::Constant *C = llvm::ConstantArray::get(Str);
1105  C = new llvm::GlobalVariable(C->getType(), true,
1106                               llvm::GlobalValue::InternalLinkage,
1107                               C, ".str", &getModule());
1108  return C;
1109}
1110
1111
1112/// GenerateWritableString -- Creates storage for a string literal.
1113static llvm::Constant *GenerateStringLiteral(const std::string &str,
1114                                             bool constant,
1115                                             CodeGenModule &CGM,
1116                                             const char *GlobalName) {
1117  // Create Constant for this string literal. Don't add a '\0'.
1118  llvm::Constant *C = llvm::ConstantArray::get(str, false);
1119
1120  // Create a global variable for this string
1121  return new llvm::GlobalVariable(C->getType(), constant,
1122                                  llvm::GlobalValue::InternalLinkage,
1123                                  C, GlobalName ? GlobalName : ".str",
1124                                  &CGM.getModule());
1125}
1126
1127/// GetAddrOfConstantString - Returns a pointer to a character array
1128/// containing the literal. This contents are exactly that of the
1129/// given string, i.e. it will not be null terminated automatically;
1130/// see GetAddrOfConstantCString. Note that whether the result is
1131/// actually a pointer to an LLVM constant depends on
1132/// Feature.WriteableStrings.
1133///
1134/// The result has pointer to array type.
1135llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1136                                                       const char *GlobalName) {
1137  // Don't share any string literals if writable-strings is turned on.
1138  if (Features.WritableStrings)
1139    return GenerateStringLiteral(str, false, *this, GlobalName);
1140
1141  llvm::StringMapEntry<llvm::Constant *> &Entry =
1142  ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1143
1144  if (Entry.getValue())
1145    return Entry.getValue();
1146
1147  // Create a global variable for this.
1148  llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1149  Entry.setValue(C);
1150  return C;
1151}
1152
1153/// GetAddrOfConstantCString - Returns a pointer to a character
1154/// array containing the literal and a terminating '\-'
1155/// character. The result has pointer to array type.
1156llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1157                                                        const char *GlobalName){
1158  return GetAddrOfConstantString(str + '\0', GlobalName);
1159}
1160
1161/// EmitObjCPropertyImplementations - Emit information for synthesized
1162/// properties for an implementation.
1163void CodeGenModule::EmitObjCPropertyImplementations(const
1164                                                    ObjCImplementationDecl *D) {
1165  for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1166         e = D->propimpl_end(); i != e; ++i) {
1167    ObjCPropertyImplDecl *PID = *i;
1168
1169    // Dynamic is just for type-checking.
1170    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1171      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1172
1173      // Determine which methods need to be implemented, some may have
1174      // been overridden. Note that ::isSynthesized is not the method
1175      // we want, that just indicates if the decl came from a
1176      // property. What we want to know is if the method is defined in
1177      // this implementation.
1178      if (!D->getInstanceMethod(PD->getGetterName()))
1179        CodeGenFunction(*this).GenerateObjCGetter(
1180                                 const_cast<ObjCImplementationDecl *>(D), PID);
1181      if (!PD->isReadOnly() &&
1182          !D->getInstanceMethod(PD->getSetterName()))
1183        CodeGenFunction(*this).GenerateObjCSetter(
1184                                 const_cast<ObjCImplementationDecl *>(D), PID);
1185    }
1186  }
1187}
1188
1189/// EmitTopLevelDecl - Emit code for a single top level declaration.
1190void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1191  // If an error has occurred, stop code generation, but continue
1192  // parsing and semantic analysis (to ensure all warnings and errors
1193  // are emitted).
1194  if (Diags.hasErrorOccurred())
1195    return;
1196
1197  switch (D->getKind()) {
1198  case Decl::Function:
1199  case Decl::Var:
1200    EmitGlobal(cast<ValueDecl>(D));
1201    break;
1202
1203  case Decl::Namespace:
1204    ErrorUnsupported(D, "namespace");
1205    break;
1206
1207    // Objective-C Decls
1208
1209    // Forward declarations, no (immediate) code generation.
1210  case Decl::ObjCClass:
1211  case Decl::ObjCCategory:
1212  case Decl::ObjCForwardProtocol:
1213  case Decl::ObjCInterface:
1214    break;
1215
1216  case Decl::ObjCProtocol:
1217    Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1218    break;
1219
1220  case Decl::ObjCCategoryImpl:
1221    // Categories have properties but don't support synthesize so we
1222    // can ignore them here.
1223
1224    Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1225    break;
1226
1227  case Decl::ObjCImplementation: {
1228    ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1229    EmitObjCPropertyImplementations(OMD);
1230    Runtime->GenerateClass(OMD);
1231    break;
1232  }
1233  case Decl::ObjCMethod: {
1234    ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1235    // If this is not a prototype, emit the body.
1236    if (OMD->getBody())
1237      CodeGenFunction(*this).GenerateObjCMethod(OMD);
1238    break;
1239  }
1240  case Decl::ObjCCompatibleAlias:
1241    // compatibility-alias is a directive and has no code gen.
1242    break;
1243
1244  case Decl::LinkageSpec: {
1245    LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1246    if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
1247      ErrorUnsupported(LSD, "linkage spec");
1248    // FIXME: implement C++ linkage, C linkage works mostly by C
1249    // language reuse already.
1250    break;
1251  }
1252
1253  case Decl::FileScopeAsm: {
1254    FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1255    std::string AsmString(AD->getAsmString()->getStrData(),
1256                          AD->getAsmString()->getByteLength());
1257
1258    const std::string &S = getModule().getModuleInlineAsm();
1259    if (S.empty())
1260      getModule().setModuleInlineAsm(AsmString);
1261    else
1262      getModule().setModuleInlineAsm(S + '\n' + AsmString);
1263    break;
1264  }
1265
1266  default:
1267    // Make sure we handled everything we should, every other kind is
1268    // a non-top-level decl.  FIXME: Would be nice to have an
1269    // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1270    // that easily.
1271    assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1272  }
1273}
1274