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