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