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