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