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