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