xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 87590e60c088355ed0227da12f0ca04928b1e28f)
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 "CodeGenTBAA.h"
18 #include "CGCall.h"
19 #include "CGCUDARuntime.h"
20 #include "CGCXXABI.h"
21 #include "CGObjCRuntime.h"
22 #include "CGOpenCLRuntime.h"
23 #include "TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclCXX.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/RecordLayout.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/Diagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include "llvm/CallingConv.h"
39 #include "llvm/Module.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ErrorHandling.h"
48 using namespace clang;
49 using namespace CodeGen;
50 
51 static const char AnnotationSection[] = "llvm.metadata";
52 
53 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
54   switch (CGM.getContext().getTargetInfo().getCXXABI()) {
55   case CXXABI_ARM: return *CreateARMCXXABI(CGM);
56   case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
57   case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
58   }
59 
60   llvm_unreachable("invalid C++ ABI kind");
61 }
62 
63 
64 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
65                              llvm::Module &M, const llvm::TargetData &TD,
66                              DiagnosticsEngine &diags)
67   : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
68     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
69     ABI(createCXXABI(*this)),
70     Types(*this),
71     TBAA(0),
72     VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
73     DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
74     RRData(0), CFConstantStringClassRef(0),
75     ConstantStringClassRef(0), NSConstantStringType(0),
76     VMContext(M.getContext()),
77     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
78     BlockObjectAssign(0), BlockObjectDispose(0),
79     BlockDescriptorType(0), GenericBlockLiteralType(0) {
80 
81   // Initialize the type cache.
82   llvm::LLVMContext &LLVMContext = M.getContext();
83   VoidTy = llvm::Type::getVoidTy(LLVMContext);
84   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
85   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
86   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
87   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
88   FloatTy = llvm::Type::getFloatTy(LLVMContext);
89   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
90   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
91   PointerAlignInBytes =
92   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
93   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
94   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
95   Int8PtrTy = Int8Ty->getPointerTo(0);
96   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
97 
98   if (LangOpts.ObjC1)
99     createObjCRuntime();
100   if (LangOpts.OpenCL)
101     createOpenCLRuntime();
102   if (LangOpts.CUDA)
103     createCUDARuntime();
104 
105   // Enable TBAA unless it's suppressed.
106   if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
107     TBAA = new CodeGenTBAA(Context, VMContext, getLangOpts(),
108                            ABI.getMangleContext());
109 
110   // If debug info or coverage generation is enabled, create the CGDebugInfo
111   // object.
112   if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
113       CodeGenOpts.EmitGcovNotes)
114     DebugInfo = new CGDebugInfo(*this);
115 
116   Block.GlobalUniqueCount = 0;
117 
118   if (C.getLangOpts().ObjCAutoRefCount)
119     ARCData = new ARCEntrypoints();
120   RRData = new RREntrypoints();
121 }
122 
123 CodeGenModule::~CodeGenModule() {
124   delete ObjCRuntime;
125   delete OpenCLRuntime;
126   delete CUDARuntime;
127   delete TheTargetCodeGenInfo;
128   delete &ABI;
129   delete TBAA;
130   delete DebugInfo;
131   delete ARCData;
132   delete RRData;
133 }
134 
135 void CodeGenModule::createObjCRuntime() {
136   if (!LangOpts.NeXTRuntime)
137     ObjCRuntime = CreateGNUObjCRuntime(*this);
138   else
139     ObjCRuntime = CreateMacObjCRuntime(*this);
140 }
141 
142 void CodeGenModule::createOpenCLRuntime() {
143   OpenCLRuntime = new CGOpenCLRuntime(*this);
144 }
145 
146 void CodeGenModule::createCUDARuntime() {
147   CUDARuntime = CreateNVCUDARuntime(*this);
148 }
149 
150 void CodeGenModule::Release() {
151   EmitDeferred();
152   EmitCXXGlobalInitFunc();
153   EmitCXXGlobalDtorFunc();
154   if (ObjCRuntime)
155     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
156       AddGlobalCtor(ObjCInitFunction);
157   EmitCtorList(GlobalCtors, "llvm.global_ctors");
158   EmitCtorList(GlobalDtors, "llvm.global_dtors");
159   EmitGlobalAnnotations();
160   EmitLLVMUsed();
161 
162   SimplifyPersonality();
163 
164   if (getCodeGenOpts().EmitDeclMetadata)
165     EmitDeclMetadata();
166 
167   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
168     EmitCoverageFile();
169 
170   if (DebugInfo)
171     DebugInfo->finalize();
172 }
173 
174 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
175   // Make sure that this type is translated.
176   Types.UpdateCompletedType(TD);
177 }
178 
179 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
180   if (!TBAA)
181     return 0;
182   return TBAA->getTBAAInfo(QTy);
183 }
184 
185 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
186   if (!TBAA)
187     return 0;
188   return TBAA->getTBAAInfoForVTablePtr();
189 }
190 
191 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
192                                         llvm::MDNode *TBAAInfo) {
193   Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
194 }
195 
196 bool CodeGenModule::isTargetDarwin() const {
197   return getContext().getTargetInfo().getTriple().isOSDarwin();
198 }
199 
200 void CodeGenModule::Error(SourceLocation loc, const Twine &error) {
201   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
202                                                error.str());
203   getDiags().Report(Context.getFullLoc(loc), diagID);
204 }
205 
206 /// ErrorUnsupported - Print out an error that codegen doesn't support the
207 /// specified stmt yet.
208 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
209                                      bool OmitOnError) {
210   if (OmitOnError && getDiags().hasErrorOccurred())
211     return;
212   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
213                                                "cannot compile this %0 yet");
214   std::string Msg = Type;
215   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
216     << Msg << S->getSourceRange();
217 }
218 
219 /// ErrorUnsupported - Print out an error that codegen doesn't support the
220 /// specified decl yet.
221 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
222                                      bool OmitOnError) {
223   if (OmitOnError && getDiags().hasErrorOccurred())
224     return;
225   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
226                                                "cannot compile this %0 yet");
227   std::string Msg = Type;
228   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
229 }
230 
231 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
232   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
233 }
234 
235 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
236                                         const NamedDecl *D) const {
237   // Internal definitions always have default visibility.
238   if (GV->hasLocalLinkage()) {
239     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
240     return;
241   }
242 
243   // Set visibility for definitions.
244   NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
245   if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
246     GV->setVisibility(GetLLVMVisibility(LV.visibility()));
247 }
248 
249 /// Set the symbol visibility of type information (vtable and RTTI)
250 /// associated with the given type.
251 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
252                                       const CXXRecordDecl *RD,
253                                       TypeVisibilityKind TVK) const {
254   setGlobalVisibility(GV, RD);
255 
256   if (!CodeGenOpts.HiddenWeakVTables)
257     return;
258 
259   // We never want to drop the visibility for RTTI names.
260   if (TVK == TVK_ForRTTIName)
261     return;
262 
263   // We want to drop the visibility to hidden for weak type symbols.
264   // This isn't possible if there might be unresolved references
265   // elsewhere that rely on this symbol being visible.
266 
267   // This should be kept roughly in sync with setThunkVisibility
268   // in CGVTables.cpp.
269 
270   // Preconditions.
271   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
272       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
273     return;
274 
275   // Don't override an explicit visibility attribute.
276   if (RD->getExplicitVisibility())
277     return;
278 
279   switch (RD->getTemplateSpecializationKind()) {
280   // We have to disable the optimization if this is an EI definition
281   // because there might be EI declarations in other shared objects.
282   case TSK_ExplicitInstantiationDefinition:
283   case TSK_ExplicitInstantiationDeclaration:
284     return;
285 
286   // Every use of a non-template class's type information has to emit it.
287   case TSK_Undeclared:
288     break;
289 
290   // In theory, implicit instantiations can ignore the possibility of
291   // an explicit instantiation declaration because there necessarily
292   // must be an EI definition somewhere with default visibility.  In
293   // practice, it's possible to have an explicit instantiation for
294   // an arbitrary template class, and linkers aren't necessarily able
295   // to deal with mixed-visibility symbols.
296   case TSK_ExplicitSpecialization:
297   case TSK_ImplicitInstantiation:
298     if (!CodeGenOpts.HiddenWeakTemplateVTables)
299       return;
300     break;
301   }
302 
303   // If there's a key function, there may be translation units
304   // that don't have the key function's definition.  But ignore
305   // this if we're emitting RTTI under -fno-rtti.
306   if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
307     if (Context.getKeyFunction(RD))
308       return;
309   }
310 
311   // Otherwise, drop the visibility to hidden.
312   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
313   GV->setUnnamedAddr(true);
314 }
315 
316 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
317   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
318 
319   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
320   if (!Str.empty())
321     return Str;
322 
323   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
324     IdentifierInfo *II = ND->getIdentifier();
325     assert(II && "Attempt to mangle unnamed decl.");
326 
327     Str = II->getName();
328     return Str;
329   }
330 
331   SmallString<256> Buffer;
332   llvm::raw_svector_ostream Out(Buffer);
333   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
334     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
335   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
336     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
337   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
338     getCXXABI().getMangleContext().mangleBlock(BD, Out);
339   else
340     getCXXABI().getMangleContext().mangleName(ND, Out);
341 
342   // Allocate space for the mangled name.
343   Out.flush();
344   size_t Length = Buffer.size();
345   char *Name = MangledNamesAllocator.Allocate<char>(Length);
346   std::copy(Buffer.begin(), Buffer.end(), Name);
347 
348   Str = StringRef(Name, Length);
349 
350   return Str;
351 }
352 
353 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
354                                         const BlockDecl *BD) {
355   MangleContext &MangleCtx = getCXXABI().getMangleContext();
356   const Decl *D = GD.getDecl();
357   llvm::raw_svector_ostream Out(Buffer.getBuffer());
358   if (D == 0)
359     MangleCtx.mangleGlobalBlock(BD, Out);
360   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
361     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
362   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
363     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
364   else
365     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
366 }
367 
368 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
369   return getModule().getNamedValue(Name);
370 }
371 
372 /// AddGlobalCtor - Add a function to the list that will be called before
373 /// main() runs.
374 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
375   // FIXME: Type coercion of void()* types.
376   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
377 }
378 
379 /// AddGlobalDtor - Add a function to the list that will be called
380 /// when the module is unloaded.
381 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
382   // FIXME: Type coercion of void()* types.
383   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
384 }
385 
386 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
387   // Ctor function type is void()*.
388   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
389   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
390 
391   // Get the type of a ctor entry, { i32, void ()* }.
392   llvm::StructType *CtorStructTy =
393     llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
394 
395   // Construct the constructor and destructor arrays.
396   SmallVector<llvm::Constant*, 8> Ctors;
397   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
398     llvm::Constant *S[] = {
399       llvm::ConstantInt::get(Int32Ty, I->second, false),
400       llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
401     };
402     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
403   }
404 
405   if (!Ctors.empty()) {
406     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
407     new llvm::GlobalVariable(TheModule, AT, false,
408                              llvm::GlobalValue::AppendingLinkage,
409                              llvm::ConstantArray::get(AT, Ctors),
410                              GlobalName);
411   }
412 }
413 
414 llvm::GlobalValue::LinkageTypes
415 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
416   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
417 
418   if (Linkage == GVA_Internal)
419     return llvm::Function::InternalLinkage;
420 
421   if (D->hasAttr<DLLExportAttr>())
422     return llvm::Function::DLLExportLinkage;
423 
424   if (D->hasAttr<WeakAttr>())
425     return llvm::Function::WeakAnyLinkage;
426 
427   // In C99 mode, 'inline' functions are guaranteed to have a strong
428   // definition somewhere else, so we can use available_externally linkage.
429   if (Linkage == GVA_C99Inline)
430     return llvm::Function::AvailableExternallyLinkage;
431 
432   // Note that Apple's kernel linker doesn't support symbol
433   // coalescing, so we need to avoid linkonce and weak linkages there.
434   // Normally, this means we just map to internal, but for explicit
435   // instantiations we'll map to external.
436 
437   // In C++, the compiler has to emit a definition in every translation unit
438   // that references the function.  We should use linkonce_odr because
439   // a) if all references in this translation unit are optimized away, we
440   // don't need to codegen it.  b) if the function persists, it needs to be
441   // merged with other definitions. c) C++ has the ODR, so we know the
442   // definition is dependable.
443   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
444     return !Context.getLangOpts().AppleKext
445              ? llvm::Function::LinkOnceODRLinkage
446              : llvm::Function::InternalLinkage;
447 
448   // An explicit instantiation of a template has weak linkage, since
449   // explicit instantiations can occur in multiple translation units
450   // and must all be equivalent. However, we are not allowed to
451   // throw away these explicit instantiations.
452   if (Linkage == GVA_ExplicitTemplateInstantiation)
453     return !Context.getLangOpts().AppleKext
454              ? llvm::Function::WeakODRLinkage
455              : llvm::Function::ExternalLinkage;
456 
457   // Otherwise, we have strong external linkage.
458   assert(Linkage == GVA_StrongExternal);
459   return llvm::Function::ExternalLinkage;
460 }
461 
462 
463 /// SetFunctionDefinitionAttributes - Set attributes for a global.
464 ///
465 /// FIXME: This is currently only done for aliases and functions, but not for
466 /// variables (these details are set in EmitGlobalVarDefinition for variables).
467 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
468                                                     llvm::GlobalValue *GV) {
469   SetCommonAttributes(D, GV);
470 }
471 
472 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
473                                               const CGFunctionInfo &Info,
474                                               llvm::Function *F) {
475   unsigned CallingConv;
476   AttributeListType AttributeList;
477   ConstructAttributeList(Info, D, AttributeList, CallingConv);
478   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
479                                           AttributeList.size()));
480   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
481 }
482 
483 /// Determines whether the language options require us to model
484 /// unwind exceptions.  We treat -fexceptions as mandating this
485 /// except under the fragile ObjC ABI with only ObjC exceptions
486 /// enabled.  This means, for example, that C with -fexceptions
487 /// enables this.
488 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
489   // If exceptions are completely disabled, obviously this is false.
490   if (!LangOpts.Exceptions) return false;
491 
492   // If C++ exceptions are enabled, this is true.
493   if (LangOpts.CXXExceptions) return true;
494 
495   // If ObjC exceptions are enabled, this depends on the ABI.
496   if (LangOpts.ObjCExceptions) {
497     if (!LangOpts.ObjCNonFragileABI) return false;
498   }
499 
500   return true;
501 }
502 
503 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
504                                                            llvm::Function *F) {
505   if (CodeGenOpts.UnwindTables)
506     F->setHasUWTable();
507 
508   if (!hasUnwindExceptions(LangOpts))
509     F->addFnAttr(llvm::Attribute::NoUnwind);
510 
511   if (D->hasAttr<NakedAttr>()) {
512     // Naked implies noinline: we should not be inlining such functions.
513     F->addFnAttr(llvm::Attribute::Naked);
514     F->addFnAttr(llvm::Attribute::NoInline);
515   }
516 
517   if (D->hasAttr<NoInlineAttr>())
518     F->addFnAttr(llvm::Attribute::NoInline);
519 
520   // (noinline wins over always_inline, and we can't specify both in IR)
521   if (D->hasAttr<AlwaysInlineAttr>() &&
522       !F->hasFnAttr(llvm::Attribute::NoInline))
523     F->addFnAttr(llvm::Attribute::AlwaysInline);
524 
525   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
526     F->setUnnamedAddr(true);
527 
528   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
529     F->addFnAttr(llvm::Attribute::StackProtect);
530   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
531     F->addFnAttr(llvm::Attribute::StackProtectReq);
532 
533   if (LangOpts.AddressSanitizer) {
534     // When AddressSanitizer is enabled, set AddressSafety attribute
535     // unless __attribute__((no_address_safety_analysis)) is used.
536     if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
537       F->addFnAttr(llvm::Attribute::AddressSafety);
538   }
539 
540   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
541   if (alignment)
542     F->setAlignment(alignment);
543 
544   // C++ ABI requires 2-byte alignment for member functions.
545   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
546     F->setAlignment(2);
547 }
548 
549 void CodeGenModule::SetCommonAttributes(const Decl *D,
550                                         llvm::GlobalValue *GV) {
551   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
552     setGlobalVisibility(GV, ND);
553   else
554     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
555 
556   if (D->hasAttr<UsedAttr>())
557     AddUsedGlobal(GV);
558 
559   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
560     GV->setSection(SA->getName());
561 
562   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
563 }
564 
565 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
566                                                   llvm::Function *F,
567                                                   const CGFunctionInfo &FI) {
568   SetLLVMFunctionAttributes(D, FI, F);
569   SetLLVMFunctionAttributesForDefinition(D, F);
570 
571   F->setLinkage(llvm::Function::InternalLinkage);
572 
573   SetCommonAttributes(D, F);
574 }
575 
576 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
577                                           llvm::Function *F,
578                                           bool IsIncompleteFunction) {
579   if (unsigned IID = F->getIntrinsicID()) {
580     // If this is an intrinsic function, set the function's attributes
581     // to the intrinsic's attributes.
582     F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
583     return;
584   }
585 
586   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
587 
588   if (!IsIncompleteFunction)
589     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
590 
591   // Only a few attributes are set on declarations; these may later be
592   // overridden by a definition.
593 
594   if (FD->hasAttr<DLLImportAttr>()) {
595     F->setLinkage(llvm::Function::DLLImportLinkage);
596   } else if (FD->hasAttr<WeakAttr>() ||
597              FD->isWeakImported()) {
598     // "extern_weak" is overloaded in LLVM; we probably should have
599     // separate linkage types for this.
600     F->setLinkage(llvm::Function::ExternalWeakLinkage);
601   } else {
602     F->setLinkage(llvm::Function::ExternalLinkage);
603 
604     NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
605     if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
606       F->setVisibility(GetLLVMVisibility(LV.visibility()));
607     }
608   }
609 
610   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
611     F->setSection(SA->getName());
612 }
613 
614 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
615   assert(!GV->isDeclaration() &&
616          "Only globals with definition can force usage.");
617   LLVMUsed.push_back(GV);
618 }
619 
620 void CodeGenModule::EmitLLVMUsed() {
621   // Don't create llvm.used if there is no need.
622   if (LLVMUsed.empty())
623     return;
624 
625   // Convert LLVMUsed to what ConstantArray needs.
626   SmallVector<llvm::Constant*, 8> UsedArray;
627   UsedArray.resize(LLVMUsed.size());
628   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
629     UsedArray[i] =
630      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
631                                     Int8PtrTy);
632   }
633 
634   if (UsedArray.empty())
635     return;
636   llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
637 
638   llvm::GlobalVariable *GV =
639     new llvm::GlobalVariable(getModule(), ATy, false,
640                              llvm::GlobalValue::AppendingLinkage,
641                              llvm::ConstantArray::get(ATy, UsedArray),
642                              "llvm.used");
643 
644   GV->setSection("llvm.metadata");
645 }
646 
647 void CodeGenModule::EmitDeferred() {
648   // Emit code for any potentially referenced deferred decls.  Since a
649   // previously unused static decl may become used during the generation of code
650   // for a static function, iterate until no changes are made.
651 
652   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
653     if (!DeferredVTables.empty()) {
654       const CXXRecordDecl *RD = DeferredVTables.back();
655       DeferredVTables.pop_back();
656       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
657       continue;
658     }
659 
660     GlobalDecl D = DeferredDeclsToEmit.back();
661     DeferredDeclsToEmit.pop_back();
662 
663     // Check to see if we've already emitted this.  This is necessary
664     // for a couple of reasons: first, decls can end up in the
665     // deferred-decls queue multiple times, and second, decls can end
666     // up with definitions in unusual ways (e.g. by an extern inline
667     // function acquiring a strong function redefinition).  Just
668     // ignore these cases.
669     //
670     // TODO: That said, looking this up multiple times is very wasteful.
671     StringRef Name = getMangledName(D);
672     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
673     assert(CGRef && "Deferred decl wasn't referenced?");
674 
675     if (!CGRef->isDeclaration())
676       continue;
677 
678     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
679     // purposes an alias counts as a definition.
680     if (isa<llvm::GlobalAlias>(CGRef))
681       continue;
682 
683     // Otherwise, emit the definition and move on to the next one.
684     EmitGlobalDefinition(D);
685   }
686 }
687 
688 void CodeGenModule::EmitGlobalAnnotations() {
689   if (Annotations.empty())
690     return;
691 
692   // Create a new global variable for the ConstantStruct in the Module.
693   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
694     Annotations[0]->getType(), Annotations.size()), Annotations);
695   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
696     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
697     "llvm.global.annotations");
698   gv->setSection(AnnotationSection);
699 }
700 
701 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
702   llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
703   if (i != AnnotationStrings.end())
704     return i->second;
705 
706   // Not found yet, create a new global.
707   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
708   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
709     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
710   gv->setSection(AnnotationSection);
711   gv->setUnnamedAddr(true);
712   AnnotationStrings[Str] = gv;
713   return gv;
714 }
715 
716 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
717   SourceManager &SM = getContext().getSourceManager();
718   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
719   if (PLoc.isValid())
720     return EmitAnnotationString(PLoc.getFilename());
721   return EmitAnnotationString(SM.getBufferName(Loc));
722 }
723 
724 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
725   SourceManager &SM = getContext().getSourceManager();
726   PresumedLoc PLoc = SM.getPresumedLoc(L);
727   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
728     SM.getExpansionLineNumber(L);
729   return llvm::ConstantInt::get(Int32Ty, LineNo);
730 }
731 
732 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
733                                                 const AnnotateAttr *AA,
734                                                 SourceLocation L) {
735   // Get the globals for file name, annotation, and the line number.
736   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
737                  *UnitGV = EmitAnnotationUnit(L),
738                  *LineNoCst = EmitAnnotationLineNo(L);
739 
740   // Create the ConstantStruct for the global annotation.
741   llvm::Constant *Fields[4] = {
742     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
743     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
744     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
745     LineNoCst
746   };
747   return llvm::ConstantStruct::getAnon(Fields);
748 }
749 
750 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
751                                          llvm::GlobalValue *GV) {
752   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
753   // Get the struct elements for these annotations.
754   for (specific_attr_iterator<AnnotateAttr>
755        ai = D->specific_attr_begin<AnnotateAttr>(),
756        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
757     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
758 }
759 
760 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
761   // Never defer when EmitAllDecls is specified.
762   if (LangOpts.EmitAllDecls)
763     return false;
764 
765   return !getContext().DeclMustBeEmitted(Global);
766 }
767 
768 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
769   const AliasAttr *AA = VD->getAttr<AliasAttr>();
770   assert(AA && "No alias?");
771 
772   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
773 
774   // See if there is already something with the target's name in the module.
775   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
776 
777   llvm::Constant *Aliasee;
778   if (isa<llvm::FunctionType>(DeclTy))
779     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
780                                       /*ForVTable=*/false);
781   else
782     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
783                                     llvm::PointerType::getUnqual(DeclTy), 0);
784   if (!Entry) {
785     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
786     F->setLinkage(llvm::Function::ExternalWeakLinkage);
787     WeakRefReferences.insert(F);
788   }
789 
790   return Aliasee;
791 }
792 
793 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
794   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
795 
796   // Weak references don't produce any output by themselves.
797   if (Global->hasAttr<WeakRefAttr>())
798     return;
799 
800   // If this is an alias definition (which otherwise looks like a declaration)
801   // emit it now.
802   if (Global->hasAttr<AliasAttr>())
803     return EmitAliasDefinition(GD);
804 
805   // If this is CUDA, be selective about which declarations we emit.
806   if (LangOpts.CUDA) {
807     if (CodeGenOpts.CUDAIsDevice) {
808       if (!Global->hasAttr<CUDADeviceAttr>() &&
809           !Global->hasAttr<CUDAGlobalAttr>() &&
810           !Global->hasAttr<CUDAConstantAttr>() &&
811           !Global->hasAttr<CUDASharedAttr>())
812         return;
813     } else {
814       if (!Global->hasAttr<CUDAHostAttr>() && (
815             Global->hasAttr<CUDADeviceAttr>() ||
816             Global->hasAttr<CUDAConstantAttr>() ||
817             Global->hasAttr<CUDASharedAttr>()))
818         return;
819     }
820   }
821 
822   // Ignore declarations, they will be emitted on their first use.
823   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
824     // Forward declarations are emitted lazily on first use.
825     if (!FD->doesThisDeclarationHaveABody()) {
826       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
827         return;
828 
829       const FunctionDecl *InlineDefinition = 0;
830       FD->getBody(InlineDefinition);
831 
832       StringRef MangledName = getMangledName(GD);
833       DeferredDecls.erase(MangledName);
834       EmitGlobalDefinition(InlineDefinition);
835       return;
836     }
837   } else {
838     const VarDecl *VD = cast<VarDecl>(Global);
839     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
840 
841     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
842       return;
843   }
844 
845   // Defer code generation when possible if this is a static definition, inline
846   // function etc.  These we only want to emit if they are used.
847   if (!MayDeferGeneration(Global)) {
848     // Emit the definition if it can't be deferred.
849     EmitGlobalDefinition(GD);
850     return;
851   }
852 
853   // If we're deferring emission of a C++ variable with an
854   // initializer, remember the order in which it appeared in the file.
855   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
856       cast<VarDecl>(Global)->hasInit()) {
857     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
858     CXXGlobalInits.push_back(0);
859   }
860 
861   // If the value has already been used, add it directly to the
862   // DeferredDeclsToEmit list.
863   StringRef MangledName = getMangledName(GD);
864   if (GetGlobalValue(MangledName))
865     DeferredDeclsToEmit.push_back(GD);
866   else {
867     // Otherwise, remember that we saw a deferred decl with this name.  The
868     // first use of the mangled name will cause it to move into
869     // DeferredDeclsToEmit.
870     DeferredDecls[MangledName] = GD;
871   }
872 }
873 
874 namespace {
875   struct FunctionIsDirectlyRecursive :
876     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
877     const StringRef Name;
878     const Builtin::Context &BI;
879     bool Result;
880     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
881       Name(N), BI(C), Result(false) {
882     }
883     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
884 
885     bool TraverseCallExpr(CallExpr *E) {
886       const FunctionDecl *FD = E->getDirectCallee();
887       if (!FD)
888         return true;
889       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
890       if (Attr && Name == Attr->getLabel()) {
891         Result = true;
892         return false;
893       }
894       unsigned BuiltinID = FD->getBuiltinID();
895       if (!BuiltinID)
896         return true;
897       StringRef BuiltinName = BI.GetName(BuiltinID);
898       if (BuiltinName.startswith("__builtin_") &&
899           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
900         Result = true;
901         return false;
902       }
903       return true;
904     }
905   };
906 }
907 
908 // isTriviallyRecursive - Check if this function calls another
909 // decl that, because of the asm attribute or the other decl being a builtin,
910 // ends up pointing to itself.
911 bool
912 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
913   StringRef Name;
914   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
915     // asm labels are a special kind of mangling we have to support.
916     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
917     if (!Attr)
918       return false;
919     Name = Attr->getLabel();
920   } else {
921     Name = FD->getName();
922   }
923 
924   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
925   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
926   return Walker.Result;
927 }
928 
929 bool
930 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
931   if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
932     return true;
933   if (CodeGenOpts.OptimizationLevel == 0 &&
934       !F->hasAttr<AlwaysInlineAttr>())
935     return false;
936   // PR9614. Avoid cases where the source code is lying to us. An available
937   // externally function should have an equivalent function somewhere else,
938   // but a function that calls itself is clearly not equivalent to the real
939   // implementation.
940   // This happens in glibc's btowc and in some configure checks.
941   return !isTriviallyRecursive(F);
942 }
943 
944 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
945   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
946 
947   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
948                                  Context.getSourceManager(),
949                                  "Generating code for declaration");
950 
951   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
952     // At -O0, don't generate IR for functions with available_externally
953     // linkage.
954     if (!shouldEmitFunction(Function))
955       return;
956 
957     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
958       // Make sure to emit the definition(s) before we emit the thunks.
959       // This is necessary for the generation of certain thunks.
960       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
961         EmitCXXConstructor(CD, GD.getCtorType());
962       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
963         EmitCXXDestructor(DD, GD.getDtorType());
964       else
965         EmitGlobalFunctionDefinition(GD);
966 
967       if (Method->isVirtual())
968         getVTables().EmitThunks(GD);
969 
970       return;
971     }
972 
973     return EmitGlobalFunctionDefinition(GD);
974   }
975 
976   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
977     return EmitGlobalVarDefinition(VD);
978 
979   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
980 }
981 
982 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
983 /// module, create and return an llvm Function with the specified type. If there
984 /// is something in the module with the specified name, return it potentially
985 /// bitcasted to the right type.
986 ///
987 /// If D is non-null, it specifies a decl that correspond to this.  This is used
988 /// to set the attributes on the function when it is first created.
989 llvm::Constant *
990 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
991                                        llvm::Type *Ty,
992                                        GlobalDecl D, bool ForVTable,
993                                        llvm::Attributes ExtraAttrs) {
994   // Lookup the entry, lazily creating it if necessary.
995   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
996   if (Entry) {
997     if (WeakRefReferences.count(Entry)) {
998       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
999       if (FD && !FD->hasAttr<WeakAttr>())
1000         Entry->setLinkage(llvm::Function::ExternalLinkage);
1001 
1002       WeakRefReferences.erase(Entry);
1003     }
1004 
1005     if (Entry->getType()->getElementType() == Ty)
1006       return Entry;
1007 
1008     // Make sure the result is of the correct type.
1009     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1010   }
1011 
1012   // This function doesn't have a complete type (for example, the return
1013   // type is an incomplete struct). Use a fake type instead, and make
1014   // sure not to try to set attributes.
1015   bool IsIncompleteFunction = false;
1016 
1017   llvm::FunctionType *FTy;
1018   if (isa<llvm::FunctionType>(Ty)) {
1019     FTy = cast<llvm::FunctionType>(Ty);
1020   } else {
1021     FTy = llvm::FunctionType::get(VoidTy, false);
1022     IsIncompleteFunction = true;
1023   }
1024 
1025   llvm::Function *F = llvm::Function::Create(FTy,
1026                                              llvm::Function::ExternalLinkage,
1027                                              MangledName, &getModule());
1028   assert(F->getName() == MangledName && "name was uniqued!");
1029   if (D.getDecl())
1030     SetFunctionAttributes(D, F, IsIncompleteFunction);
1031   if (ExtraAttrs != llvm::Attribute::None)
1032     F->addFnAttr(ExtraAttrs);
1033 
1034   // This is the first use or definition of a mangled name.  If there is a
1035   // deferred decl with this name, remember that we need to emit it at the end
1036   // of the file.
1037   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1038   if (DDI != DeferredDecls.end()) {
1039     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1040     // list, and remove it from DeferredDecls (since we don't need it anymore).
1041     DeferredDeclsToEmit.push_back(DDI->second);
1042     DeferredDecls.erase(DDI);
1043 
1044   // Otherwise, there are cases we have to worry about where we're
1045   // using a declaration for which we must emit a definition but where
1046   // we might not find a top-level definition:
1047   //   - member functions defined inline in their classes
1048   //   - friend functions defined inline in some class
1049   //   - special member functions with implicit definitions
1050   // If we ever change our AST traversal to walk into class methods,
1051   // this will be unnecessary.
1052   //
1053   // We also don't emit a definition for a function if it's going to be an entry
1054   // in a vtable, unless it's already marked as used.
1055   } else if (getLangOpts().CPlusPlus && D.getDecl()) {
1056     // Look for a declaration that's lexically in a record.
1057     const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
1058     do {
1059       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1060         if (FD->isImplicit() && !ForVTable) {
1061           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
1062           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1063           break;
1064         } else if (FD->doesThisDeclarationHaveABody()) {
1065           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
1066           break;
1067         }
1068       }
1069       FD = FD->getPreviousDecl();
1070     } while (FD);
1071   }
1072 
1073   // Make sure the result is of the requested type.
1074   if (!IsIncompleteFunction) {
1075     assert(F->getType()->getElementType() == Ty);
1076     return F;
1077   }
1078 
1079   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1080   return llvm::ConstantExpr::getBitCast(F, PTy);
1081 }
1082 
1083 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1084 /// non-null, then this function will use the specified type if it has to
1085 /// create it (this occurs when we see a definition of the function).
1086 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1087                                                  llvm::Type *Ty,
1088                                                  bool ForVTable) {
1089   // If there was no specific requested type, just convert it now.
1090   if (!Ty)
1091     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1092 
1093   StringRef MangledName = getMangledName(GD);
1094   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
1095 }
1096 
1097 /// CreateRuntimeFunction - Create a new runtime function with the specified
1098 /// type and name.
1099 llvm::Constant *
1100 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1101                                      StringRef Name,
1102                                      llvm::Attributes ExtraAttrs) {
1103   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1104                                  ExtraAttrs);
1105 }
1106 
1107 /// isTypeConstant - Determine whether an object of this type can be emitted
1108 /// as a constant.
1109 ///
1110 /// If ExcludeCtor is true, the duration when the object's constructor runs
1111 /// will not be considered. The caller will need to verify that the object is
1112 /// not written to during its construction.
1113 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1114   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1115     return false;
1116 
1117   if (Context.getLangOpts().CPlusPlus) {
1118     if (const CXXRecordDecl *Record
1119           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1120       return ExcludeCtor && !Record->hasMutableFields() &&
1121              Record->hasTrivialDestructor();
1122   }
1123 
1124   return true;
1125 }
1126 
1127 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1128 /// create and return an llvm GlobalVariable with the specified type.  If there
1129 /// is something in the module with the specified name, return it potentially
1130 /// bitcasted to the right type.
1131 ///
1132 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1133 /// to set the attributes on the global when it is first created.
1134 llvm::Constant *
1135 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1136                                      llvm::PointerType *Ty,
1137                                      const VarDecl *D,
1138                                      bool UnnamedAddr) {
1139   // Lookup the entry, lazily creating it if necessary.
1140   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1141   if (Entry) {
1142     if (WeakRefReferences.count(Entry)) {
1143       if (D && !D->hasAttr<WeakAttr>())
1144         Entry->setLinkage(llvm::Function::ExternalLinkage);
1145 
1146       WeakRefReferences.erase(Entry);
1147     }
1148 
1149     if (UnnamedAddr)
1150       Entry->setUnnamedAddr(true);
1151 
1152     if (Entry->getType() == Ty)
1153       return Entry;
1154 
1155     // Make sure the result is of the correct type.
1156     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1157   }
1158 
1159   // This is the first use or definition of a mangled name.  If there is a
1160   // deferred decl with this name, remember that we need to emit it at the end
1161   // of the file.
1162   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1163   if (DDI != DeferredDecls.end()) {
1164     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1165     // list, and remove it from DeferredDecls (since we don't need it anymore).
1166     DeferredDeclsToEmit.push_back(DDI->second);
1167     DeferredDecls.erase(DDI);
1168   }
1169 
1170   llvm::GlobalVariable *GV =
1171     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1172                              llvm::GlobalValue::ExternalLinkage,
1173                              0, MangledName, 0,
1174                              false, Ty->getAddressSpace());
1175 
1176   // Handle things which are present even on external declarations.
1177   if (D) {
1178     // FIXME: This code is overly simple and should be merged with other global
1179     // handling.
1180     GV->setConstant(isTypeConstant(D->getType(), false));
1181 
1182     // Set linkage and visibility in case we never see a definition.
1183     NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1184     if (LV.linkage() != ExternalLinkage) {
1185       // Don't set internal linkage on declarations.
1186     } else {
1187       if (D->hasAttr<DLLImportAttr>())
1188         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1189       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1190         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1191 
1192       // Set visibility on a declaration only if it's explicit.
1193       if (LV.visibilityExplicit())
1194         GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1195     }
1196 
1197     GV->setThreadLocal(D->isThreadSpecified());
1198   }
1199 
1200   return GV;
1201 }
1202 
1203 
1204 llvm::GlobalVariable *
1205 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1206                                       llvm::Type *Ty,
1207                                       llvm::GlobalValue::LinkageTypes Linkage) {
1208   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1209   llvm::GlobalVariable *OldGV = 0;
1210 
1211 
1212   if (GV) {
1213     // Check if the variable has the right type.
1214     if (GV->getType()->getElementType() == Ty)
1215       return GV;
1216 
1217     // Because C++ name mangling, the only way we can end up with an already
1218     // existing global with the same name is if it has been declared extern "C".
1219       assert(GV->isDeclaration() && "Declaration has wrong type!");
1220     OldGV = GV;
1221   }
1222 
1223   // Create a new variable.
1224   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1225                                 Linkage, 0, Name);
1226 
1227   if (OldGV) {
1228     // Replace occurrences of the old variable if needed.
1229     GV->takeName(OldGV);
1230 
1231     if (!OldGV->use_empty()) {
1232       llvm::Constant *NewPtrForOldDecl =
1233       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1234       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1235     }
1236 
1237     OldGV->eraseFromParent();
1238   }
1239 
1240   return GV;
1241 }
1242 
1243 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1244 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1245 /// then it will be greated with the specified type instead of whatever the
1246 /// normal requested type would be.
1247 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1248                                                   llvm::Type *Ty) {
1249   assert(D->hasGlobalStorage() && "Not a global variable");
1250   QualType ASTTy = D->getType();
1251   if (Ty == 0)
1252     Ty = getTypes().ConvertTypeForMem(ASTTy);
1253 
1254   llvm::PointerType *PTy =
1255     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1256 
1257   StringRef MangledName = getMangledName(D);
1258   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1259 }
1260 
1261 /// CreateRuntimeVariable - Create a new runtime global variable with the
1262 /// specified type and name.
1263 llvm::Constant *
1264 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1265                                      StringRef Name) {
1266   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1267                                true);
1268 }
1269 
1270 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1271   assert(!D->getInit() && "Cannot emit definite definitions here!");
1272 
1273   if (MayDeferGeneration(D)) {
1274     // If we have not seen a reference to this variable yet, place it
1275     // into the deferred declarations table to be emitted if needed
1276     // later.
1277     StringRef MangledName = getMangledName(D);
1278     if (!GetGlobalValue(MangledName)) {
1279       DeferredDecls[MangledName] = D;
1280       return;
1281     }
1282   }
1283 
1284   // The tentative definition is the only definition.
1285   EmitGlobalVarDefinition(D);
1286 }
1287 
1288 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1289   if (DefinitionRequired)
1290     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1291 }
1292 
1293 llvm::GlobalVariable::LinkageTypes
1294 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1295   if (RD->getLinkage() != ExternalLinkage)
1296     return llvm::GlobalVariable::InternalLinkage;
1297 
1298   if (const CXXMethodDecl *KeyFunction
1299                                     = RD->getASTContext().getKeyFunction(RD)) {
1300     // If this class has a key function, use that to determine the linkage of
1301     // the vtable.
1302     const FunctionDecl *Def = 0;
1303     if (KeyFunction->hasBody(Def))
1304       KeyFunction = cast<CXXMethodDecl>(Def);
1305 
1306     switch (KeyFunction->getTemplateSpecializationKind()) {
1307       case TSK_Undeclared:
1308       case TSK_ExplicitSpecialization:
1309         // When compiling with optimizations turned on, we emit all vtables,
1310         // even if the key function is not defined in the current translation
1311         // unit. If this is the case, use available_externally linkage.
1312         if (!Def && CodeGenOpts.OptimizationLevel)
1313           return llvm::GlobalVariable::AvailableExternallyLinkage;
1314 
1315         if (KeyFunction->isInlined())
1316           return !Context.getLangOpts().AppleKext ?
1317                    llvm::GlobalVariable::LinkOnceODRLinkage :
1318                    llvm::Function::InternalLinkage;
1319 
1320         return llvm::GlobalVariable::ExternalLinkage;
1321 
1322       case TSK_ImplicitInstantiation:
1323         return !Context.getLangOpts().AppleKext ?
1324                  llvm::GlobalVariable::LinkOnceODRLinkage :
1325                  llvm::Function::InternalLinkage;
1326 
1327       case TSK_ExplicitInstantiationDefinition:
1328         return !Context.getLangOpts().AppleKext ?
1329                  llvm::GlobalVariable::WeakODRLinkage :
1330                  llvm::Function::InternalLinkage;
1331 
1332       case TSK_ExplicitInstantiationDeclaration:
1333         // FIXME: Use available_externally linkage. However, this currently
1334         // breaks LLVM's build due to undefined symbols.
1335         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1336         return !Context.getLangOpts().AppleKext ?
1337                  llvm::GlobalVariable::LinkOnceODRLinkage :
1338                  llvm::Function::InternalLinkage;
1339     }
1340   }
1341 
1342   if (Context.getLangOpts().AppleKext)
1343     return llvm::Function::InternalLinkage;
1344 
1345   switch (RD->getTemplateSpecializationKind()) {
1346   case TSK_Undeclared:
1347   case TSK_ExplicitSpecialization:
1348   case TSK_ImplicitInstantiation:
1349     // FIXME: Use available_externally linkage. However, this currently
1350     // breaks LLVM's build due to undefined symbols.
1351     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1352   case TSK_ExplicitInstantiationDeclaration:
1353     return llvm::GlobalVariable::LinkOnceODRLinkage;
1354 
1355   case TSK_ExplicitInstantiationDefinition:
1356       return llvm::GlobalVariable::WeakODRLinkage;
1357   }
1358 
1359   llvm_unreachable("Invalid TemplateSpecializationKind!");
1360 }
1361 
1362 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1363     return Context.toCharUnitsFromBits(
1364       TheTargetData.getTypeStoreSizeInBits(Ty));
1365 }
1366 
1367 llvm::Constant *
1368 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1369                                                        const Expr *rawInit) {
1370   ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1371   if (const ExprWithCleanups *withCleanups =
1372           dyn_cast<ExprWithCleanups>(rawInit)) {
1373     cleanups = withCleanups->getObjects();
1374     rawInit = withCleanups->getSubExpr();
1375   }
1376 
1377   const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1378   if (!init || !init->initializesStdInitializerList() ||
1379       init->getNumInits() == 0)
1380     return 0;
1381 
1382   ASTContext &ctx = getContext();
1383   unsigned numInits = init->getNumInits();
1384   // FIXME: This check is here because we would otherwise silently miscompile
1385   // nested global std::initializer_lists. Better would be to have a real
1386   // implementation.
1387   for (unsigned i = 0; i < numInits; ++i) {
1388     const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1389     if (inner && inner->initializesStdInitializerList()) {
1390       ErrorUnsupported(inner, "nested global std::initializer_list");
1391       return 0;
1392     }
1393   }
1394 
1395   // Synthesize a fake VarDecl for the array and initialize that.
1396   QualType elementType = init->getInit(0)->getType();
1397   llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1398   QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1399                                                 ArrayType::Normal, 0);
1400 
1401   IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1402   TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1403                                               arrayType, D->getLocation());
1404   VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1405                                                           D->getDeclContext()),
1406                                           D->getLocStart(), D->getLocation(),
1407                                           name, arrayType, sourceInfo,
1408                                           SC_Static, SC_Static);
1409 
1410   // Now clone the InitListExpr to initialize the array instead.
1411   // Incredible hack: we want to use the existing InitListExpr here, so we need
1412   // to tell it that it no longer initializes a std::initializer_list.
1413   Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(),
1414                                     const_cast<InitListExpr*>(init)->getInits(),
1415                                                    init->getNumInits(),
1416                                                    init->getRBraceLoc());
1417   arrayInit->setType(arrayType);
1418 
1419   if (!cleanups.empty())
1420     arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1421 
1422   backingArray->setInit(arrayInit);
1423 
1424   // Emit the definition of the array.
1425   EmitGlobalVarDefinition(backingArray);
1426 
1427   // Inspect the initializer list to validate it and determine its type.
1428   // FIXME: doing this every time is probably inefficient; caching would be nice
1429   RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1430   RecordDecl::field_iterator field = record->field_begin();
1431   if (field == record->field_end()) {
1432     ErrorUnsupported(D, "weird std::initializer_list");
1433     return 0;
1434   }
1435   QualType elementPtr = ctx.getPointerType(elementType.withConst());
1436   // Start pointer.
1437   if (!ctx.hasSameType(field->getType(), elementPtr)) {
1438     ErrorUnsupported(D, "weird std::initializer_list");
1439     return 0;
1440   }
1441   ++field;
1442   if (field == record->field_end()) {
1443     ErrorUnsupported(D, "weird std::initializer_list");
1444     return 0;
1445   }
1446   bool isStartEnd = false;
1447   if (ctx.hasSameType(field->getType(), elementPtr)) {
1448     // End pointer.
1449     isStartEnd = true;
1450   } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1451     ErrorUnsupported(D, "weird std::initializer_list");
1452     return 0;
1453   }
1454 
1455   // Now build an APValue representing the std::initializer_list.
1456   APValue initListValue(APValue::UninitStruct(), 0, 2);
1457   APValue &startField = initListValue.getStructField(0);
1458   APValue::LValuePathEntry startOffsetPathEntry;
1459   startOffsetPathEntry.ArrayIndex = 0;
1460   startField = APValue(APValue::LValueBase(backingArray),
1461                        CharUnits::fromQuantity(0),
1462                        llvm::makeArrayRef(startOffsetPathEntry),
1463                        /*IsOnePastTheEnd=*/false, 0);
1464 
1465   if (isStartEnd) {
1466     APValue &endField = initListValue.getStructField(1);
1467     APValue::LValuePathEntry endOffsetPathEntry;
1468     endOffsetPathEntry.ArrayIndex = numInits;
1469     endField = APValue(APValue::LValueBase(backingArray),
1470                        ctx.getTypeSizeInChars(elementType) * numInits,
1471                        llvm::makeArrayRef(endOffsetPathEntry),
1472                        /*IsOnePastTheEnd=*/true, 0);
1473   } else {
1474     APValue &sizeField = initListValue.getStructField(1);
1475     sizeField = APValue(llvm::APSInt(numElements));
1476   }
1477 
1478   // Emit the constant for the initializer_list.
1479   llvm::Constant *llvmInit =
1480       EmitConstantValueForMemory(initListValue, D->getType());
1481   assert(llvmInit && "failed to initialize as constant");
1482   return llvmInit;
1483 }
1484 
1485 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1486   llvm::Constant *Init = 0;
1487   QualType ASTTy = D->getType();
1488   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1489   bool NeedsGlobalCtor = false;
1490   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1491 
1492   const VarDecl *InitDecl;
1493   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1494 
1495   if (!InitExpr) {
1496     // This is a tentative definition; tentative definitions are
1497     // implicitly initialized with { 0 }.
1498     //
1499     // Note that tentative definitions are only emitted at the end of
1500     // a translation unit, so they should never have incomplete
1501     // type. In addition, EmitTentativeDefinition makes sure that we
1502     // never attempt to emit a tentative definition if a real one
1503     // exists. A use may still exists, however, so we still may need
1504     // to do a RAUW.
1505     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1506     Init = EmitNullConstant(D->getType());
1507   } else {
1508     // If this is a std::initializer_list, emit the special initializer.
1509     Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1510     // An empty init list will perform zero-initialization, which happens
1511     // to be exactly what we want.
1512     // FIXME: It does so in a global constructor, which is *not* what we
1513     // want.
1514 
1515     if (!Init)
1516       Init = EmitConstantInit(*InitDecl);
1517     if (!Init) {
1518       QualType T = InitExpr->getType();
1519       if (D->getType()->isReferenceType())
1520         T = D->getType();
1521 
1522       if (getLangOpts().CPlusPlus) {
1523         Init = EmitNullConstant(T);
1524         NeedsGlobalCtor = true;
1525       } else {
1526         ErrorUnsupported(D, "static initializer");
1527         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1528       }
1529     } else {
1530       // We don't need an initializer, so remove the entry for the delayed
1531       // initializer position (just in case this entry was delayed) if we
1532       // also don't need to register a destructor.
1533       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1534         DelayedCXXInitPosition.erase(D);
1535     }
1536   }
1537 
1538   llvm::Type* InitType = Init->getType();
1539   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1540 
1541   // Strip off a bitcast if we got one back.
1542   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1543     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1544            // all zero index gep.
1545            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1546     Entry = CE->getOperand(0);
1547   }
1548 
1549   // Entry is now either a Function or GlobalVariable.
1550   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1551 
1552   // We have a definition after a declaration with the wrong type.
1553   // We must make a new GlobalVariable* and update everything that used OldGV
1554   // (a declaration or tentative definition) with the new GlobalVariable*
1555   // (which will be a definition).
1556   //
1557   // This happens if there is a prototype for a global (e.g.
1558   // "extern int x[];") and then a definition of a different type (e.g.
1559   // "int x[10];"). This also happens when an initializer has a different type
1560   // from the type of the global (this happens with unions).
1561   if (GV == 0 ||
1562       GV->getType()->getElementType() != InitType ||
1563       GV->getType()->getAddressSpace() !=
1564         getContext().getTargetAddressSpace(ASTTy)) {
1565 
1566     // Move the old entry aside so that we'll create a new one.
1567     Entry->setName(StringRef());
1568 
1569     // Make a new global with the correct type, this is now guaranteed to work.
1570     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1571 
1572     // Replace all uses of the old global with the new global
1573     llvm::Constant *NewPtrForOldDecl =
1574         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1575     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1576 
1577     // Erase the old global, since it is no longer used.
1578     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1579   }
1580 
1581   if (D->hasAttr<AnnotateAttr>())
1582     AddGlobalAnnotations(D, GV);
1583 
1584   GV->setInitializer(Init);
1585 
1586   // If it is safe to mark the global 'constant', do so now.
1587   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1588                   isTypeConstant(D->getType(), true));
1589 
1590   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1591 
1592   // Set the llvm linkage type as appropriate.
1593   llvm::GlobalValue::LinkageTypes Linkage =
1594     GetLLVMLinkageVarDefinition(D, GV);
1595   GV->setLinkage(Linkage);
1596   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1597     // common vars aren't constant even if declared const.
1598     GV->setConstant(false);
1599 
1600   SetCommonAttributes(D, GV);
1601 
1602   // Emit the initializer function if necessary.
1603   if (NeedsGlobalCtor || NeedsGlobalDtor)
1604     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1605 
1606   // Emit global variable debug information.
1607   if (CGDebugInfo *DI = getModuleDebugInfo())
1608     DI->EmitGlobalVariable(GV, D);
1609 }
1610 
1611 llvm::GlobalValue::LinkageTypes
1612 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1613                                            llvm::GlobalVariable *GV) {
1614   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1615   if (Linkage == GVA_Internal)
1616     return llvm::Function::InternalLinkage;
1617   else if (D->hasAttr<DLLImportAttr>())
1618     return llvm::Function::DLLImportLinkage;
1619   else if (D->hasAttr<DLLExportAttr>())
1620     return llvm::Function::DLLExportLinkage;
1621   else if (D->hasAttr<WeakAttr>()) {
1622     if (GV->isConstant())
1623       return llvm::GlobalVariable::WeakODRLinkage;
1624     else
1625       return llvm::GlobalVariable::WeakAnyLinkage;
1626   } else if (Linkage == GVA_TemplateInstantiation ||
1627              Linkage == GVA_ExplicitTemplateInstantiation)
1628     return llvm::GlobalVariable::WeakODRLinkage;
1629   else if (!getLangOpts().CPlusPlus &&
1630            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1631              D->getAttr<CommonAttr>()) &&
1632            !D->hasExternalStorage() && !D->getInit() &&
1633            !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1634            !D->getAttr<WeakImportAttr>()) {
1635     // Thread local vars aren't considered common linkage.
1636     return llvm::GlobalVariable::CommonLinkage;
1637   }
1638   return llvm::GlobalVariable::ExternalLinkage;
1639 }
1640 
1641 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1642 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1643 /// existing call uses of the old function in the module, this adjusts them to
1644 /// call the new function directly.
1645 ///
1646 /// This is not just a cleanup: the always_inline pass requires direct calls to
1647 /// functions to be able to inline them.  If there is a bitcast in the way, it
1648 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1649 /// run at -O0.
1650 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1651                                                       llvm::Function *NewFn) {
1652   // If we're redefining a global as a function, don't transform it.
1653   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1654   if (OldFn == 0) return;
1655 
1656   llvm::Type *NewRetTy = NewFn->getReturnType();
1657   SmallVector<llvm::Value*, 4> ArgList;
1658 
1659   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1660        UI != E; ) {
1661     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1662     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1663     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1664     if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1665     llvm::CallSite CS(CI);
1666     if (!CI || !CS.isCallee(I)) continue;
1667 
1668     // If the return types don't match exactly, and if the call isn't dead, then
1669     // we can't transform this call.
1670     if (CI->getType() != NewRetTy && !CI->use_empty())
1671       continue;
1672 
1673     // Get the attribute list.
1674     llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1675     llvm::AttrListPtr AttrList = CI->getAttributes();
1676 
1677     // Get any return attributes.
1678     llvm::Attributes RAttrs = AttrList.getRetAttributes();
1679 
1680     // Add the return attributes.
1681     if (RAttrs)
1682       AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1683 
1684     // If the function was passed too few arguments, don't transform.  If extra
1685     // arguments were passed, we silently drop them.  If any of the types
1686     // mismatch, we don't transform.
1687     unsigned ArgNo = 0;
1688     bool DontTransform = false;
1689     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1690          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1691       if (CS.arg_size() == ArgNo ||
1692           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1693         DontTransform = true;
1694         break;
1695       }
1696 
1697       // Add any parameter attributes.
1698       if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1699         AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1700     }
1701     if (DontTransform)
1702       continue;
1703 
1704     if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
1705       AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1706 
1707     // Okay, we can transform this.  Create the new call instruction and copy
1708     // over the required information.
1709     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1710     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1711     ArgList.clear();
1712     if (!NewCall->getType()->isVoidTy())
1713       NewCall->takeName(CI);
1714     NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
1715                                                   AttrVec.end()));
1716     NewCall->setCallingConv(CI->getCallingConv());
1717 
1718     // Finally, remove the old call, replacing any uses with the new one.
1719     if (!CI->use_empty())
1720       CI->replaceAllUsesWith(NewCall);
1721 
1722     // Copy debug location attached to CI.
1723     if (!CI->getDebugLoc().isUnknown())
1724       NewCall->setDebugLoc(CI->getDebugLoc());
1725     CI->eraseFromParent();
1726   }
1727 }
1728 
1729 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1730   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1731   // If we have a definition, this might be a deferred decl. If the
1732   // instantiation is explicit, make sure we emit it at the end.
1733   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1734     GetAddrOfGlobalVar(VD);
1735 }
1736 
1737 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1738   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1739 
1740   // Compute the function info and LLVM type.
1741   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1742   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
1743 
1744   // Get or create the prototype for the function.
1745   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1746 
1747   // Strip off a bitcast if we got one back.
1748   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1749     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1750     Entry = CE->getOperand(0);
1751   }
1752 
1753 
1754   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1755     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1756 
1757     // If the types mismatch then we have to rewrite the definition.
1758     assert(OldFn->isDeclaration() &&
1759            "Shouldn't replace non-declaration");
1760 
1761     // F is the Function* for the one with the wrong type, we must make a new
1762     // Function* and update everything that used F (a declaration) with the new
1763     // Function* (which will be a definition).
1764     //
1765     // This happens if there is a prototype for a function
1766     // (e.g. "int f()") and then a definition of a different type
1767     // (e.g. "int f(int x)").  Move the old function aside so that it
1768     // doesn't interfere with GetAddrOfFunction.
1769     OldFn->setName(StringRef());
1770     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1771 
1772     // If this is an implementation of a function without a prototype, try to
1773     // replace any existing uses of the function (which may be calls) with uses
1774     // of the new function
1775     if (D->getType()->isFunctionNoProtoType()) {
1776       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1777       OldFn->removeDeadConstantUsers();
1778     }
1779 
1780     // Replace uses of F with the Function we will endow with a body.
1781     if (!Entry->use_empty()) {
1782       llvm::Constant *NewPtrForOldDecl =
1783         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1784       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1785     }
1786 
1787     // Ok, delete the old function now, which is dead.
1788     OldFn->eraseFromParent();
1789 
1790     Entry = NewFn;
1791   }
1792 
1793   // We need to set linkage and visibility on the function before
1794   // generating code for it because various parts of IR generation
1795   // want to propagate this information down (e.g. to local static
1796   // declarations).
1797   llvm::Function *Fn = cast<llvm::Function>(Entry);
1798   setFunctionLinkage(D, Fn);
1799 
1800   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1801   setGlobalVisibility(Fn, D);
1802 
1803   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1804 
1805   SetFunctionDefinitionAttributes(D, Fn);
1806   SetLLVMFunctionAttributesForDefinition(D, Fn);
1807 
1808   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1809     AddGlobalCtor(Fn, CA->getPriority());
1810   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1811     AddGlobalDtor(Fn, DA->getPriority());
1812   if (D->hasAttr<AnnotateAttr>())
1813     AddGlobalAnnotations(D, Fn);
1814 }
1815 
1816 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1817   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1818   const AliasAttr *AA = D->getAttr<AliasAttr>();
1819   assert(AA && "Not an alias?");
1820 
1821   StringRef MangledName = getMangledName(GD);
1822 
1823   // If there is a definition in the module, then it wins over the alias.
1824   // This is dubious, but allow it to be safe.  Just ignore the alias.
1825   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1826   if (Entry && !Entry->isDeclaration())
1827     return;
1828 
1829   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1830 
1831   // Create a reference to the named value.  This ensures that it is emitted
1832   // if a deferred decl.
1833   llvm::Constant *Aliasee;
1834   if (isa<llvm::FunctionType>(DeclTy))
1835     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1836                                       /*ForVTable=*/false);
1837   else
1838     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1839                                     llvm::PointerType::getUnqual(DeclTy), 0);
1840 
1841   // Create the new alias itself, but don't set a name yet.
1842   llvm::GlobalValue *GA =
1843     new llvm::GlobalAlias(Aliasee->getType(),
1844                           llvm::Function::ExternalLinkage,
1845                           "", Aliasee, &getModule());
1846 
1847   if (Entry) {
1848     assert(Entry->isDeclaration());
1849 
1850     // If there is a declaration in the module, then we had an extern followed
1851     // by the alias, as in:
1852     //   extern int test6();
1853     //   ...
1854     //   int test6() __attribute__((alias("test7")));
1855     //
1856     // Remove it and replace uses of it with the alias.
1857     GA->takeName(Entry);
1858 
1859     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1860                                                           Entry->getType()));
1861     Entry->eraseFromParent();
1862   } else {
1863     GA->setName(MangledName);
1864   }
1865 
1866   // Set attributes which are particular to an alias; this is a
1867   // specialization of the attributes which may be set on a global
1868   // variable/function.
1869   if (D->hasAttr<DLLExportAttr>()) {
1870     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1871       // The dllexport attribute is ignored for undefined symbols.
1872       if (FD->hasBody())
1873         GA->setLinkage(llvm::Function::DLLExportLinkage);
1874     } else {
1875       GA->setLinkage(llvm::Function::DLLExportLinkage);
1876     }
1877   } else if (D->hasAttr<WeakAttr>() ||
1878              D->hasAttr<WeakRefAttr>() ||
1879              D->isWeakImported()) {
1880     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1881   }
1882 
1883   SetCommonAttributes(D, GA);
1884 }
1885 
1886 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1887                                             ArrayRef<llvm::Type*> Tys) {
1888   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1889                                          Tys);
1890 }
1891 
1892 static llvm::StringMapEntry<llvm::Constant*> &
1893 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1894                          const StringLiteral *Literal,
1895                          bool TargetIsLSB,
1896                          bool &IsUTF16,
1897                          unsigned &StringLength) {
1898   StringRef String = Literal->getString();
1899   unsigned NumBytes = String.size();
1900 
1901   // Check for simple case.
1902   if (!Literal->containsNonAsciiOrNull()) {
1903     StringLength = NumBytes;
1904     return Map.GetOrCreateValue(String);
1905   }
1906 
1907   // Otherwise, convert the UTF8 literals into a string of shorts.
1908   IsUTF16 = true;
1909 
1910   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
1911   const UTF8 *FromPtr = (UTF8 *)String.data();
1912   UTF16 *ToPtr = &ToBuf[0];
1913 
1914   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1915                            &ToPtr, ToPtr + NumBytes,
1916                            strictConversion);
1917 
1918   // ConvertUTF8toUTF16 returns the length in ToPtr.
1919   StringLength = ToPtr - &ToBuf[0];
1920 
1921   // Add an explicit null.
1922   *ToPtr = 0;
1923   return Map.
1924     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
1925                                (StringLength + 1) * 2));
1926 }
1927 
1928 static llvm::StringMapEntry<llvm::Constant*> &
1929 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1930                        const StringLiteral *Literal,
1931                        unsigned &StringLength) {
1932   StringRef String = Literal->getString();
1933   StringLength = String.size();
1934   return Map.GetOrCreateValue(String);
1935 }
1936 
1937 llvm::Constant *
1938 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1939   unsigned StringLength = 0;
1940   bool isUTF16 = false;
1941   llvm::StringMapEntry<llvm::Constant*> &Entry =
1942     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1943                              getTargetData().isLittleEndian(),
1944                              isUTF16, StringLength);
1945 
1946   if (llvm::Constant *C = Entry.getValue())
1947     return C;
1948 
1949   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
1950   llvm::Constant *Zeros[] = { Zero, Zero };
1951 
1952   // If we don't already have it, get __CFConstantStringClassReference.
1953   if (!CFConstantStringClassRef) {
1954     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1955     Ty = llvm::ArrayType::get(Ty, 0);
1956     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1957                                            "__CFConstantStringClassReference");
1958     // Decay array -> ptr
1959     CFConstantStringClassRef =
1960       llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1961   }
1962 
1963   QualType CFTy = getContext().getCFConstantStringType();
1964 
1965   llvm::StructType *STy =
1966     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1967 
1968   llvm::Constant *Fields[4];
1969 
1970   // Class pointer.
1971   Fields[0] = CFConstantStringClassRef;
1972 
1973   // Flags.
1974   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1975   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1976     llvm::ConstantInt::get(Ty, 0x07C8);
1977 
1978   // String pointer.
1979   llvm::Constant *C = 0;
1980   if (isUTF16) {
1981     ArrayRef<uint16_t> Arr =
1982       llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
1983                                    Entry.getKey().size() / 2);
1984     C = llvm::ConstantDataArray::get(VMContext, Arr);
1985   } else {
1986     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
1987   }
1988 
1989   llvm::GlobalValue::LinkageTypes Linkage;
1990   if (isUTF16)
1991     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1992     Linkage = llvm::GlobalValue::InternalLinkage;
1993   else
1994     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1995     // when using private linkage. It is not clear if this is a bug in ld
1996     // or a reasonable new restriction.
1997     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1998 
1999   // Note: -fwritable-strings doesn't make the backing store strings of
2000   // CFStrings writable. (See <rdar://problem/10657500>)
2001   llvm::GlobalVariable *GV =
2002     new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2003                              Linkage, C, ".str");
2004   GV->setUnnamedAddr(true);
2005   if (isUTF16) {
2006     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2007     GV->setAlignment(Align.getQuantity());
2008   } else {
2009     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2010     GV->setAlignment(Align.getQuantity());
2011   }
2012 
2013   // String.
2014   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2015 
2016   if (isUTF16)
2017     // Cast the UTF16 string to the correct type.
2018     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2019 
2020   // String length.
2021   Ty = getTypes().ConvertType(getContext().LongTy);
2022   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2023 
2024   // The struct.
2025   C = llvm::ConstantStruct::get(STy, Fields);
2026   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2027                                 llvm::GlobalVariable::PrivateLinkage, C,
2028                                 "_unnamed_cfstring_");
2029   if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
2030     GV->setSection(Sect);
2031   Entry.setValue(GV);
2032 
2033   return GV;
2034 }
2035 
2036 static RecordDecl *
2037 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2038                  DeclContext *DC, IdentifierInfo *Id) {
2039   SourceLocation Loc;
2040   if (Ctx.getLangOpts().CPlusPlus)
2041     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2042   else
2043     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2044 }
2045 
2046 llvm::Constant *
2047 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2048   unsigned StringLength = 0;
2049   llvm::StringMapEntry<llvm::Constant*> &Entry =
2050     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2051 
2052   if (llvm::Constant *C = Entry.getValue())
2053     return C;
2054 
2055   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2056   llvm::Constant *Zeros[] = { Zero, Zero };
2057 
2058   // If we don't already have it, get _NSConstantStringClassReference.
2059   if (!ConstantStringClassRef) {
2060     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2061     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2062     llvm::Constant *GV;
2063     if (LangOpts.ObjCNonFragileABI) {
2064       std::string str =
2065         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2066                             : "OBJC_CLASS_$_" + StringClass;
2067       GV = getObjCRuntime().GetClassGlobal(str);
2068       // Make sure the result is of the correct type.
2069       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2070       ConstantStringClassRef =
2071         llvm::ConstantExpr::getBitCast(GV, PTy);
2072     } else {
2073       std::string str =
2074         StringClass.empty() ? "_NSConstantStringClassReference"
2075                             : "_" + StringClass + "ClassReference";
2076       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2077       GV = CreateRuntimeVariable(PTy, str);
2078       // Decay array -> ptr
2079       ConstantStringClassRef =
2080         llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2081     }
2082   }
2083 
2084   if (!NSConstantStringType) {
2085     // Construct the type for a constant NSString.
2086     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2087                                      Context.getTranslationUnitDecl(),
2088                                    &Context.Idents.get("__builtin_NSString"));
2089     D->startDefinition();
2090 
2091     QualType FieldTypes[3];
2092 
2093     // const int *isa;
2094     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2095     // const char *str;
2096     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2097     // unsigned int length;
2098     FieldTypes[2] = Context.UnsignedIntTy;
2099 
2100     // Create fields
2101     for (unsigned i = 0; i < 3; ++i) {
2102       FieldDecl *Field = FieldDecl::Create(Context, D,
2103                                            SourceLocation(),
2104                                            SourceLocation(), 0,
2105                                            FieldTypes[i], /*TInfo=*/0,
2106                                            /*BitWidth=*/0,
2107                                            /*Mutable=*/false,
2108                                            /*HasInit=*/false);
2109       Field->setAccess(AS_public);
2110       D->addDecl(Field);
2111     }
2112 
2113     D->completeDefinition();
2114     QualType NSTy = Context.getTagDeclType(D);
2115     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2116   }
2117 
2118   llvm::Constant *Fields[3];
2119 
2120   // Class pointer.
2121   Fields[0] = ConstantStringClassRef;
2122 
2123   // String pointer.
2124   llvm::Constant *C =
2125     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2126 
2127   llvm::GlobalValue::LinkageTypes Linkage;
2128   bool isConstant;
2129   Linkage = llvm::GlobalValue::PrivateLinkage;
2130   isConstant = !LangOpts.WritableStrings;
2131 
2132   llvm::GlobalVariable *GV =
2133   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2134                            ".str");
2135   GV->setUnnamedAddr(true);
2136   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2137   GV->setAlignment(Align.getQuantity());
2138   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2139 
2140   // String length.
2141   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2142   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2143 
2144   // The struct.
2145   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2146   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2147                                 llvm::GlobalVariable::PrivateLinkage, C,
2148                                 "_unnamed_nsstring_");
2149   // FIXME. Fix section.
2150   if (const char *Sect =
2151         LangOpts.ObjCNonFragileABI
2152           ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2153           : getContext().getTargetInfo().getNSStringSection())
2154     GV->setSection(Sect);
2155   Entry.setValue(GV);
2156 
2157   return GV;
2158 }
2159 
2160 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2161   if (ObjCFastEnumerationStateType.isNull()) {
2162     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2163                                      Context.getTranslationUnitDecl(),
2164                       &Context.Idents.get("__objcFastEnumerationState"));
2165     D->startDefinition();
2166 
2167     QualType FieldTypes[] = {
2168       Context.UnsignedLongTy,
2169       Context.getPointerType(Context.getObjCIdType()),
2170       Context.getPointerType(Context.UnsignedLongTy),
2171       Context.getConstantArrayType(Context.UnsignedLongTy,
2172                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2173     };
2174 
2175     for (size_t i = 0; i < 4; ++i) {
2176       FieldDecl *Field = FieldDecl::Create(Context,
2177                                            D,
2178                                            SourceLocation(),
2179                                            SourceLocation(), 0,
2180                                            FieldTypes[i], /*TInfo=*/0,
2181                                            /*BitWidth=*/0,
2182                                            /*Mutable=*/false,
2183                                            /*HasInit=*/false);
2184       Field->setAccess(AS_public);
2185       D->addDecl(Field);
2186     }
2187 
2188     D->completeDefinition();
2189     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2190   }
2191 
2192   return ObjCFastEnumerationStateType;
2193 }
2194 
2195 llvm::Constant *
2196 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2197   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2198 
2199   // Don't emit it as the address of the string, emit the string data itself
2200   // as an inline array.
2201   if (E->getCharByteWidth() == 1) {
2202     SmallString<64> Str(E->getString());
2203 
2204     // Resize the string to the right size, which is indicated by its type.
2205     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2206     Str.resize(CAT->getSize().getZExtValue());
2207     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2208   }
2209 
2210   llvm::ArrayType *AType =
2211     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2212   llvm::Type *ElemTy = AType->getElementType();
2213   unsigned NumElements = AType->getNumElements();
2214 
2215   // Wide strings have either 2-byte or 4-byte elements.
2216   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2217     SmallVector<uint16_t, 32> Elements;
2218     Elements.reserve(NumElements);
2219 
2220     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2221       Elements.push_back(E->getCodeUnit(i));
2222     Elements.resize(NumElements);
2223     return llvm::ConstantDataArray::get(VMContext, Elements);
2224   }
2225 
2226   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2227   SmallVector<uint32_t, 32> Elements;
2228   Elements.reserve(NumElements);
2229 
2230   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2231     Elements.push_back(E->getCodeUnit(i));
2232   Elements.resize(NumElements);
2233   return llvm::ConstantDataArray::get(VMContext, Elements);
2234 }
2235 
2236 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2237 /// constant array for the given string literal.
2238 llvm::Constant *
2239 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2240   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
2241   if (S->isAscii() || S->isUTF8()) {
2242     SmallString<64> Str(S->getString());
2243 
2244     // Resize the string to the right size, which is indicated by its type.
2245     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2246     Str.resize(CAT->getSize().getZExtValue());
2247     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2248   }
2249 
2250   // FIXME: the following does not memoize wide strings.
2251   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2252   llvm::GlobalVariable *GV =
2253     new llvm::GlobalVariable(getModule(),C->getType(),
2254                              !LangOpts.WritableStrings,
2255                              llvm::GlobalValue::PrivateLinkage,
2256                              C,".str");
2257 
2258   GV->setAlignment(Align.getQuantity());
2259   GV->setUnnamedAddr(true);
2260   return GV;
2261 }
2262 
2263 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2264 /// array for the given ObjCEncodeExpr node.
2265 llvm::Constant *
2266 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2267   std::string Str;
2268   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2269 
2270   return GetAddrOfConstantCString(Str);
2271 }
2272 
2273 
2274 /// GenerateWritableString -- Creates storage for a string literal.
2275 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2276                                              bool constant,
2277                                              CodeGenModule &CGM,
2278                                              const char *GlobalName,
2279                                              unsigned Alignment) {
2280   // Create Constant for this string literal. Don't add a '\0'.
2281   llvm::Constant *C =
2282       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2283 
2284   // Create a global variable for this string
2285   llvm::GlobalVariable *GV =
2286     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2287                              llvm::GlobalValue::PrivateLinkage,
2288                              C, GlobalName);
2289   GV->setAlignment(Alignment);
2290   GV->setUnnamedAddr(true);
2291   return GV;
2292 }
2293 
2294 /// GetAddrOfConstantString - Returns a pointer to a character array
2295 /// containing the literal. This contents are exactly that of the
2296 /// given string, i.e. it will not be null terminated automatically;
2297 /// see GetAddrOfConstantCString. Note that whether the result is
2298 /// actually a pointer to an LLVM constant depends on
2299 /// Feature.WriteableStrings.
2300 ///
2301 /// The result has pointer to array type.
2302 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2303                                                        const char *GlobalName,
2304                                                        unsigned Alignment) {
2305   // Get the default prefix if a name wasn't specified.
2306   if (!GlobalName)
2307     GlobalName = ".str";
2308 
2309   // Don't share any string literals if strings aren't constant.
2310   if (LangOpts.WritableStrings)
2311     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2312 
2313   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2314     ConstantStringMap.GetOrCreateValue(Str);
2315 
2316   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2317     if (Alignment > GV->getAlignment()) {
2318       GV->setAlignment(Alignment);
2319     }
2320     return GV;
2321   }
2322 
2323   // Create a global variable for this.
2324   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2325                                                    Alignment);
2326   Entry.setValue(GV);
2327   return GV;
2328 }
2329 
2330 /// GetAddrOfConstantCString - Returns a pointer to a character
2331 /// array containing the literal and a terminating '\0'
2332 /// character. The result has pointer to array type.
2333 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2334                                                         const char *GlobalName,
2335                                                         unsigned Alignment) {
2336   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2337   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2338 }
2339 
2340 /// EmitObjCPropertyImplementations - Emit information for synthesized
2341 /// properties for an implementation.
2342 void CodeGenModule::EmitObjCPropertyImplementations(const
2343                                                     ObjCImplementationDecl *D) {
2344   for (ObjCImplementationDecl::propimpl_iterator
2345          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2346     ObjCPropertyImplDecl *PID = *i;
2347 
2348     // Dynamic is just for type-checking.
2349     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2350       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2351 
2352       // Determine which methods need to be implemented, some may have
2353       // been overridden. Note that ::isSynthesized is not the method
2354       // we want, that just indicates if the decl came from a
2355       // property. What we want to know is if the method is defined in
2356       // this implementation.
2357       if (!D->getInstanceMethod(PD->getGetterName()))
2358         CodeGenFunction(*this).GenerateObjCGetter(
2359                                  const_cast<ObjCImplementationDecl *>(D), PID);
2360       if (!PD->isReadOnly() &&
2361           !D->getInstanceMethod(PD->getSetterName()))
2362         CodeGenFunction(*this).GenerateObjCSetter(
2363                                  const_cast<ObjCImplementationDecl *>(D), PID);
2364     }
2365   }
2366 }
2367 
2368 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2369   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2370   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2371        ivar; ivar = ivar->getNextIvar())
2372     if (ivar->getType().isDestructedType())
2373       return true;
2374 
2375   return false;
2376 }
2377 
2378 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2379 /// for an implementation.
2380 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2381   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2382   if (needsDestructMethod(D)) {
2383     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2384     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2385     ObjCMethodDecl *DTORMethod =
2386       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2387                              cxxSelector, getContext().VoidTy, 0, D,
2388                              /*isInstance=*/true, /*isVariadic=*/false,
2389                           /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2390                              /*isDefined=*/false, ObjCMethodDecl::Required);
2391     D->addInstanceMethod(DTORMethod);
2392     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2393     D->setHasCXXStructors(true);
2394   }
2395 
2396   // If the implementation doesn't have any ivar initializers, we don't need
2397   // a .cxx_construct.
2398   if (D->getNumIvarInitializers() == 0)
2399     return;
2400 
2401   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2402   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2403   // The constructor returns 'self'.
2404   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2405                                                 D->getLocation(),
2406                                                 D->getLocation(),
2407                                                 cxxSelector,
2408                                                 getContext().getObjCIdType(), 0,
2409                                                 D, /*isInstance=*/true,
2410                                                 /*isVariadic=*/false,
2411                                                 /*isSynthesized=*/true,
2412                                                 /*isImplicitlyDeclared=*/true,
2413                                                 /*isDefined=*/false,
2414                                                 ObjCMethodDecl::Required);
2415   D->addInstanceMethod(CTORMethod);
2416   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2417   D->setHasCXXStructors(true);
2418 }
2419 
2420 /// EmitNamespace - Emit all declarations in a namespace.
2421 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2422   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2423        I != E; ++I)
2424     EmitTopLevelDecl(*I);
2425 }
2426 
2427 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2428 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2429   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2430       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2431     ErrorUnsupported(LSD, "linkage spec");
2432     return;
2433   }
2434 
2435   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2436        I != E; ++I)
2437     EmitTopLevelDecl(*I);
2438 }
2439 
2440 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2441 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2442   // If an error has occurred, stop code generation, but continue
2443   // parsing and semantic analysis (to ensure all warnings and errors
2444   // are emitted).
2445   if (Diags.hasErrorOccurred())
2446     return;
2447 
2448   // Ignore dependent declarations.
2449   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2450     return;
2451 
2452   switch (D->getKind()) {
2453   case Decl::CXXConversion:
2454   case Decl::CXXMethod:
2455   case Decl::Function:
2456     // Skip function templates
2457     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2458         cast<FunctionDecl>(D)->isLateTemplateParsed())
2459       return;
2460 
2461     EmitGlobal(cast<FunctionDecl>(D));
2462     break;
2463 
2464   case Decl::Var:
2465     EmitGlobal(cast<VarDecl>(D));
2466     break;
2467 
2468   // Indirect fields from global anonymous structs and unions can be
2469   // ignored; only the actual variable requires IR gen support.
2470   case Decl::IndirectField:
2471     break;
2472 
2473   // C++ Decls
2474   case Decl::Namespace:
2475     EmitNamespace(cast<NamespaceDecl>(D));
2476     break;
2477     // No code generation needed.
2478   case Decl::UsingShadow:
2479   case Decl::Using:
2480   case Decl::UsingDirective:
2481   case Decl::ClassTemplate:
2482   case Decl::FunctionTemplate:
2483   case Decl::TypeAliasTemplate:
2484   case Decl::NamespaceAlias:
2485   case Decl::Block:
2486   case Decl::Import:
2487     break;
2488   case Decl::CXXConstructor:
2489     // Skip function templates
2490     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2491         cast<FunctionDecl>(D)->isLateTemplateParsed())
2492       return;
2493 
2494     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2495     break;
2496   case Decl::CXXDestructor:
2497     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2498       return;
2499     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2500     break;
2501 
2502   case Decl::StaticAssert:
2503     // Nothing to do.
2504     break;
2505 
2506   // Objective-C Decls
2507 
2508   // Forward declarations, no (immediate) code generation.
2509   case Decl::ObjCInterface:
2510     break;
2511 
2512   case Decl::ObjCCategory: {
2513     ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2514     if (CD->IsClassExtension() && CD->hasSynthBitfield())
2515       Context.ResetObjCLayout(CD->getClassInterface());
2516     break;
2517   }
2518 
2519   case Decl::ObjCProtocol: {
2520     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2521     if (Proto->isThisDeclarationADefinition())
2522       ObjCRuntime->GenerateProtocol(Proto);
2523     break;
2524   }
2525 
2526   case Decl::ObjCCategoryImpl:
2527     // Categories have properties but don't support synthesize so we
2528     // can ignore them here.
2529     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2530     break;
2531 
2532   case Decl::ObjCImplementation: {
2533     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2534     if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2535       Context.ResetObjCLayout(OMD->getClassInterface());
2536     EmitObjCPropertyImplementations(OMD);
2537     EmitObjCIvarInitializations(OMD);
2538     ObjCRuntime->GenerateClass(OMD);
2539     break;
2540   }
2541   case Decl::ObjCMethod: {
2542     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2543     // If this is not a prototype, emit the body.
2544     if (OMD->getBody())
2545       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2546     break;
2547   }
2548   case Decl::ObjCCompatibleAlias:
2549     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2550     break;
2551 
2552   case Decl::LinkageSpec:
2553     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2554     break;
2555 
2556   case Decl::FileScopeAsm: {
2557     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2558     StringRef AsmString = AD->getAsmString()->getString();
2559 
2560     const std::string &S = getModule().getModuleInlineAsm();
2561     if (S.empty())
2562       getModule().setModuleInlineAsm(AsmString);
2563     else if (*--S.end() == '\n')
2564       getModule().setModuleInlineAsm(S + AsmString.str());
2565     else
2566       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2567     break;
2568   }
2569 
2570   default:
2571     // Make sure we handled everything we should, every other kind is a
2572     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2573     // function. Need to recode Decl::Kind to do that easily.
2574     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2575   }
2576 }
2577 
2578 /// Turns the given pointer into a constant.
2579 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2580                                           const void *Ptr) {
2581   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2582   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2583   return llvm::ConstantInt::get(i64, PtrInt);
2584 }
2585 
2586 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2587                                    llvm::NamedMDNode *&GlobalMetadata,
2588                                    GlobalDecl D,
2589                                    llvm::GlobalValue *Addr) {
2590   if (!GlobalMetadata)
2591     GlobalMetadata =
2592       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2593 
2594   // TODO: should we report variant information for ctors/dtors?
2595   llvm::Value *Ops[] = {
2596     Addr,
2597     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2598   };
2599   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2600 }
2601 
2602 /// Emits metadata nodes associating all the global values in the
2603 /// current module with the Decls they came from.  This is useful for
2604 /// projects using IR gen as a subroutine.
2605 ///
2606 /// Since there's currently no way to associate an MDNode directly
2607 /// with an llvm::GlobalValue, we create a global named metadata
2608 /// with the name 'clang.global.decl.ptrs'.
2609 void CodeGenModule::EmitDeclMetadata() {
2610   llvm::NamedMDNode *GlobalMetadata = 0;
2611 
2612   // StaticLocalDeclMap
2613   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2614          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2615        I != E; ++I) {
2616     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2617     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2618   }
2619 }
2620 
2621 /// Emits metadata nodes for all the local variables in the current
2622 /// function.
2623 void CodeGenFunction::EmitDeclMetadata() {
2624   if (LocalDeclMap.empty()) return;
2625 
2626   llvm::LLVMContext &Context = getLLVMContext();
2627 
2628   // Find the unique metadata ID for this name.
2629   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2630 
2631   llvm::NamedMDNode *GlobalMetadata = 0;
2632 
2633   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2634          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2635     const Decl *D = I->first;
2636     llvm::Value *Addr = I->second;
2637 
2638     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2639       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2640       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2641     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2642       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2643       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2644     }
2645   }
2646 }
2647 
2648 void CodeGenModule::EmitCoverageFile() {
2649   if (!getCodeGenOpts().CoverageFile.empty()) {
2650     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2651       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2652       llvm::LLVMContext &Ctx = TheModule.getContext();
2653       llvm::MDString *CoverageFile =
2654           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2655       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2656         llvm::MDNode *CU = CUNode->getOperand(i);
2657         llvm::Value *node[] = { CoverageFile, CU };
2658         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2659         GCov->addOperand(N);
2660       }
2661     }
2662   }
2663 }
2664