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