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