xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 6ab4ae4168e35fb1c9fab309cee79130c812d90c)
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 "CGBlocks.h"
16 #include "CGCUDARuntime.h"
17 #include "CGCXXABI.h"
18 #include "CGCall.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "ConstantEmitter.h"
27 #include "CoverageMappingGen.h"
28 #include "TargetInfo.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/DeclTemplate.h"
34 #include "clang/AST/Mangle.h"
35 #include "clang/AST/RecordLayout.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/CodeGen/ConstantInitBuilder.h"
45 #include "clang/Frontend/CodeGenOptions.h"
46 #include "clang/Sema/SemaDiagnostic.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
59 
60 using namespace clang;
61 using namespace CodeGen;
62 
63 static llvm::cl::opt<bool> LimitedCoverage(
64     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
65     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
66     llvm::cl::init(false));
67 
68 static const char AnnotationSection[] = "llvm.metadata";
69 
70 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
71   switch (CGM.getTarget().getCXXABI().getKind()) {
72   case TargetCXXABI::GenericAArch64:
73   case TargetCXXABI::GenericARM:
74   case TargetCXXABI::iOS:
75   case TargetCXXABI::iOS64:
76   case TargetCXXABI::WatchOS:
77   case TargetCXXABI::GenericMIPS:
78   case TargetCXXABI::GenericItanium:
79   case TargetCXXABI::WebAssembly:
80     return CreateItaniumCXXABI(CGM);
81   case TargetCXXABI::Microsoft:
82     return CreateMicrosoftCXXABI(CGM);
83   }
84 
85   llvm_unreachable("invalid C++ ABI kind");
86 }
87 
88 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
89                              const PreprocessorOptions &PPO,
90                              const CodeGenOptions &CGO, llvm::Module &M,
91                              DiagnosticsEngine &diags,
92                              CoverageSourceInfo *CoverageInfo)
93     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
95       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
96       VMContext(M.getContext()), Types(*this), VTables(*this),
97       SanitizerMD(new SanitizerMetadata(*this)) {
98 
99   // Initialize the type cache.
100   llvm::LLVMContext &LLVMContext = M.getContext();
101   VoidTy = llvm::Type::getVoidTy(LLVMContext);
102   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106   HalfTy = llvm::Type::getHalfTy(LLVMContext);
107   FloatTy = llvm::Type::getFloatTy(LLVMContext);
108   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
109   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
110   PointerAlignInBytes =
111     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
112   SizeSizeInBytes =
113     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
114   IntAlignInBytes =
115     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
116   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
117   IntPtrTy = llvm::IntegerType::get(LLVMContext,
118     C.getTargetInfo().getMaxPointerWidth());
119   Int8PtrTy = Int8Ty->getPointerTo(0);
120   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
121   AllocaInt8PtrTy = Int8Ty->getPointerTo(
122       M.getDataLayout().getAllocaAddrSpace());
123   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
124 
125   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
126 
127   if (LangOpts.ObjC1)
128     createObjCRuntime();
129   if (LangOpts.OpenCL)
130     createOpenCLRuntime();
131   if (LangOpts.OpenMP)
132     createOpenMPRuntime();
133   if (LangOpts.CUDA)
134     createCUDARuntime();
135 
136   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
137   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
138       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
139     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
140                                getCXXABI().getMangleContext()));
141 
142   // If debug info or coverage generation is enabled, create the CGDebugInfo
143   // object.
144   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
145       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
146     DebugInfo.reset(new CGDebugInfo(*this));
147 
148   Block.GlobalUniqueCount = 0;
149 
150   if (C.getLangOpts().ObjC1)
151     ObjCData.reset(new ObjCEntrypoints());
152 
153   if (CodeGenOpts.hasProfileClangUse()) {
154     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
155         CodeGenOpts.ProfileInstrumentUsePath);
156     if (auto E = ReaderOrErr.takeError()) {
157       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
158                                               "Could not read profile %0: %1");
159       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
160         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
161                                   << EI.message();
162       });
163     } else
164       PGOReader = std::move(ReaderOrErr.get());
165   }
166 
167   // If coverage mapping generation is enabled, create the
168   // CoverageMappingModuleGen object.
169   if (CodeGenOpts.CoverageMapping)
170     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
171 }
172 
173 CodeGenModule::~CodeGenModule() {}
174 
175 void CodeGenModule::createObjCRuntime() {
176   // This is just isGNUFamily(), but we want to force implementors of
177   // new ABIs to decide how best to do this.
178   switch (LangOpts.ObjCRuntime.getKind()) {
179   case ObjCRuntime::GNUstep:
180   case ObjCRuntime::GCC:
181   case ObjCRuntime::ObjFW:
182     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
183     return;
184 
185   case ObjCRuntime::FragileMacOSX:
186   case ObjCRuntime::MacOSX:
187   case ObjCRuntime::iOS:
188   case ObjCRuntime::WatchOS:
189     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
190     return;
191   }
192   llvm_unreachable("bad runtime kind");
193 }
194 
195 void CodeGenModule::createOpenCLRuntime() {
196   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
197 }
198 
199 void CodeGenModule::createOpenMPRuntime() {
200   // Select a specialized code generation class based on the target, if any.
201   // If it does not exist use the default implementation.
202   switch (getTriple().getArch()) {
203   case llvm::Triple::nvptx:
204   case llvm::Triple::nvptx64:
205     assert(getLangOpts().OpenMPIsDevice &&
206            "OpenMP NVPTX is only prepared to deal with device code.");
207     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
208     break;
209   default:
210     if (LangOpts.OpenMPSimd)
211       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
212     else
213       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
214     break;
215   }
216 }
217 
218 void CodeGenModule::createCUDARuntime() {
219   CUDARuntime.reset(CreateNVCUDARuntime(*this));
220 }
221 
222 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
223   Replacements[Name] = C;
224 }
225 
226 void CodeGenModule::applyReplacements() {
227   for (auto &I : Replacements) {
228     StringRef MangledName = I.first();
229     llvm::Constant *Replacement = I.second;
230     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
231     if (!Entry)
232       continue;
233     auto *OldF = cast<llvm::Function>(Entry);
234     auto *NewF = dyn_cast<llvm::Function>(Replacement);
235     if (!NewF) {
236       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
237         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
238       } else {
239         auto *CE = cast<llvm::ConstantExpr>(Replacement);
240         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
241                CE->getOpcode() == llvm::Instruction::GetElementPtr);
242         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
243       }
244     }
245 
246     // Replace old with new, but keep the old order.
247     OldF->replaceAllUsesWith(Replacement);
248     if (NewF) {
249       NewF->removeFromParent();
250       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
251                                                        NewF);
252     }
253     OldF->eraseFromParent();
254   }
255 }
256 
257 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
258   GlobalValReplacements.push_back(std::make_pair(GV, C));
259 }
260 
261 void CodeGenModule::applyGlobalValReplacements() {
262   for (auto &I : GlobalValReplacements) {
263     llvm::GlobalValue *GV = I.first;
264     llvm::Constant *C = I.second;
265 
266     GV->replaceAllUsesWith(C);
267     GV->eraseFromParent();
268   }
269 }
270 
271 // This is only used in aliases that we created and we know they have a
272 // linear structure.
273 static const llvm::GlobalObject *getAliasedGlobal(
274     const llvm::GlobalIndirectSymbol &GIS) {
275   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
276   const llvm::Constant *C = &GIS;
277   for (;;) {
278     C = C->stripPointerCasts();
279     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
280       return GO;
281     // stripPointerCasts will not walk over weak aliases.
282     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
283     if (!GIS2)
284       return nullptr;
285     if (!Visited.insert(GIS2).second)
286       return nullptr;
287     C = GIS2->getIndirectSymbol();
288   }
289 }
290 
291 void CodeGenModule::checkAliases() {
292   // Check if the constructed aliases are well formed. It is really unfortunate
293   // that we have to do this in CodeGen, but we only construct mangled names
294   // and aliases during codegen.
295   bool Error = false;
296   DiagnosticsEngine &Diags = getDiags();
297   for (const GlobalDecl &GD : Aliases) {
298     const auto *D = cast<ValueDecl>(GD.getDecl());
299     SourceLocation Location;
300     bool IsIFunc = D->hasAttr<IFuncAttr>();
301     if (const Attr *A = D->getDefiningAttr())
302       Location = A->getLocation();
303     else
304       llvm_unreachable("Not an alias or ifunc?");
305     StringRef MangledName = getMangledName(GD);
306     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
307     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
308     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
309     if (!GV) {
310       Error = true;
311       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
312     } else if (GV->isDeclaration()) {
313       Error = true;
314       Diags.Report(Location, diag::err_alias_to_undefined)
315           << IsIFunc << IsIFunc;
316     } else if (IsIFunc) {
317       // Check resolver function type.
318       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
319           GV->getType()->getPointerElementType());
320       assert(FTy);
321       if (!FTy->getReturnType()->isPointerTy())
322         Diags.Report(Location, diag::err_ifunc_resolver_return);
323       if (FTy->getNumParams())
324         Diags.Report(Location, diag::err_ifunc_resolver_params);
325     }
326 
327     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
328     llvm::GlobalValue *AliaseeGV;
329     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
331     else
332       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
333 
334     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335       StringRef AliasSection = SA->getName();
336       if (AliasSection != AliaseeGV->getSection())
337         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
338             << AliasSection << IsIFunc << IsIFunc;
339     }
340 
341     // We have to handle alias to weak aliases in here. LLVM itself disallows
342     // this since the object semantics would not match the IL one. For
343     // compatibility with gcc we implement it by just pointing the alias
344     // to its aliasee's aliasee. We also warn, since the user is probably
345     // expecting the link to be weak.
346     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347       if (GA->isInterposable()) {
348         Diags.Report(Location, diag::warn_alias_to_weak_alias)
349             << GV->getName() << GA->getName() << IsIFunc;
350         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351             GA->getIndirectSymbol(), Alias->getType());
352         Alias->setIndirectSymbol(Aliasee);
353       }
354     }
355   }
356   if (!Error)
357     return;
358 
359   for (const GlobalDecl &GD : Aliases) {
360     StringRef MangledName = getMangledName(GD);
361     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
362     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364     Alias->eraseFromParent();
365   }
366 }
367 
368 void CodeGenModule::clear() {
369   DeferredDeclsToEmit.clear();
370   if (OpenMPRuntime)
371     OpenMPRuntime->clear();
372 }
373 
374 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
375                                        StringRef MainFile) {
376   if (!hasDiagnostics())
377     return;
378   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379     if (MainFile.empty())
380       MainFile = "<stdin>";
381     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
382   } else {
383     if (Mismatched > 0)
384       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
385 
386     if (Missing > 0)
387       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
388   }
389 }
390 
391 void CodeGenModule::Release() {
392   EmitDeferred();
393   EmitVTablesOpportunistically();
394   applyGlobalValReplacements();
395   applyReplacements();
396   checkAliases();
397   emitMultiVersionFunctions();
398   EmitCXXGlobalInitFunc();
399   EmitCXXGlobalDtorFunc();
400   EmitCXXThreadLocalInitFunc();
401   if (ObjCRuntime)
402     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
403       AddGlobalCtor(ObjCInitFunction);
404   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
405       CUDARuntime) {
406     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
407       AddGlobalCtor(CudaCtorFunction);
408     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
409       AddGlobalDtor(CudaDtorFunction);
410   }
411   if (OpenMPRuntime)
412     if (llvm::Function *OpenMPRegistrationFunction =
413             OpenMPRuntime->emitRegistrationFunction()) {
414       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415         OpenMPRegistrationFunction : nullptr;
416       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
417     }
418   if (PGOReader) {
419     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
420     if (PGOStats.hasDiagnostics())
421       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
422   }
423   EmitCtorList(GlobalCtors, "llvm.global_ctors");
424   EmitCtorList(GlobalDtors, "llvm.global_dtors");
425   EmitGlobalAnnotations();
426   EmitStaticExternCAliases();
427   EmitDeferredUnusedCoverageMappings();
428   if (CoverageMapping)
429     CoverageMapping->emit();
430   if (CodeGenOpts.SanitizeCfiCrossDso) {
431     CodeGenFunction(*this).EmitCfiCheckFail();
432     CodeGenFunction(*this).EmitCfiCheckStub();
433   }
434   emitAtAvailableLinkGuard();
435   emitLLVMUsed();
436   if (SanStats)
437     SanStats->finish();
438 
439   if (CodeGenOpts.Autolink &&
440       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
441     EmitModuleLinkOptions();
442   }
443 
444   // Record mregparm value now so it is visible through rest of codegen.
445   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
446     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
447                               CodeGenOpts.NumRegisterParameters);
448 
449   if (CodeGenOpts.DwarfVersion) {
450     // We actually want the latest version when there are conflicts.
451     // We can change from Warning to Latest if such mode is supported.
452     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
453                               CodeGenOpts.DwarfVersion);
454   }
455   if (CodeGenOpts.EmitCodeView) {
456     // Indicate that we want CodeView in the metadata.
457     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
458   }
459   if (CodeGenOpts.ControlFlowGuard) {
460     // We want function ID tables for Control Flow Guard.
461     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
462   }
463   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
464     // We don't support LTO with 2 with different StrictVTablePointers
465     // FIXME: we could support it by stripping all the information introduced
466     // by StrictVTablePointers.
467 
468     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
469 
470     llvm::Metadata *Ops[2] = {
471               llvm::MDString::get(VMContext, "StrictVTablePointers"),
472               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
473                   llvm::Type::getInt32Ty(VMContext), 1))};
474 
475     getModule().addModuleFlag(llvm::Module::Require,
476                               "StrictVTablePointersRequirement",
477                               llvm::MDNode::get(VMContext, Ops));
478   }
479   if (DebugInfo)
480     // We support a single version in the linked module. The LLVM
481     // parser will drop debug info with a different version number
482     // (and warn about it, too).
483     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
484                               llvm::DEBUG_METADATA_VERSION);
485 
486   // We need to record the widths of enums and wchar_t, so that we can generate
487   // the correct build attributes in the ARM backend. wchar_size is also used by
488   // TargetLibraryInfo.
489   uint64_t WCharWidth =
490       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
491   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
492 
493   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
494   if (   Arch == llvm::Triple::arm
495       || Arch == llvm::Triple::armeb
496       || Arch == llvm::Triple::thumb
497       || Arch == llvm::Triple::thumbeb) {
498     // The minimum width of an enum in bytes
499     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
500     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
501   }
502 
503   if (CodeGenOpts.SanitizeCfiCrossDso) {
504     // Indicate that we want cross-DSO control flow integrity checks.
505     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
506   }
507 
508   if (CodeGenOpts.CFProtectionReturn &&
509       Target.checkCFProtectionReturnSupported(getDiags())) {
510     // Indicate that we want to instrument return control flow protection.
511     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
512                               1);
513   }
514 
515   if (CodeGenOpts.CFProtectionBranch &&
516       Target.checkCFProtectionBranchSupported(getDiags())) {
517     // Indicate that we want to instrument branch control flow protection.
518     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
519                               1);
520   }
521 
522   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
523     // Indicate whether __nvvm_reflect should be configured to flush denormal
524     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
525     // property.)
526     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
527                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
528   }
529 
530   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
531   if (LangOpts.OpenCL) {
532     EmitOpenCLMetadata();
533     // Emit SPIR version.
534     if (getTriple().getArch() == llvm::Triple::spir ||
535         getTriple().getArch() == llvm::Triple::spir64) {
536       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
537       // opencl.spir.version named metadata.
538       llvm::Metadata *SPIRVerElts[] = {
539           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
540               Int32Ty, LangOpts.OpenCLVersion / 100)),
541           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542               Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
543       llvm::NamedMDNode *SPIRVerMD =
544           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
545       llvm::LLVMContext &Ctx = TheModule.getContext();
546       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
547     }
548   }
549 
550   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
551     assert(PLevel < 3 && "Invalid PIC Level");
552     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
553     if (Context.getLangOpts().PIE)
554       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
555   }
556 
557   if (CodeGenOpts.NoPLT)
558     getModule().setRtLibUseGOT();
559 
560   SimplifyPersonality();
561 
562   if (getCodeGenOpts().EmitDeclMetadata)
563     EmitDeclMetadata();
564 
565   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
566     EmitCoverageFile();
567 
568   if (DebugInfo)
569     DebugInfo->finalize();
570 
571   EmitVersionIdentMetadata();
572 
573   EmitTargetMetadata();
574 }
575 
576 void CodeGenModule::EmitOpenCLMetadata() {
577   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
578   // opencl.ocl.version named metadata node.
579   llvm::Metadata *OCLVerElts[] = {
580       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
581           Int32Ty, LangOpts.OpenCLVersion / 100)),
582       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
583           Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
584   llvm::NamedMDNode *OCLVerMD =
585       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
586   llvm::LLVMContext &Ctx = TheModule.getContext();
587   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
588 }
589 
590 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
591   // Make sure that this type is translated.
592   Types.UpdateCompletedType(TD);
593 }
594 
595 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
596   // Make sure that this type is translated.
597   Types.RefreshTypeCacheForClass(RD);
598 }
599 
600 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
601   if (!TBAA)
602     return nullptr;
603   return TBAA->getTypeInfo(QTy);
604 }
605 
606 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
607   if (!TBAA)
608     return TBAAAccessInfo();
609   return TBAA->getAccessInfo(AccessType);
610 }
611 
612 TBAAAccessInfo
613 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
614   if (!TBAA)
615     return TBAAAccessInfo();
616   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
617 }
618 
619 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
620   if (!TBAA)
621     return nullptr;
622   return TBAA->getTBAAStructInfo(QTy);
623 }
624 
625 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
626   if (!TBAA)
627     return nullptr;
628   return TBAA->getBaseTypeInfo(QTy);
629 }
630 
631 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
632   if (!TBAA)
633     return nullptr;
634   return TBAA->getAccessTagInfo(Info);
635 }
636 
637 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
638                                                    TBAAAccessInfo TargetInfo) {
639   if (!TBAA)
640     return TBAAAccessInfo();
641   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
642 }
643 
644 TBAAAccessInfo
645 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
646                                                    TBAAAccessInfo InfoB) {
647   if (!TBAA)
648     return TBAAAccessInfo();
649   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
650 }
651 
652 TBAAAccessInfo
653 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
654                                               TBAAAccessInfo SrcInfo) {
655   if (!TBAA)
656     return TBAAAccessInfo();
657   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
658 }
659 
660 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
661                                                 TBAAAccessInfo TBAAInfo) {
662   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
663     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
664 }
665 
666 void CodeGenModule::DecorateInstructionWithInvariantGroup(
667     llvm::Instruction *I, const CXXRecordDecl *RD) {
668   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
669                  llvm::MDNode::get(getLLVMContext(), {}));
670 }
671 
672 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
673   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
674   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
675 }
676 
677 /// ErrorUnsupported - Print out an error that codegen doesn't support the
678 /// specified stmt yet.
679 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
680   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
681                                                "cannot compile this %0 yet");
682   std::string Msg = Type;
683   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
684     << Msg << S->getSourceRange();
685 }
686 
687 /// ErrorUnsupported - Print out an error that codegen doesn't support the
688 /// specified decl yet.
689 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
690   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
691                                                "cannot compile this %0 yet");
692   std::string Msg = Type;
693   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
694 }
695 
696 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
697   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
698 }
699 
700 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
701                                         const NamedDecl *D) const {
702   if (GV->hasDLLImportStorageClass())
703     return;
704   // Internal definitions always have default visibility.
705   if (GV->hasLocalLinkage()) {
706     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
707     return;
708   }
709   if (!D)
710     return;
711   // Set visibility for definitions.
712   LinkageInfo LV = D->getLinkageAndVisibility();
713   if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
714     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
715 }
716 
717 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
718                                  llvm::GlobalValue *GV) {
719   if (GV->hasLocalLinkage())
720     return true;
721 
722   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
723     return true;
724 
725   // DLLImport explicitly marks the GV as external.
726   if (GV->hasDLLImportStorageClass())
727     return false;
728 
729   const llvm::Triple &TT = CGM.getTriple();
730   // Every other GV is local on COFF.
731   // Make an exception for windows OS in the triple: Some firmware builds use
732   // *-win32-macho triples. This (accidentally?) produced windows relocations
733   // without GOT tables in older clang versions; Keep this behaviour.
734   // FIXME: even thread local variables?
735   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
736     return true;
737 
738   // Only handle COFF and ELF for now.
739   if (!TT.isOSBinFormatELF())
740     return false;
741 
742   // If this is not an executable, don't assume anything is local.
743   const auto &CGOpts = CGM.getCodeGenOpts();
744   llvm::Reloc::Model RM = CGOpts.RelocationModel;
745   const auto &LOpts = CGM.getLangOpts();
746   if (RM != llvm::Reloc::Static && !LOpts.PIE)
747     return false;
748 
749   // A definition cannot be preempted from an executable.
750   if (!GV->isDeclarationForLinker())
751     return true;
752 
753   // Most PIC code sequences that assume that a symbol is local cannot produce a
754   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
755   // depended, it seems worth it to handle it here.
756   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
757     return false;
758 
759   // PPC has no copy relocations and cannot use a plt entry as a symbol address.
760   llvm::Triple::ArchType Arch = TT.getArch();
761   if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
762       Arch == llvm::Triple::ppc64le)
763     return false;
764 
765   // If we can use copy relocations we can assume it is local.
766   if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
767     if (!Var->isThreadLocal() &&
768         (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
769       return true;
770 
771   // If we can use a plt entry as the symbol address we can assume it
772   // is local.
773   // FIXME: This should work for PIE, but the gold linker doesn't support it.
774   if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
775     return true;
776 
777   // Otherwise don't assue it is local.
778   return false;
779 }
780 
781 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
782   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
783 }
784 
785 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
786                                           GlobalDecl GD) const {
787   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
788   // C++ destructors have a few C++ ABI specific special cases.
789   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
790     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
791     return;
792   }
793   setDLLImportDLLExport(GV, D);
794 }
795 
796 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
797                                           const NamedDecl *D) const {
798   if (D && D->isExternallyVisible()) {
799     if (D->hasAttr<DLLImportAttr>())
800       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
801     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
802       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
803   }
804 }
805 
806 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
807                                     GlobalDecl GD) const {
808   setDLLImportDLLExport(GV, GD);
809   setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
810 }
811 
812 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
813                                     const NamedDecl *D) const {
814   setDLLImportDLLExport(GV, D);
815   setGlobalVisibilityAndLocal(GV, D);
816 }
817 
818 void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
819                                                 const NamedDecl *D) const {
820   setGlobalVisibility(GV, D);
821   setDSOLocal(GV);
822 }
823 
824 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
825   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
826       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
827       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
828       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
829       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
830 }
831 
832 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
833     CodeGenOptions::TLSModel M) {
834   switch (M) {
835   case CodeGenOptions::GeneralDynamicTLSModel:
836     return llvm::GlobalVariable::GeneralDynamicTLSModel;
837   case CodeGenOptions::LocalDynamicTLSModel:
838     return llvm::GlobalVariable::LocalDynamicTLSModel;
839   case CodeGenOptions::InitialExecTLSModel:
840     return llvm::GlobalVariable::InitialExecTLSModel;
841   case CodeGenOptions::LocalExecTLSModel:
842     return llvm::GlobalVariable::LocalExecTLSModel;
843   }
844   llvm_unreachable("Invalid TLS model!");
845 }
846 
847 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
848   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
849 
850   llvm::GlobalValue::ThreadLocalMode TLM;
851   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
852 
853   // Override the TLS model if it is explicitly specified.
854   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
855     TLM = GetLLVMTLSModel(Attr->getModel());
856   }
857 
858   GV->setThreadLocalMode(TLM);
859 }
860 
861 static void AppendTargetMangling(const CodeGenModule &CGM,
862                                  const TargetAttr *Attr, raw_ostream &Out) {
863   if (Attr->isDefaultVersion())
864     return;
865 
866   Out << '.';
867   const auto &Target = CGM.getTarget();
868   TargetAttr::ParsedTargetAttr Info =
869       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
870                     // Multiversioning doesn't allow "no-${feature}", so we can
871                     // only have "+" prefixes here.
872                     assert(LHS.startswith("+") && RHS.startswith("+") &&
873                            "Features should always have a prefix.");
874                     return Target.multiVersionSortPriority(LHS.substr(1)) >
875                            Target.multiVersionSortPriority(RHS.substr(1));
876                   });
877 
878   bool IsFirst = true;
879 
880   if (!Info.Architecture.empty()) {
881     IsFirst = false;
882     Out << "arch_" << Info.Architecture;
883   }
884 
885   for (StringRef Feat : Info.Features) {
886     if (!IsFirst)
887       Out << '_';
888     IsFirst = false;
889     Out << Feat.substr(1);
890   }
891 }
892 
893 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
894                                       const NamedDecl *ND,
895                                       bool OmitTargetMangling = false) {
896   SmallString<256> Buffer;
897   llvm::raw_svector_ostream Out(Buffer);
898   MangleContext &MC = CGM.getCXXABI().getMangleContext();
899   if (MC.shouldMangleDeclName(ND)) {
900     llvm::raw_svector_ostream Out(Buffer);
901     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
902       MC.mangleCXXCtor(D, GD.getCtorType(), Out);
903     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
904       MC.mangleCXXDtor(D, GD.getDtorType(), Out);
905     else
906       MC.mangleName(ND, Out);
907   } else {
908     IdentifierInfo *II = ND->getIdentifier();
909     assert(II && "Attempt to mangle unnamed decl.");
910     const auto *FD = dyn_cast<FunctionDecl>(ND);
911 
912     if (FD &&
913         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
914       llvm::raw_svector_ostream Out(Buffer);
915       Out << "__regcall3__" << II->getName();
916     } else {
917       Out << II->getName();
918     }
919   }
920 
921   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
922     if (FD->isMultiVersion() && !OmitTargetMangling)
923       AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
924   return Out.str();
925 }
926 
927 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
928                                             const FunctionDecl *FD) {
929   if (!FD->isMultiVersion())
930     return;
931 
932   // Get the name of what this would be without the 'target' attribute.  This
933   // allows us to lookup the version that was emitted when this wasn't a
934   // multiversion function.
935   std::string NonTargetName =
936       getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
937   GlobalDecl OtherGD;
938   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
939     assert(OtherGD.getCanonicalDecl()
940                .getDecl()
941                ->getAsFunction()
942                ->isMultiVersion() &&
943            "Other GD should now be a multiversioned function");
944     // OtherFD is the version of this function that was mangled BEFORE
945     // becoming a MultiVersion function.  It potentially needs to be updated.
946     const FunctionDecl *OtherFD =
947         OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
948     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
949     // This is so that if the initial version was already the 'default'
950     // version, we don't try to update it.
951     if (OtherName != NonTargetName) {
952       // Remove instead of erase, since others may have stored the StringRef
953       // to this.
954       const auto ExistingRecord = Manglings.find(NonTargetName);
955       if (ExistingRecord != std::end(Manglings))
956         Manglings.remove(&(*ExistingRecord));
957       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
958       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
959       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
960         Entry->setName(OtherName);
961     }
962   }
963 }
964 
965 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
966   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
967 
968   // Some ABIs don't have constructor variants.  Make sure that base and
969   // complete constructors get mangled the same.
970   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
971     if (!getTarget().getCXXABI().hasConstructorVariants()) {
972       CXXCtorType OrigCtorType = GD.getCtorType();
973       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
974       if (OrigCtorType == Ctor_Base)
975         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
976     }
977   }
978 
979   auto FoundName = MangledDeclNames.find(CanonicalGD);
980   if (FoundName != MangledDeclNames.end())
981     return FoundName->second;
982 
983 
984   // Keep the first result in the case of a mangling collision.
985   const auto *ND = cast<NamedDecl>(GD.getDecl());
986   auto Result =
987       Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
988   return MangledDeclNames[CanonicalGD] = Result.first->first();
989 }
990 
991 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
992                                              const BlockDecl *BD) {
993   MangleContext &MangleCtx = getCXXABI().getMangleContext();
994   const Decl *D = GD.getDecl();
995 
996   SmallString<256> Buffer;
997   llvm::raw_svector_ostream Out(Buffer);
998   if (!D)
999     MangleCtx.mangleGlobalBlock(BD,
1000       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1001   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1002     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1003   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1004     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1005   else
1006     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1007 
1008   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1009   return Result.first->first();
1010 }
1011 
1012 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1013   return getModule().getNamedValue(Name);
1014 }
1015 
1016 /// AddGlobalCtor - Add a function to the list that will be called before
1017 /// main() runs.
1018 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1019                                   llvm::Constant *AssociatedData) {
1020   // FIXME: Type coercion of void()* types.
1021   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1022 }
1023 
1024 /// AddGlobalDtor - Add a function to the list that will be called
1025 /// when the module is unloaded.
1026 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1027   // FIXME: Type coercion of void()* types.
1028   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1029 }
1030 
1031 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1032   if (Fns.empty()) return;
1033 
1034   // Ctor function type is void()*.
1035   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1036   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
1037 
1038   // Get the type of a ctor entry, { i32, void ()*, i8* }.
1039   llvm::StructType *CtorStructTy = llvm::StructType::get(
1040       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
1041 
1042   // Construct the constructor and destructor arrays.
1043   ConstantInitBuilder builder(*this);
1044   auto ctors = builder.beginArray(CtorStructTy);
1045   for (const auto &I : Fns) {
1046     auto ctor = ctors.beginStruct(CtorStructTy);
1047     ctor.addInt(Int32Ty, I.Priority);
1048     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1049     if (I.AssociatedData)
1050       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1051     else
1052       ctor.addNullPointer(VoidPtrTy);
1053     ctor.finishAndAddTo(ctors);
1054   }
1055 
1056   auto list =
1057     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1058                                 /*constant*/ false,
1059                                 llvm::GlobalValue::AppendingLinkage);
1060 
1061   // The LTO linker doesn't seem to like it when we set an alignment
1062   // on appending variables.  Take it off as a workaround.
1063   list->setAlignment(0);
1064 
1065   Fns.clear();
1066 }
1067 
1068 llvm::GlobalValue::LinkageTypes
1069 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1070   const auto *D = cast<FunctionDecl>(GD.getDecl());
1071 
1072   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1073 
1074   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1075     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1076 
1077   if (isa<CXXConstructorDecl>(D) &&
1078       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1079       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1080     // Our approach to inheriting constructors is fundamentally different from
1081     // that used by the MS ABI, so keep our inheriting constructor thunks
1082     // internal rather than trying to pick an unambiguous mangling for them.
1083     return llvm::GlobalValue::InternalLinkage;
1084   }
1085 
1086   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
1087 }
1088 
1089 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1090   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1091   if (!MDS) return nullptr;
1092 
1093   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1094 }
1095 
1096 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
1097                                               const CGFunctionInfo &Info,
1098                                               llvm::Function *F) {
1099   unsigned CallingConv;
1100   llvm::AttributeList PAL;
1101   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1102   F->setAttributes(PAL);
1103   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1104 }
1105 
1106 /// Determines whether the language options require us to model
1107 /// unwind exceptions.  We treat -fexceptions as mandating this
1108 /// except under the fragile ObjC ABI with only ObjC exceptions
1109 /// enabled.  This means, for example, that C with -fexceptions
1110 /// enables this.
1111 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1112   // If exceptions are completely disabled, obviously this is false.
1113   if (!LangOpts.Exceptions) return false;
1114 
1115   // If C++ exceptions are enabled, this is true.
1116   if (LangOpts.CXXExceptions) return true;
1117 
1118   // If ObjC exceptions are enabled, this depends on the ABI.
1119   if (LangOpts.ObjCExceptions) {
1120     return LangOpts.ObjCRuntime.hasUnwindExceptions();
1121   }
1122 
1123   return true;
1124 }
1125 
1126 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1127                                                            llvm::Function *F) {
1128   llvm::AttrBuilder B;
1129 
1130   if (CodeGenOpts.UnwindTables)
1131     B.addAttribute(llvm::Attribute::UWTable);
1132 
1133   if (!hasUnwindExceptions(LangOpts))
1134     B.addAttribute(llvm::Attribute::NoUnwind);
1135 
1136   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1137     B.addAttribute(llvm::Attribute::StackProtect);
1138   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1139     B.addAttribute(llvm::Attribute::StackProtectStrong);
1140   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1141     B.addAttribute(llvm::Attribute::StackProtectReq);
1142 
1143   if (!D) {
1144     // If we don't have a declaration to control inlining, the function isn't
1145     // explicitly marked as alwaysinline for semantic reasons, and inlining is
1146     // disabled, mark the function as noinline.
1147     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1148         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1149       B.addAttribute(llvm::Attribute::NoInline);
1150 
1151     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1152     return;
1153   }
1154 
1155   // Track whether we need to add the optnone LLVM attribute,
1156   // starting with the default for this optimization level.
1157   bool ShouldAddOptNone =
1158       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1159   // We can't add optnone in the following cases, it won't pass the verifier.
1160   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1161   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1162   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1163 
1164   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
1165     B.addAttribute(llvm::Attribute::OptimizeNone);
1166 
1167     // OptimizeNone implies noinline; we should not be inlining such functions.
1168     B.addAttribute(llvm::Attribute::NoInline);
1169     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1170            "OptimizeNone and AlwaysInline on same function!");
1171 
1172     // We still need to handle naked functions even though optnone subsumes
1173     // much of their semantics.
1174     if (D->hasAttr<NakedAttr>())
1175       B.addAttribute(llvm::Attribute::Naked);
1176 
1177     // OptimizeNone wins over OptimizeForSize and MinSize.
1178     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1179     F->removeFnAttr(llvm::Attribute::MinSize);
1180   } else if (D->hasAttr<NakedAttr>()) {
1181     // Naked implies noinline: we should not be inlining such functions.
1182     B.addAttribute(llvm::Attribute::Naked);
1183     B.addAttribute(llvm::Attribute::NoInline);
1184   } else if (D->hasAttr<NoDuplicateAttr>()) {
1185     B.addAttribute(llvm::Attribute::NoDuplicate);
1186   } else if (D->hasAttr<NoInlineAttr>()) {
1187     B.addAttribute(llvm::Attribute::NoInline);
1188   } else if (D->hasAttr<AlwaysInlineAttr>() &&
1189              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1190     // (noinline wins over always_inline, and we can't specify both in IR)
1191     B.addAttribute(llvm::Attribute::AlwaysInline);
1192   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1193     // If we're not inlining, then force everything that isn't always_inline to
1194     // carry an explicit noinline attribute.
1195     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1196       B.addAttribute(llvm::Attribute::NoInline);
1197   } else {
1198     // Otherwise, propagate the inline hint attribute and potentially use its
1199     // absence to mark things as noinline.
1200     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1201       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1202             return Redecl->isInlineSpecified();
1203           })) {
1204         B.addAttribute(llvm::Attribute::InlineHint);
1205       } else if (CodeGenOpts.getInlining() ==
1206                      CodeGenOptions::OnlyHintInlining &&
1207                  !FD->isInlined() &&
1208                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1209         B.addAttribute(llvm::Attribute::NoInline);
1210       }
1211     }
1212   }
1213 
1214   // Add other optimization related attributes if we are optimizing this
1215   // function.
1216   if (!D->hasAttr<OptimizeNoneAttr>()) {
1217     if (D->hasAttr<ColdAttr>()) {
1218       if (!ShouldAddOptNone)
1219         B.addAttribute(llvm::Attribute::OptimizeForSize);
1220       B.addAttribute(llvm::Attribute::Cold);
1221     }
1222 
1223     if (D->hasAttr<MinSizeAttr>())
1224       B.addAttribute(llvm::Attribute::MinSize);
1225   }
1226 
1227   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1228 
1229   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1230   if (alignment)
1231     F->setAlignment(alignment);
1232 
1233   // Some C++ ABIs require 2-byte alignment for member functions, in order to
1234   // reserve a bit for differentiating between virtual and non-virtual member
1235   // functions. If the current target's C++ ABI requires this and this is a
1236   // member function, set its alignment accordingly.
1237   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1238     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1239       F->setAlignment(2);
1240   }
1241 
1242   // In the cross-dso CFI mode, we want !type attributes on definitions only.
1243   if (CodeGenOpts.SanitizeCfiCrossDso)
1244     if (auto *FD = dyn_cast<FunctionDecl>(D))
1245       CreateFunctionTypeMetadata(FD, F);
1246 }
1247 
1248 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1249   const Decl *D = GD.getDecl();
1250   if (dyn_cast_or_null<NamedDecl>(D))
1251     setGVProperties(GV, GD);
1252   else
1253     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1254 
1255   if (D && D->hasAttr<UsedAttr>())
1256     addUsedGlobal(GV);
1257 }
1258 
1259 bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1260                                                 llvm::AttrBuilder &Attrs) {
1261   // Add target-cpu and target-features attributes to functions. If
1262   // we have a decl for the function and it has a target attribute then
1263   // parse that and add it to the feature set.
1264   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1265   std::vector<std::string> Features;
1266   const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1267   FD = FD ? FD->getMostRecentDecl() : FD;
1268   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1269   bool AddedAttr = false;
1270   if (TD) {
1271     llvm::StringMap<bool> FeatureMap;
1272     getFunctionFeatureMap(FeatureMap, FD);
1273 
1274     // Produce the canonical string for this set of features.
1275     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1276       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1277 
1278     // Now add the target-cpu and target-features to the function.
1279     // While we populated the feature map above, we still need to
1280     // get and parse the target attribute so we can get the cpu for
1281     // the function.
1282     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1283     if (ParsedAttr.Architecture != "" &&
1284         getTarget().isValidCPUName(ParsedAttr.Architecture))
1285       TargetCPU = ParsedAttr.Architecture;
1286   } else {
1287     // Otherwise just add the existing target cpu and target features to the
1288     // function.
1289     Features = getTarget().getTargetOpts().Features;
1290   }
1291 
1292   if (TargetCPU != "") {
1293     Attrs.addAttribute("target-cpu", TargetCPU);
1294     AddedAttr = true;
1295   }
1296   if (!Features.empty()) {
1297     std::sort(Features.begin(), Features.end());
1298     Attrs.addAttribute("target-features", llvm::join(Features, ","));
1299     AddedAttr = true;
1300   }
1301 
1302   return AddedAttr;
1303 }
1304 
1305 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1306                                           llvm::GlobalObject *GO) {
1307   const Decl *D = GD.getDecl();
1308   SetCommonAttributes(GD, GO);
1309 
1310   if (D) {
1311     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1312       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1313         GV->addAttribute("bss-section", SA->getName());
1314       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1315         GV->addAttribute("data-section", SA->getName());
1316       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1317         GV->addAttribute("rodata-section", SA->getName());
1318     }
1319 
1320     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1321       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1322         if (!D->getAttr<SectionAttr>())
1323           F->addFnAttr("implicit-section-name", SA->getName());
1324 
1325       llvm::AttrBuilder Attrs;
1326       if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1327         // We know that GetCPUAndFeaturesAttributes will always have the
1328         // newest set, since it has the newest possible FunctionDecl, so the
1329         // new ones should replace the old.
1330         F->removeFnAttr("target-cpu");
1331         F->removeFnAttr("target-features");
1332         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1333       }
1334     }
1335 
1336     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1337       GO->setSection(SA->getName());
1338   }
1339 
1340   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1341 }
1342 
1343 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1344                                                   llvm::Function *F,
1345                                                   const CGFunctionInfo &FI) {
1346   const Decl *D = GD.getDecl();
1347   SetLLVMFunctionAttributes(D, FI, F);
1348   SetLLVMFunctionAttributesForDefinition(D, F);
1349 
1350   F->setLinkage(llvm::Function::InternalLinkage);
1351 
1352   setNonAliasAttributes(GD, F);
1353 }
1354 
1355 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1356   // Set linkage and visibility in case we never see a definition.
1357   LinkageInfo LV = ND->getLinkageAndVisibility();
1358   // Don't set internal linkage on declarations.
1359   // "extern_weak" is overloaded in LLVM; we probably should have
1360   // separate linkage types for this.
1361   if (isExternallyVisible(LV.getLinkage()) &&
1362       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1363     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1364 }
1365 
1366 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1367                                                llvm::Function *F) {
1368   // Only if we are checking indirect calls.
1369   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1370     return;
1371 
1372   // Non-static class methods are handled via vtable pointer checks elsewhere.
1373   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1374     return;
1375 
1376   // Additionally, if building with cross-DSO support...
1377   if (CodeGenOpts.SanitizeCfiCrossDso) {
1378     // Skip available_externally functions. They won't be codegen'ed in the
1379     // current module anyway.
1380     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1381       return;
1382   }
1383 
1384   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1385   F->addTypeMetadata(0, MD);
1386   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1387 
1388   // Emit a hash-based bit set entry for cross-DSO calls.
1389   if (CodeGenOpts.SanitizeCfiCrossDso)
1390     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1391       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1392 }
1393 
1394 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1395                                           bool IsIncompleteFunction,
1396                                           bool IsThunk) {
1397 
1398   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1399     // If this is an intrinsic function, set the function's attributes
1400     // to the intrinsic's attributes.
1401     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1402     return;
1403   }
1404 
1405   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1406 
1407   if (!IsIncompleteFunction) {
1408     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1409     // Setup target-specific attributes.
1410     if (F->isDeclaration())
1411       getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1412   }
1413 
1414   // Add the Returned attribute for "this", except for iOS 5 and earlier
1415   // where substantial code, including the libstdc++ dylib, was compiled with
1416   // GCC and does not actually return "this".
1417   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1418       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1419     assert(!F->arg_empty() &&
1420            F->arg_begin()->getType()
1421              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1422            "unexpected this return");
1423     F->addAttribute(1, llvm::Attribute::Returned);
1424   }
1425 
1426   // Only a few attributes are set on declarations; these may later be
1427   // overridden by a definition.
1428 
1429   setLinkageForGV(F, FD);
1430   setGVProperties(F, FD);
1431 
1432   if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1433     F->addFnAttr("implicit-section-name");
1434   }
1435 
1436   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1437     F->setSection(SA->getName());
1438 
1439   if (FD->isReplaceableGlobalAllocationFunction()) {
1440     // A replaceable global allocation function does not act like a builtin by
1441     // default, only if it is invoked by a new-expression or delete-expression.
1442     F->addAttribute(llvm::AttributeList::FunctionIndex,
1443                     llvm::Attribute::NoBuiltin);
1444 
1445     // A sane operator new returns a non-aliasing pointer.
1446     // FIXME: Also add NonNull attribute to the return value
1447     // for the non-nothrow forms?
1448     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1449     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1450         (Kind == OO_New || Kind == OO_Array_New))
1451       F->addAttribute(llvm::AttributeList::ReturnIndex,
1452                       llvm::Attribute::NoAlias);
1453   }
1454 
1455   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1456     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1457   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1458     if (MD->isVirtual())
1459       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1460 
1461   // Don't emit entries for function declarations in the cross-DSO mode. This
1462   // is handled with better precision by the receiving DSO.
1463   if (!CodeGenOpts.SanitizeCfiCrossDso)
1464     CreateFunctionTypeMetadata(FD, F);
1465 
1466   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1467     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1468 }
1469 
1470 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1471   assert(!GV->isDeclaration() &&
1472          "Only globals with definition can force usage.");
1473   LLVMUsed.emplace_back(GV);
1474 }
1475 
1476 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1477   assert(!GV->isDeclaration() &&
1478          "Only globals with definition can force usage.");
1479   LLVMCompilerUsed.emplace_back(GV);
1480 }
1481 
1482 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1483                      std::vector<llvm::WeakTrackingVH> &List) {
1484   // Don't create llvm.used if there is no need.
1485   if (List.empty())
1486     return;
1487 
1488   // Convert List to what ConstantArray needs.
1489   SmallVector<llvm::Constant*, 8> UsedArray;
1490   UsedArray.resize(List.size());
1491   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1492     UsedArray[i] =
1493         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1494             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1495   }
1496 
1497   if (UsedArray.empty())
1498     return;
1499   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1500 
1501   auto *GV = new llvm::GlobalVariable(
1502       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1503       llvm::ConstantArray::get(ATy, UsedArray), Name);
1504 
1505   GV->setSection("llvm.metadata");
1506 }
1507 
1508 void CodeGenModule::emitLLVMUsed() {
1509   emitUsed(*this, "llvm.used", LLVMUsed);
1510   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1511 }
1512 
1513 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1514   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1515   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1516 }
1517 
1518 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1519   llvm::SmallString<32> Opt;
1520   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1521   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1522   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1523 }
1524 
1525 void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1526   auto &C = getLLVMContext();
1527   LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1528       C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1529 }
1530 
1531 void CodeGenModule::AddDependentLib(StringRef Lib) {
1532   llvm::SmallString<24> Opt;
1533   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1534   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1535   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1536 }
1537 
1538 /// \brief Add link options implied by the given module, including modules
1539 /// it depends on, using a postorder walk.
1540 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1541                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1542                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1543   // Import this module's parent.
1544   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1545     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1546   }
1547 
1548   // Import this module's dependencies.
1549   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1550     if (Visited.insert(Mod->Imports[I - 1]).second)
1551       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1552   }
1553 
1554   // Add linker options to link against the libraries/frameworks
1555   // described by this module.
1556   llvm::LLVMContext &Context = CGM.getLLVMContext();
1557   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1558     // Link against a framework.  Frameworks are currently Darwin only, so we
1559     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1560     if (Mod->LinkLibraries[I-1].IsFramework) {
1561       llvm::Metadata *Args[2] = {
1562           llvm::MDString::get(Context, "-framework"),
1563           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1564 
1565       Metadata.push_back(llvm::MDNode::get(Context, Args));
1566       continue;
1567     }
1568 
1569     // Link against a library.
1570     llvm::SmallString<24> Opt;
1571     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1572       Mod->LinkLibraries[I-1].Library, Opt);
1573     auto *OptString = llvm::MDString::get(Context, Opt);
1574     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1575   }
1576 }
1577 
1578 void CodeGenModule::EmitModuleLinkOptions() {
1579   // Collect the set of all of the modules we want to visit to emit link
1580   // options, which is essentially the imported modules and all of their
1581   // non-explicit child modules.
1582   llvm::SetVector<clang::Module *> LinkModules;
1583   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1584   SmallVector<clang::Module *, 16> Stack;
1585 
1586   // Seed the stack with imported modules.
1587   for (Module *M : ImportedModules) {
1588     // Do not add any link flags when an implementation TU of a module imports
1589     // a header of that same module.
1590     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1591         !getLangOpts().isCompilingModule())
1592       continue;
1593     if (Visited.insert(M).second)
1594       Stack.push_back(M);
1595   }
1596 
1597   // Find all of the modules to import, making a little effort to prune
1598   // non-leaf modules.
1599   while (!Stack.empty()) {
1600     clang::Module *Mod = Stack.pop_back_val();
1601 
1602     bool AnyChildren = false;
1603 
1604     // Visit the submodules of this module.
1605     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1606                                         SubEnd = Mod->submodule_end();
1607          Sub != SubEnd; ++Sub) {
1608       // Skip explicit children; they need to be explicitly imported to be
1609       // linked against.
1610       if ((*Sub)->IsExplicit)
1611         continue;
1612 
1613       if (Visited.insert(*Sub).second) {
1614         Stack.push_back(*Sub);
1615         AnyChildren = true;
1616       }
1617     }
1618 
1619     // We didn't find any children, so add this module to the list of
1620     // modules to link against.
1621     if (!AnyChildren) {
1622       LinkModules.insert(Mod);
1623     }
1624   }
1625 
1626   // Add link options for all of the imported modules in reverse topological
1627   // order.  We don't do anything to try to order import link flags with respect
1628   // to linker options inserted by things like #pragma comment().
1629   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1630   Visited.clear();
1631   for (Module *M : LinkModules)
1632     if (Visited.insert(M).second)
1633       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1634   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1635   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1636 
1637   // Add the linker options metadata flag.
1638   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1639   for (auto *MD : LinkerOptionsMetadata)
1640     NMD->addOperand(MD);
1641 }
1642 
1643 void CodeGenModule::EmitDeferred() {
1644   // Emit code for any potentially referenced deferred decls.  Since a
1645   // previously unused static decl may become used during the generation of code
1646   // for a static function, iterate until no changes are made.
1647 
1648   if (!DeferredVTables.empty()) {
1649     EmitDeferredVTables();
1650 
1651     // Emitting a vtable doesn't directly cause more vtables to
1652     // become deferred, although it can cause functions to be
1653     // emitted that then need those vtables.
1654     assert(DeferredVTables.empty());
1655   }
1656 
1657   // Stop if we're out of both deferred vtables and deferred declarations.
1658   if (DeferredDeclsToEmit.empty())
1659     return;
1660 
1661   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1662   // work, it will not interfere with this.
1663   std::vector<GlobalDecl> CurDeclsToEmit;
1664   CurDeclsToEmit.swap(DeferredDeclsToEmit);
1665 
1666   for (GlobalDecl &D : CurDeclsToEmit) {
1667     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1668     // to get GlobalValue with exactly the type we need, not something that
1669     // might had been created for another decl with the same mangled name but
1670     // different type.
1671     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1672         GetAddrOfGlobal(D, ForDefinition));
1673 
1674     // In case of different address spaces, we may still get a cast, even with
1675     // IsForDefinition equal to true. Query mangled names table to get
1676     // GlobalValue.
1677     if (!GV)
1678       GV = GetGlobalValue(getMangledName(D));
1679 
1680     // Make sure GetGlobalValue returned non-null.
1681     assert(GV);
1682 
1683     // Check to see if we've already emitted this.  This is necessary
1684     // for a couple of reasons: first, decls can end up in the
1685     // deferred-decls queue multiple times, and second, decls can end
1686     // up with definitions in unusual ways (e.g. by an extern inline
1687     // function acquiring a strong function redefinition).  Just
1688     // ignore these cases.
1689     if (!GV->isDeclaration())
1690       continue;
1691 
1692     // Otherwise, emit the definition and move on to the next one.
1693     EmitGlobalDefinition(D, GV);
1694 
1695     // If we found out that we need to emit more decls, do that recursively.
1696     // This has the advantage that the decls are emitted in a DFS and related
1697     // ones are close together, which is convenient for testing.
1698     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1699       EmitDeferred();
1700       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1701     }
1702   }
1703 }
1704 
1705 void CodeGenModule::EmitVTablesOpportunistically() {
1706   // Try to emit external vtables as available_externally if they have emitted
1707   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1708   // is not allowed to create new references to things that need to be emitted
1709   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1710 
1711   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1712          && "Only emit opportunistic vtables with optimizations");
1713 
1714   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1715     assert(getVTables().isVTableExternal(RD) &&
1716            "This queue should only contain external vtables");
1717     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1718       VTables.GenerateClassData(RD);
1719   }
1720   OpportunisticVTables.clear();
1721 }
1722 
1723 void CodeGenModule::EmitGlobalAnnotations() {
1724   if (Annotations.empty())
1725     return;
1726 
1727   // Create a new global variable for the ConstantStruct in the Module.
1728   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1729     Annotations[0]->getType(), Annotations.size()), Annotations);
1730   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1731                                       llvm::GlobalValue::AppendingLinkage,
1732                                       Array, "llvm.global.annotations");
1733   gv->setSection(AnnotationSection);
1734 }
1735 
1736 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1737   llvm::Constant *&AStr = AnnotationStrings[Str];
1738   if (AStr)
1739     return AStr;
1740 
1741   // Not found yet, create a new global.
1742   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1743   auto *gv =
1744       new llvm::GlobalVariable(getModule(), s->getType(), true,
1745                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1746   gv->setSection(AnnotationSection);
1747   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1748   AStr = gv;
1749   return gv;
1750 }
1751 
1752 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1753   SourceManager &SM = getContext().getSourceManager();
1754   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1755   if (PLoc.isValid())
1756     return EmitAnnotationString(PLoc.getFilename());
1757   return EmitAnnotationString(SM.getBufferName(Loc));
1758 }
1759 
1760 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1761   SourceManager &SM = getContext().getSourceManager();
1762   PresumedLoc PLoc = SM.getPresumedLoc(L);
1763   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1764     SM.getExpansionLineNumber(L);
1765   return llvm::ConstantInt::get(Int32Ty, LineNo);
1766 }
1767 
1768 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1769                                                 const AnnotateAttr *AA,
1770                                                 SourceLocation L) {
1771   // Get the globals for file name, annotation, and the line number.
1772   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1773                  *UnitGV = EmitAnnotationUnit(L),
1774                  *LineNoCst = EmitAnnotationLineNo(L);
1775 
1776   // Create the ConstantStruct for the global annotation.
1777   llvm::Constant *Fields[4] = {
1778     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1779     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1780     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1781     LineNoCst
1782   };
1783   return llvm::ConstantStruct::getAnon(Fields);
1784 }
1785 
1786 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1787                                          llvm::GlobalValue *GV) {
1788   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1789   // Get the struct elements for these annotations.
1790   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1791     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1792 }
1793 
1794 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1795                                            llvm::Function *Fn,
1796                                            SourceLocation Loc) const {
1797   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1798   // Blacklist by function name.
1799   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1800     return true;
1801   // Blacklist by location.
1802   if (Loc.isValid())
1803     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
1804   // If location is unknown, this may be a compiler-generated function. Assume
1805   // it's located in the main file.
1806   auto &SM = Context.getSourceManager();
1807   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1808     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1809   }
1810   return false;
1811 }
1812 
1813 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1814                                            SourceLocation Loc, QualType Ty,
1815                                            StringRef Category) const {
1816   // For now globals can be blacklisted only in ASan and KASan.
1817   const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
1818       (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
1819   if (!EnabledAsanMask)
1820     return false;
1821   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1822   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
1823     return true;
1824   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1825     return true;
1826   // Check global type.
1827   if (!Ty.isNull()) {
1828     // Drill down the array types: if global variable of a fixed type is
1829     // blacklisted, we also don't instrument arrays of them.
1830     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1831       Ty = AT->getElementType();
1832     Ty = Ty.getCanonicalType().getUnqualifiedType();
1833     // We allow to blacklist only record types (classes, structs etc.)
1834     if (Ty->isRecordType()) {
1835       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1836       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1837         return true;
1838     }
1839   }
1840   return false;
1841 }
1842 
1843 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1844                                    StringRef Category) const {
1845   if (!LangOpts.XRayInstrument)
1846     return false;
1847   const auto &XRayFilter = getContext().getXRayFilter();
1848   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1849   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1850   if (Loc.isValid())
1851     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1852   if (Attr == ImbueAttr::NONE)
1853     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1854   switch (Attr) {
1855   case ImbueAttr::NONE:
1856     return false;
1857   case ImbueAttr::ALWAYS:
1858     Fn->addFnAttr("function-instrument", "xray-always");
1859     break;
1860   case ImbueAttr::ALWAYS_ARG1:
1861     Fn->addFnAttr("function-instrument", "xray-always");
1862     Fn->addFnAttr("xray-log-args", "1");
1863     break;
1864   case ImbueAttr::NEVER:
1865     Fn->addFnAttr("function-instrument", "xray-never");
1866     break;
1867   }
1868   return true;
1869 }
1870 
1871 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1872   // Never defer when EmitAllDecls is specified.
1873   if (LangOpts.EmitAllDecls)
1874     return true;
1875 
1876   return getContext().DeclMustBeEmitted(Global);
1877 }
1878 
1879 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1880   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1881     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1882       // Implicit template instantiations may change linkage if they are later
1883       // explicitly instantiated, so they should not be emitted eagerly.
1884       return false;
1885   if (const auto *VD = dyn_cast<VarDecl>(Global))
1886     if (Context.getInlineVariableDefinitionKind(VD) ==
1887         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1888       // A definition of an inline constexpr static data member may change
1889       // linkage later if it's redeclared outside the class.
1890       return false;
1891   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1892   // codegen for global variables, because they may be marked as threadprivate.
1893   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1894       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1895     return false;
1896 
1897   return true;
1898 }
1899 
1900 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1901     const CXXUuidofExpr* E) {
1902   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1903   // well-formed.
1904   StringRef Uuid = E->getUuidStr();
1905   std::string Name = "_GUID_" + Uuid.lower();
1906   std::replace(Name.begin(), Name.end(), '-', '_');
1907 
1908   // The UUID descriptor should be pointer aligned.
1909   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1910 
1911   // Look for an existing global.
1912   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1913     return ConstantAddress(GV, Alignment);
1914 
1915   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1916   assert(Init && "failed to initialize as constant");
1917 
1918   auto *GV = new llvm::GlobalVariable(
1919       getModule(), Init->getType(),
1920       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1921   if (supportsCOMDAT())
1922     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1923   setDSOLocal(GV);
1924   return ConstantAddress(GV, Alignment);
1925 }
1926 
1927 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1928   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1929   assert(AA && "No alias?");
1930 
1931   CharUnits Alignment = getContext().getDeclAlign(VD);
1932   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1933 
1934   // See if there is already something with the target's name in the module.
1935   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1936   if (Entry) {
1937     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1938     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1939     return ConstantAddress(Ptr, Alignment);
1940   }
1941 
1942   llvm::Constant *Aliasee;
1943   if (isa<llvm::FunctionType>(DeclTy))
1944     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1945                                       GlobalDecl(cast<FunctionDecl>(VD)),
1946                                       /*ForVTable=*/false);
1947   else
1948     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1949                                     llvm::PointerType::getUnqual(DeclTy),
1950                                     nullptr);
1951 
1952   auto *F = cast<llvm::GlobalValue>(Aliasee);
1953   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1954   WeakRefReferences.insert(F);
1955 
1956   return ConstantAddress(Aliasee, Alignment);
1957 }
1958 
1959 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1960   const auto *Global = cast<ValueDecl>(GD.getDecl());
1961 
1962   // Weak references don't produce any output by themselves.
1963   if (Global->hasAttr<WeakRefAttr>())
1964     return;
1965 
1966   // If this is an alias definition (which otherwise looks like a declaration)
1967   // emit it now.
1968   if (Global->hasAttr<AliasAttr>())
1969     return EmitAliasDefinition(GD);
1970 
1971   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1972   if (Global->hasAttr<IFuncAttr>())
1973     return emitIFuncDefinition(GD);
1974 
1975   // If this is CUDA, be selective about which declarations we emit.
1976   if (LangOpts.CUDA) {
1977     if (LangOpts.CUDAIsDevice) {
1978       if (!Global->hasAttr<CUDADeviceAttr>() &&
1979           !Global->hasAttr<CUDAGlobalAttr>() &&
1980           !Global->hasAttr<CUDAConstantAttr>() &&
1981           !Global->hasAttr<CUDASharedAttr>())
1982         return;
1983     } else {
1984       // We need to emit host-side 'shadows' for all global
1985       // device-side variables because the CUDA runtime needs their
1986       // size and host-side address in order to provide access to
1987       // their device-side incarnations.
1988 
1989       // So device-only functions are the only things we skip.
1990       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1991           Global->hasAttr<CUDADeviceAttr>())
1992         return;
1993 
1994       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1995              "Expected Variable or Function");
1996     }
1997   }
1998 
1999   if (LangOpts.OpenMP) {
2000     // If this is OpenMP device, check if it is legal to emit this global
2001     // normally.
2002     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2003       return;
2004     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2005       if (MustBeEmitted(Global))
2006         EmitOMPDeclareReduction(DRD);
2007       return;
2008     }
2009   }
2010 
2011   // Ignore declarations, they will be emitted on their first use.
2012   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2013     // Forward declarations are emitted lazily on first use.
2014     if (!FD->doesThisDeclarationHaveABody()) {
2015       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2016         return;
2017 
2018       StringRef MangledName = getMangledName(GD);
2019 
2020       // Compute the function info and LLVM type.
2021       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2022       llvm::Type *Ty = getTypes().GetFunctionType(FI);
2023 
2024       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2025                               /*DontDefer=*/false);
2026       return;
2027     }
2028   } else {
2029     const auto *VD = cast<VarDecl>(Global);
2030     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2031     // We need to emit device-side global CUDA variables even if a
2032     // variable does not have a definition -- we still need to define
2033     // host-side shadow for it.
2034     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2035                            !VD->hasDefinition() &&
2036                            (VD->hasAttr<CUDAConstantAttr>() ||
2037                             VD->hasAttr<CUDADeviceAttr>());
2038     if (!MustEmitForCuda &&
2039         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2040         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2041       // If this declaration may have caused an inline variable definition to
2042       // change linkage, make sure that it's emitted.
2043       if (Context.getInlineVariableDefinitionKind(VD) ==
2044           ASTContext::InlineVariableDefinitionKind::Strong)
2045         GetAddrOfGlobalVar(VD);
2046       return;
2047     }
2048   }
2049 
2050   // Defer code generation to first use when possible, e.g. if this is an inline
2051   // function. If the global must always be emitted, do it eagerly if possible
2052   // to benefit from cache locality.
2053   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2054     // Emit the definition if it can't be deferred.
2055     EmitGlobalDefinition(GD);
2056     return;
2057   }
2058 
2059   // If we're deferring emission of a C++ variable with an
2060   // initializer, remember the order in which it appeared in the file.
2061   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2062       cast<VarDecl>(Global)->hasInit()) {
2063     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2064     CXXGlobalInits.push_back(nullptr);
2065   }
2066 
2067   StringRef MangledName = getMangledName(GD);
2068   if (GetGlobalValue(MangledName) != nullptr) {
2069     // The value has already been used and should therefore be emitted.
2070     addDeferredDeclToEmit(GD);
2071   } else if (MustBeEmitted(Global)) {
2072     // The value must be emitted, but cannot be emitted eagerly.
2073     assert(!MayBeEmittedEagerly(Global));
2074     addDeferredDeclToEmit(GD);
2075   } else {
2076     // Otherwise, remember that we saw a deferred decl with this name.  The
2077     // first use of the mangled name will cause it to move into
2078     // DeferredDeclsToEmit.
2079     DeferredDecls[MangledName] = GD;
2080   }
2081 }
2082 
2083 // Check if T is a class type with a destructor that's not dllimport.
2084 static bool HasNonDllImportDtor(QualType T) {
2085   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2086     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2087       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2088         return true;
2089 
2090   return false;
2091 }
2092 
2093 namespace {
2094   struct FunctionIsDirectlyRecursive :
2095     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2096     const StringRef Name;
2097     const Builtin::Context &BI;
2098     bool Result;
2099     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2100       Name(N), BI(C), Result(false) {
2101     }
2102     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2103 
2104     bool TraverseCallExpr(CallExpr *E) {
2105       const FunctionDecl *FD = E->getDirectCallee();
2106       if (!FD)
2107         return true;
2108       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2109       if (Attr && Name == Attr->getLabel()) {
2110         Result = true;
2111         return false;
2112       }
2113       unsigned BuiltinID = FD->getBuiltinID();
2114       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2115         return true;
2116       StringRef BuiltinName = BI.getName(BuiltinID);
2117       if (BuiltinName.startswith("__builtin_") &&
2118           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2119         Result = true;
2120         return false;
2121       }
2122       return true;
2123     }
2124   };
2125 
2126   // Make sure we're not referencing non-imported vars or functions.
2127   struct DLLImportFunctionVisitor
2128       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2129     bool SafeToInline = true;
2130 
2131     bool shouldVisitImplicitCode() const { return true; }
2132 
2133     bool VisitVarDecl(VarDecl *VD) {
2134       if (VD->getTLSKind()) {
2135         // A thread-local variable cannot be imported.
2136         SafeToInline = false;
2137         return SafeToInline;
2138       }
2139 
2140       // A variable definition might imply a destructor call.
2141       if (VD->isThisDeclarationADefinition())
2142         SafeToInline = !HasNonDllImportDtor(VD->getType());
2143 
2144       return SafeToInline;
2145     }
2146 
2147     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2148       if (const auto *D = E->getTemporary()->getDestructor())
2149         SafeToInline = D->hasAttr<DLLImportAttr>();
2150       return SafeToInline;
2151     }
2152 
2153     bool VisitDeclRefExpr(DeclRefExpr *E) {
2154       ValueDecl *VD = E->getDecl();
2155       if (isa<FunctionDecl>(VD))
2156         SafeToInline = VD->hasAttr<DLLImportAttr>();
2157       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2158         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2159       return SafeToInline;
2160     }
2161 
2162     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2163       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2164       return SafeToInline;
2165     }
2166 
2167     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2168       CXXMethodDecl *M = E->getMethodDecl();
2169       if (!M) {
2170         // Call through a pointer to member function. This is safe to inline.
2171         SafeToInline = true;
2172       } else {
2173         SafeToInline = M->hasAttr<DLLImportAttr>();
2174       }
2175       return SafeToInline;
2176     }
2177 
2178     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2179       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2180       return SafeToInline;
2181     }
2182 
2183     bool VisitCXXNewExpr(CXXNewExpr *E) {
2184       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2185       return SafeToInline;
2186     }
2187   };
2188 }
2189 
2190 // isTriviallyRecursive - Check if this function calls another
2191 // decl that, because of the asm attribute or the other decl being a builtin,
2192 // ends up pointing to itself.
2193 bool
2194 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2195   StringRef Name;
2196   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2197     // asm labels are a special kind of mangling we have to support.
2198     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2199     if (!Attr)
2200       return false;
2201     Name = Attr->getLabel();
2202   } else {
2203     Name = FD->getName();
2204   }
2205 
2206   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2207   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2208   return Walker.Result;
2209 }
2210 
2211 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2212   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2213     return true;
2214   const auto *F = cast<FunctionDecl>(GD.getDecl());
2215   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2216     return false;
2217 
2218   if (F->hasAttr<DLLImportAttr>()) {
2219     // Check whether it would be safe to inline this dllimport function.
2220     DLLImportFunctionVisitor Visitor;
2221     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2222     if (!Visitor.SafeToInline)
2223       return false;
2224 
2225     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2226       // Implicit destructor invocations aren't captured in the AST, so the
2227       // check above can't see them. Check for them manually here.
2228       for (const Decl *Member : Dtor->getParent()->decls())
2229         if (isa<FieldDecl>(Member))
2230           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2231             return false;
2232       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2233         if (HasNonDllImportDtor(B.getType()))
2234           return false;
2235     }
2236   }
2237 
2238   // PR9614. Avoid cases where the source code is lying to us. An available
2239   // externally function should have an equivalent function somewhere else,
2240   // but a function that calls itself is clearly not equivalent to the real
2241   // implementation.
2242   // This happens in glibc's btowc and in some configure checks.
2243   return !isTriviallyRecursive(F);
2244 }
2245 
2246 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2247   return CodeGenOpts.OptimizationLevel > 0;
2248 }
2249 
2250 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2251   const auto *D = cast<ValueDecl>(GD.getDecl());
2252 
2253   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2254                                  Context.getSourceManager(),
2255                                  "Generating code for declaration");
2256 
2257   if (isa<FunctionDecl>(D)) {
2258     // At -O0, don't generate IR for functions with available_externally
2259     // linkage.
2260     if (!shouldEmitFunction(GD))
2261       return;
2262 
2263     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2264       // Make sure to emit the definition(s) before we emit the thunks.
2265       // This is necessary for the generation of certain thunks.
2266       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2267         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2268       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2269         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2270       else
2271         EmitGlobalFunctionDefinition(GD, GV);
2272 
2273       if (Method->isVirtual())
2274         getVTables().EmitThunks(GD);
2275 
2276       return;
2277     }
2278 
2279     return EmitGlobalFunctionDefinition(GD, GV);
2280   }
2281 
2282   if (const auto *VD = dyn_cast<VarDecl>(D))
2283     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2284 
2285   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2286 }
2287 
2288 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2289                                                       llvm::Function *NewFn);
2290 
2291 void CodeGenModule::emitMultiVersionFunctions() {
2292   for (GlobalDecl GD : MultiVersionFuncs) {
2293     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2294     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2295     getContext().forEachMultiversionedFunctionVersion(
2296         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2297           GlobalDecl CurGD{
2298               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2299           StringRef MangledName = getMangledName(CurGD);
2300           llvm::Constant *Func = GetGlobalValue(MangledName);
2301           if (!Func) {
2302             if (CurFD->isDefined()) {
2303               EmitGlobalFunctionDefinition(CurGD, nullptr);
2304               Func = GetGlobalValue(MangledName);
2305             } else {
2306               const CGFunctionInfo &FI =
2307                   getTypes().arrangeGlobalDeclaration(GD);
2308               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2309               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2310                                        /*DontDefer=*/false, ForDefinition);
2311             }
2312             assert(Func && "This should have just been created");
2313           }
2314           Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2315                                CurFD->getAttr<TargetAttr>()->parse());
2316         });
2317 
2318     llvm::Function *ResolverFunc = cast<llvm::Function>(
2319         GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2320     if (supportsCOMDAT())
2321       ResolverFunc->setComdat(
2322           getModule().getOrInsertComdat(ResolverFunc->getName()));
2323     std::stable_sort(
2324         Options.begin(), Options.end(),
2325         std::greater<CodeGenFunction::MultiVersionResolverOption>());
2326     CodeGenFunction CGF(*this);
2327     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2328   }
2329 }
2330 
2331 /// If an ifunc for the specified mangled name is not in the module, create and
2332 /// return an llvm IFunc Function with the specified type.
2333 llvm::Constant *
2334 CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2335                                             StringRef MangledName,
2336                                             const FunctionDecl *FD) {
2337   std::string IFuncName = (MangledName + ".ifunc").str();
2338   if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2339     return IFuncGV;
2340 
2341   // Since this is the first time we've created this IFunc, make sure
2342   // that we put this multiversioned function into the list to be
2343   // replaced later.
2344   MultiVersionFuncs.push_back(GD);
2345 
2346   std::string ResolverName = (MangledName + ".resolver").str();
2347   llvm::Type *ResolverType = llvm::FunctionType::get(
2348       llvm::PointerType::get(DeclTy,
2349                              Context.getTargetAddressSpace(FD->getType())),
2350       false);
2351   llvm::Constant *Resolver =
2352       GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2353                               /*ForVTable=*/false);
2354   llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2355       DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2356   GIF->setName(IFuncName);
2357   SetCommonAttributes(FD, GIF);
2358 
2359   return GIF;
2360 }
2361 
2362 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2363 /// module, create and return an llvm Function with the specified type. If there
2364 /// is something in the module with the specified name, return it potentially
2365 /// bitcasted to the right type.
2366 ///
2367 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2368 /// to set the attributes on the function when it is first created.
2369 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2370     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2371     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2372     ForDefinition_t IsForDefinition) {
2373   const Decl *D = GD.getDecl();
2374 
2375   // Any attempts to use a MultiVersion function should result in retrieving
2376   // the iFunc instead. Name Mangling will handle the rest of the changes.
2377   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2378     // For the device mark the function as one that should be emitted.
2379     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2380         !OpenMPRuntime->markAsGlobalTarget(FD) && FD->isDefined() &&
2381         !DontDefer && !IsForDefinition)
2382       addDeferredDeclToEmit(GD);
2383 
2384     if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
2385       UpdateMultiVersionNames(GD, FD);
2386       if (!IsForDefinition)
2387         return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
2388     }
2389   }
2390 
2391   // Lookup the entry, lazily creating it if necessary.
2392   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2393   if (Entry) {
2394     if (WeakRefReferences.erase(Entry)) {
2395       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2396       if (FD && !FD->hasAttr<WeakAttr>())
2397         Entry->setLinkage(llvm::Function::ExternalLinkage);
2398     }
2399 
2400     // Handle dropped DLL attributes.
2401     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2402       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2403 
2404     // If there are two attempts to define the same mangled name, issue an
2405     // error.
2406     if (IsForDefinition && !Entry->isDeclaration()) {
2407       GlobalDecl OtherGD;
2408       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2409       // to make sure that we issue an error only once.
2410       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2411           (GD.getCanonicalDecl().getDecl() !=
2412            OtherGD.getCanonicalDecl().getDecl()) &&
2413           DiagnosedConflictingDefinitions.insert(GD).second) {
2414         getDiags().Report(D->getLocation(),
2415                           diag::err_duplicate_mangled_name);
2416         getDiags().Report(OtherGD.getDecl()->getLocation(),
2417                           diag::note_previous_definition);
2418       }
2419     }
2420 
2421     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2422         (Entry->getType()->getElementType() == Ty)) {
2423       return Entry;
2424     }
2425 
2426     // Make sure the result is of the correct type.
2427     // (If function is requested for a definition, we always need to create a new
2428     // function, not just return a bitcast.)
2429     if (!IsForDefinition)
2430       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2431   }
2432 
2433   // This function doesn't have a complete type (for example, the return
2434   // type is an incomplete struct). Use a fake type instead, and make
2435   // sure not to try to set attributes.
2436   bool IsIncompleteFunction = false;
2437 
2438   llvm::FunctionType *FTy;
2439   if (isa<llvm::FunctionType>(Ty)) {
2440     FTy = cast<llvm::FunctionType>(Ty);
2441   } else {
2442     FTy = llvm::FunctionType::get(VoidTy, false);
2443     IsIncompleteFunction = true;
2444   }
2445 
2446   llvm::Function *F =
2447       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2448                              Entry ? StringRef() : MangledName, &getModule());
2449 
2450   // If we already created a function with the same mangled name (but different
2451   // type) before, take its name and add it to the list of functions to be
2452   // replaced with F at the end of CodeGen.
2453   //
2454   // This happens if there is a prototype for a function (e.g. "int f()") and
2455   // then a definition of a different type (e.g. "int f(int x)").
2456   if (Entry) {
2457     F->takeName(Entry);
2458 
2459     // This might be an implementation of a function without a prototype, in
2460     // which case, try to do special replacement of calls which match the new
2461     // prototype.  The really key thing here is that we also potentially drop
2462     // arguments from the call site so as to make a direct call, which makes the
2463     // inliner happier and suppresses a number of optimizer warnings (!) about
2464     // dropping arguments.
2465     if (!Entry->use_empty()) {
2466       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2467       Entry->removeDeadConstantUsers();
2468     }
2469 
2470     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2471         F, Entry->getType()->getElementType()->getPointerTo());
2472     addGlobalValReplacement(Entry, BC);
2473   }
2474 
2475   assert(F->getName() == MangledName && "name was uniqued!");
2476   if (D)
2477     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2478   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2479     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2480     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2481   }
2482 
2483   if (!DontDefer) {
2484     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2485     // each other bottoming out with the base dtor.  Therefore we emit non-base
2486     // dtors on usage, even if there is no dtor definition in the TU.
2487     if (D && isa<CXXDestructorDecl>(D) &&
2488         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2489                                            GD.getDtorType()))
2490       addDeferredDeclToEmit(GD);
2491 
2492     // This is the first use or definition of a mangled name.  If there is a
2493     // deferred decl with this name, remember that we need to emit it at the end
2494     // of the file.
2495     auto DDI = DeferredDecls.find(MangledName);
2496     if (DDI != DeferredDecls.end()) {
2497       // Move the potentially referenced deferred decl to the
2498       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2499       // don't need it anymore).
2500       addDeferredDeclToEmit(DDI->second);
2501       DeferredDecls.erase(DDI);
2502 
2503       // Otherwise, there are cases we have to worry about where we're
2504       // using a declaration for which we must emit a definition but where
2505       // we might not find a top-level definition:
2506       //   - member functions defined inline in their classes
2507       //   - friend functions defined inline in some class
2508       //   - special member functions with implicit definitions
2509       // If we ever change our AST traversal to walk into class methods,
2510       // this will be unnecessary.
2511       //
2512       // We also don't emit a definition for a function if it's going to be an
2513       // entry in a vtable, unless it's already marked as used.
2514     } else if (getLangOpts().CPlusPlus && D) {
2515       // Look for a declaration that's lexically in a record.
2516       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2517            FD = FD->getPreviousDecl()) {
2518         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2519           if (FD->doesThisDeclarationHaveABody()) {
2520             addDeferredDeclToEmit(GD.getWithDecl(FD));
2521             break;
2522           }
2523         }
2524       }
2525     }
2526   }
2527 
2528   // Make sure the result is of the requested type.
2529   if (!IsIncompleteFunction) {
2530     assert(F->getType()->getElementType() == Ty);
2531     return F;
2532   }
2533 
2534   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2535   return llvm::ConstantExpr::getBitCast(F, PTy);
2536 }
2537 
2538 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2539 /// non-null, then this function will use the specified type if it has to
2540 /// create it (this occurs when we see a definition of the function).
2541 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2542                                                  llvm::Type *Ty,
2543                                                  bool ForVTable,
2544                                                  bool DontDefer,
2545                                               ForDefinition_t IsForDefinition) {
2546   // If there was no specific requested type, just convert it now.
2547   if (!Ty) {
2548     const auto *FD = cast<FunctionDecl>(GD.getDecl());
2549     auto CanonTy = Context.getCanonicalType(FD->getType());
2550     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2551   }
2552 
2553   // Devirtualized destructor calls may come through here instead of via
2554   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2555   // of the complete destructor when necessary.
2556   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2557     if (getTarget().getCXXABI().isMicrosoft() &&
2558         GD.getDtorType() == Dtor_Complete &&
2559         DD->getParent()->getNumVBases() == 0)
2560       GD = GlobalDecl(DD, Dtor_Base);
2561   }
2562 
2563   StringRef MangledName = getMangledName(GD);
2564   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2565                                  /*IsThunk=*/false, llvm::AttributeList(),
2566                                  IsForDefinition);
2567 }
2568 
2569 static const FunctionDecl *
2570 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2571   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2572   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2573 
2574   IdentifierInfo &CII = C.Idents.get(Name);
2575   for (const auto &Result : DC->lookup(&CII))
2576     if (const auto FD = dyn_cast<FunctionDecl>(Result))
2577       return FD;
2578 
2579   if (!C.getLangOpts().CPlusPlus)
2580     return nullptr;
2581 
2582   // Demangle the premangled name from getTerminateFn()
2583   IdentifierInfo &CXXII =
2584       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
2585           ? C.Idents.get("terminate")
2586           : C.Idents.get(Name);
2587 
2588   for (const auto &N : {"__cxxabiv1", "std"}) {
2589     IdentifierInfo &NS = C.Idents.get(N);
2590     for (const auto &Result : DC->lookup(&NS)) {
2591       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2592       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2593         for (const auto &Result : LSD->lookup(&NS))
2594           if ((ND = dyn_cast<NamespaceDecl>(Result)))
2595             break;
2596 
2597       if (ND)
2598         for (const auto &Result : ND->lookup(&CXXII))
2599           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2600             return FD;
2601     }
2602   }
2603 
2604   return nullptr;
2605 }
2606 
2607 /// CreateRuntimeFunction - Create a new runtime function with the specified
2608 /// type and name.
2609 llvm::Constant *
2610 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2611                                      llvm::AttributeList ExtraAttrs,
2612                                      bool Local) {
2613   llvm::Constant *C =
2614       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2615                               /*DontDefer=*/false, /*IsThunk=*/false,
2616                               ExtraAttrs);
2617 
2618   if (auto *F = dyn_cast<llvm::Function>(C)) {
2619     if (F->empty()) {
2620       F->setCallingConv(getRuntimeCC());
2621 
2622       if (!Local && getTriple().isOSBinFormatCOFF() &&
2623           !getCodeGenOpts().LTOVisibilityPublicStd &&
2624           !getTriple().isWindowsGNUEnvironment()) {
2625         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2626         if (!FD || FD->hasAttr<DLLImportAttr>()) {
2627           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2628           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2629         }
2630       }
2631       setDSOLocal(F);
2632     }
2633   }
2634 
2635   return C;
2636 }
2637 
2638 /// CreateBuiltinFunction - Create a new builtin function with the specified
2639 /// type and name.
2640 llvm::Constant *
2641 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2642                                      llvm::AttributeList ExtraAttrs) {
2643   llvm::Constant *C =
2644       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2645                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2646   if (auto *F = dyn_cast<llvm::Function>(C))
2647     if (F->empty())
2648       F->setCallingConv(getRuntimeCC());
2649   return C;
2650 }
2651 
2652 /// isTypeConstant - Determine whether an object of this type can be emitted
2653 /// as a constant.
2654 ///
2655 /// If ExcludeCtor is true, the duration when the object's constructor runs
2656 /// will not be considered. The caller will need to verify that the object is
2657 /// not written to during its construction.
2658 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2659   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2660     return false;
2661 
2662   if (Context.getLangOpts().CPlusPlus) {
2663     if (const CXXRecordDecl *Record
2664           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2665       return ExcludeCtor && !Record->hasMutableFields() &&
2666              Record->hasTrivialDestructor();
2667   }
2668 
2669   return true;
2670 }
2671 
2672 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2673 /// create and return an llvm GlobalVariable with the specified type.  If there
2674 /// is something in the module with the specified name, return it potentially
2675 /// bitcasted to the right type.
2676 ///
2677 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2678 /// to set the attributes on the global when it is first created.
2679 ///
2680 /// If IsForDefinition is true, it is guranteed that an actual global with
2681 /// type Ty will be returned, not conversion of a variable with the same
2682 /// mangled name but some other type.
2683 llvm::Constant *
2684 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2685                                      llvm::PointerType *Ty,
2686                                      const VarDecl *D,
2687                                      ForDefinition_t IsForDefinition) {
2688   // Lookup the entry, lazily creating it if necessary.
2689   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2690   if (Entry) {
2691     if (WeakRefReferences.erase(Entry)) {
2692       if (D && !D->hasAttr<WeakAttr>())
2693         Entry->setLinkage(llvm::Function::ExternalLinkage);
2694     }
2695 
2696     // Handle dropped DLL attributes.
2697     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2698       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2699 
2700     if (Entry->getType() == Ty)
2701       return Entry;
2702 
2703     // If there are two attempts to define the same mangled name, issue an
2704     // error.
2705     if (IsForDefinition && !Entry->isDeclaration()) {
2706       GlobalDecl OtherGD;
2707       const VarDecl *OtherD;
2708 
2709       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2710       // to make sure that we issue an error only once.
2711       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2712           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2713           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2714           OtherD->hasInit() &&
2715           DiagnosedConflictingDefinitions.insert(D).second) {
2716         getDiags().Report(D->getLocation(),
2717                           diag::err_duplicate_mangled_name);
2718         getDiags().Report(OtherGD.getDecl()->getLocation(),
2719                           diag::note_previous_definition);
2720       }
2721     }
2722 
2723     // Make sure the result is of the correct type.
2724     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2725       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2726 
2727     // (If global is requested for a definition, we always need to create a new
2728     // global, not just return a bitcast.)
2729     if (!IsForDefinition)
2730       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2731   }
2732 
2733   auto AddrSpace = GetGlobalVarAddressSpace(D);
2734   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2735 
2736   auto *GV = new llvm::GlobalVariable(
2737       getModule(), Ty->getElementType(), false,
2738       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2739       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2740 
2741   // If we already created a global with the same mangled name (but different
2742   // type) before, take its name and remove it from its parent.
2743   if (Entry) {
2744     GV->takeName(Entry);
2745 
2746     if (!Entry->use_empty()) {
2747       llvm::Constant *NewPtrForOldDecl =
2748           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2749       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2750     }
2751 
2752     Entry->eraseFromParent();
2753   }
2754 
2755   // This is the first use or definition of a mangled name.  If there is a
2756   // deferred decl with this name, remember that we need to emit it at the end
2757   // of the file.
2758   auto DDI = DeferredDecls.find(MangledName);
2759   if (DDI != DeferredDecls.end()) {
2760     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2761     // list, and remove it from DeferredDecls (since we don't need it anymore).
2762     addDeferredDeclToEmit(DDI->second);
2763     DeferredDecls.erase(DDI);
2764   }
2765 
2766   // Handle things which are present even on external declarations.
2767   if (D) {
2768     // FIXME: This code is overly simple and should be merged with other global
2769     // handling.
2770     GV->setConstant(isTypeConstant(D->getType(), false));
2771 
2772     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2773 
2774     setLinkageForGV(GV, D);
2775 
2776     if (D->getTLSKind()) {
2777       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2778         CXXThreadLocals.push_back(D);
2779       setTLSMode(GV, *D);
2780     }
2781 
2782     setGVProperties(GV, D);
2783 
2784     // If required by the ABI, treat declarations of static data members with
2785     // inline initializers as definitions.
2786     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2787       EmitGlobalVarDefinition(D);
2788     }
2789 
2790     // Emit section information for extern variables.
2791     if (D->hasExternalStorage()) {
2792       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2793         GV->setSection(SA->getName());
2794     }
2795 
2796     // Handle XCore specific ABI requirements.
2797     if (getTriple().getArch() == llvm::Triple::xcore &&
2798         D->getLanguageLinkage() == CLanguageLinkage &&
2799         D->getType().isConstant(Context) &&
2800         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2801       GV->setSection(".cp.rodata");
2802 
2803     // Check if we a have a const declaration with an initializer, we may be
2804     // able to emit it as available_externally to expose it's value to the
2805     // optimizer.
2806     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2807         D->getType().isConstQualified() && !GV->hasInitializer() &&
2808         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2809       const auto *Record =
2810           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2811       bool HasMutableFields = Record && Record->hasMutableFields();
2812       if (!HasMutableFields) {
2813         const VarDecl *InitDecl;
2814         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2815         if (InitExpr) {
2816           ConstantEmitter emitter(*this);
2817           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2818           if (Init) {
2819             auto *InitType = Init->getType();
2820             if (GV->getType()->getElementType() != InitType) {
2821               // The type of the initializer does not match the definition.
2822               // This happens when an initializer has a different type from
2823               // the type of the global (because of padding at the end of a
2824               // structure for instance).
2825               GV->setName(StringRef());
2826               // Make a new global with the correct type, this is now guaranteed
2827               // to work.
2828               auto *NewGV = cast<llvm::GlobalVariable>(
2829                   GetAddrOfGlobalVar(D, InitType, IsForDefinition));
2830 
2831               // Erase the old global, since it is no longer used.
2832               GV->eraseFromParent();
2833               GV = NewGV;
2834             } else {
2835               GV->setInitializer(Init);
2836               GV->setConstant(true);
2837               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2838             }
2839             emitter.finalize(GV);
2840           }
2841         }
2842       }
2843     }
2844   }
2845 
2846   LangAS ExpectedAS =
2847       D ? D->getType().getAddressSpace()
2848         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
2849   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2850          Ty->getPointerAddressSpace());
2851   if (AddrSpace != ExpectedAS)
2852     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2853                                                        ExpectedAS, Ty);
2854 
2855   return GV;
2856 }
2857 
2858 llvm::Constant *
2859 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2860                                ForDefinition_t IsForDefinition) {
2861   const Decl *D = GD.getDecl();
2862   if (isa<CXXConstructorDecl>(D))
2863     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2864                                 getFromCtorType(GD.getCtorType()),
2865                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2866                                 /*DontDefer=*/false, IsForDefinition);
2867   else if (isa<CXXDestructorDecl>(D))
2868     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2869                                 getFromDtorType(GD.getDtorType()),
2870                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2871                                 /*DontDefer=*/false, IsForDefinition);
2872   else if (isa<CXXMethodDecl>(D)) {
2873     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2874         cast<CXXMethodDecl>(D));
2875     auto Ty = getTypes().GetFunctionType(*FInfo);
2876     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2877                              IsForDefinition);
2878   } else if (isa<FunctionDecl>(D)) {
2879     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2880     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2881     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2882                              IsForDefinition);
2883   } else
2884     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2885                               IsForDefinition);
2886 }
2887 
2888 llvm::GlobalVariable *
2889 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2890                                       llvm::Type *Ty,
2891                                       llvm::GlobalValue::LinkageTypes Linkage) {
2892   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2893   llvm::GlobalVariable *OldGV = nullptr;
2894 
2895   if (GV) {
2896     // Check if the variable has the right type.
2897     if (GV->getType()->getElementType() == Ty)
2898       return GV;
2899 
2900     // Because C++ name mangling, the only way we can end up with an already
2901     // existing global with the same name is if it has been declared extern "C".
2902     assert(GV->isDeclaration() && "Declaration has wrong type!");
2903     OldGV = GV;
2904   }
2905 
2906   // Create a new variable.
2907   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2908                                 Linkage, nullptr, Name);
2909 
2910   if (OldGV) {
2911     // Replace occurrences of the old variable if needed.
2912     GV->takeName(OldGV);
2913 
2914     if (!OldGV->use_empty()) {
2915       llvm::Constant *NewPtrForOldDecl =
2916       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2917       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2918     }
2919 
2920     OldGV->eraseFromParent();
2921   }
2922 
2923   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2924       !GV->hasAvailableExternallyLinkage())
2925     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2926 
2927   return GV;
2928 }
2929 
2930 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2931 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2932 /// then it will be created with the specified type instead of whatever the
2933 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2934 /// that an actual global with type Ty will be returned, not conversion of a
2935 /// variable with the same mangled name but some other type.
2936 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2937                                                   llvm::Type *Ty,
2938                                            ForDefinition_t IsForDefinition) {
2939   assert(D->hasGlobalStorage() && "Not a global variable");
2940   QualType ASTTy = D->getType();
2941   if (!Ty)
2942     Ty = getTypes().ConvertTypeForMem(ASTTy);
2943 
2944   llvm::PointerType *PTy =
2945     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2946 
2947   StringRef MangledName = getMangledName(D);
2948   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2949 }
2950 
2951 /// CreateRuntimeVariable - Create a new runtime global variable with the
2952 /// specified type and name.
2953 llvm::Constant *
2954 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2955                                      StringRef Name) {
2956   auto *Ret =
2957       GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2958   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
2959   return Ret;
2960 }
2961 
2962 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2963   assert(!D->getInit() && "Cannot emit definite definitions here!");
2964 
2965   StringRef MangledName = getMangledName(D);
2966   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2967 
2968   // We already have a definition, not declaration, with the same mangled name.
2969   // Emitting of declaration is not required (and actually overwrites emitted
2970   // definition).
2971   if (GV && !GV->isDeclaration())
2972     return;
2973 
2974   // If we have not seen a reference to this variable yet, place it into the
2975   // deferred declarations table to be emitted if needed later.
2976   if (!MustBeEmitted(D) && !GV) {
2977       DeferredDecls[MangledName] = D;
2978       return;
2979   }
2980 
2981   // The tentative definition is the only definition.
2982   EmitGlobalVarDefinition(D);
2983 }
2984 
2985 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2986   return Context.toCharUnitsFromBits(
2987       getDataLayout().getTypeStoreSizeInBits(Ty));
2988 }
2989 
2990 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
2991   LangAS AddrSpace = LangAS::Default;
2992   if (LangOpts.OpenCL) {
2993     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
2994     assert(AddrSpace == LangAS::opencl_global ||
2995            AddrSpace == LangAS::opencl_constant ||
2996            AddrSpace == LangAS::opencl_local ||
2997            AddrSpace >= LangAS::FirstTargetAddressSpace);
2998     return AddrSpace;
2999   }
3000 
3001   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3002     if (D && D->hasAttr<CUDAConstantAttr>())
3003       return LangAS::cuda_constant;
3004     else if (D && D->hasAttr<CUDASharedAttr>())
3005       return LangAS::cuda_shared;
3006     else
3007       return LangAS::cuda_device;
3008   }
3009 
3010   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3011 }
3012 
3013 template<typename SomeDecl>
3014 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3015                                                llvm::GlobalValue *GV) {
3016   if (!getLangOpts().CPlusPlus)
3017     return;
3018 
3019   // Must have 'used' attribute, or else inline assembly can't rely on
3020   // the name existing.
3021   if (!D->template hasAttr<UsedAttr>())
3022     return;
3023 
3024   // Must have internal linkage and an ordinary name.
3025   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3026     return;
3027 
3028   // Must be in an extern "C" context. Entities declared directly within
3029   // a record are not extern "C" even if the record is in such a context.
3030   const SomeDecl *First = D->getFirstDecl();
3031   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3032     return;
3033 
3034   // OK, this is an internal linkage entity inside an extern "C" linkage
3035   // specification. Make a note of that so we can give it the "expected"
3036   // mangled name if nothing else is using that name.
3037   std::pair<StaticExternCMap::iterator, bool> R =
3038       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3039 
3040   // If we have multiple internal linkage entities with the same name
3041   // in extern "C" regions, none of them gets that name.
3042   if (!R.second)
3043     R.first->second = nullptr;
3044 }
3045 
3046 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3047   if (!CGM.supportsCOMDAT())
3048     return false;
3049 
3050   if (D.hasAttr<SelectAnyAttr>())
3051     return true;
3052 
3053   GVALinkage Linkage;
3054   if (auto *VD = dyn_cast<VarDecl>(&D))
3055     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3056   else
3057     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3058 
3059   switch (Linkage) {
3060   case GVA_Internal:
3061   case GVA_AvailableExternally:
3062   case GVA_StrongExternal:
3063     return false;
3064   case GVA_DiscardableODR:
3065   case GVA_StrongODR:
3066     return true;
3067   }
3068   llvm_unreachable("No such linkage");
3069 }
3070 
3071 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3072                                           llvm::GlobalObject &GO) {
3073   if (!shouldBeInCOMDAT(*this, D))
3074     return;
3075   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3076 }
3077 
3078 /// Pass IsTentative as true if you want to create a tentative definition.
3079 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3080                                             bool IsTentative) {
3081   // OpenCL global variables of sampler type are translated to function calls,
3082   // therefore no need to be translated.
3083   QualType ASTTy = D->getType();
3084   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3085     return;
3086 
3087   // If this is OpenMP device, check if it is legal to emit this global
3088   // normally.
3089   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3090       OpenMPRuntime->emitTargetGlobalVariable(D))
3091     return;
3092 
3093   llvm::Constant *Init = nullptr;
3094   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3095   bool NeedsGlobalCtor = false;
3096   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3097 
3098   const VarDecl *InitDecl;
3099   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3100 
3101   Optional<ConstantEmitter> emitter;
3102 
3103   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3104   // as part of their declaration."  Sema has already checked for
3105   // error cases, so we just need to set Init to UndefValue.
3106   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3107       D->hasAttr<CUDASharedAttr>())
3108     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3109   else if (!InitExpr) {
3110     // This is a tentative definition; tentative definitions are
3111     // implicitly initialized with { 0 }.
3112     //
3113     // Note that tentative definitions are only emitted at the end of
3114     // a translation unit, so they should never have incomplete
3115     // type. In addition, EmitTentativeDefinition makes sure that we
3116     // never attempt to emit a tentative definition if a real one
3117     // exists. A use may still exists, however, so we still may need
3118     // to do a RAUW.
3119     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3120     Init = EmitNullConstant(D->getType());
3121   } else {
3122     initializedGlobalDecl = GlobalDecl(D);
3123     emitter.emplace(*this);
3124     Init = emitter->tryEmitForInitializer(*InitDecl);
3125 
3126     if (!Init) {
3127       QualType T = InitExpr->getType();
3128       if (D->getType()->isReferenceType())
3129         T = D->getType();
3130 
3131       if (getLangOpts().CPlusPlus) {
3132         Init = EmitNullConstant(T);
3133         NeedsGlobalCtor = true;
3134       } else {
3135         ErrorUnsupported(D, "static initializer");
3136         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3137       }
3138     } else {
3139       // We don't need an initializer, so remove the entry for the delayed
3140       // initializer position (just in case this entry was delayed) if we
3141       // also don't need to register a destructor.
3142       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3143         DelayedCXXInitPosition.erase(D);
3144     }
3145   }
3146 
3147   llvm::Type* InitType = Init->getType();
3148   llvm::Constant *Entry =
3149       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3150 
3151   // Strip off a bitcast if we got one back.
3152   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3153     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3154            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3155            // All zero index gep.
3156            CE->getOpcode() == llvm::Instruction::GetElementPtr);
3157     Entry = CE->getOperand(0);
3158   }
3159 
3160   // Entry is now either a Function or GlobalVariable.
3161   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3162 
3163   // We have a definition after a declaration with the wrong type.
3164   // We must make a new GlobalVariable* and update everything that used OldGV
3165   // (a declaration or tentative definition) with the new GlobalVariable*
3166   // (which will be a definition).
3167   //
3168   // This happens if there is a prototype for a global (e.g.
3169   // "extern int x[];") and then a definition of a different type (e.g.
3170   // "int x[10];"). This also happens when an initializer has a different type
3171   // from the type of the global (this happens with unions).
3172   if (!GV || GV->getType()->getElementType() != InitType ||
3173       GV->getType()->getAddressSpace() !=
3174           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3175 
3176     // Move the old entry aside so that we'll create a new one.
3177     Entry->setName(StringRef());
3178 
3179     // Make a new global with the correct type, this is now guaranteed to work.
3180     GV = cast<llvm::GlobalVariable>(
3181         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3182 
3183     // Replace all uses of the old global with the new global
3184     llvm::Constant *NewPtrForOldDecl =
3185         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3186     Entry->replaceAllUsesWith(NewPtrForOldDecl);
3187 
3188     // Erase the old global, since it is no longer used.
3189     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3190   }
3191 
3192   MaybeHandleStaticInExternC(D, GV);
3193 
3194   if (D->hasAttr<AnnotateAttr>())
3195     AddGlobalAnnotations(D, GV);
3196 
3197   // Set the llvm linkage type as appropriate.
3198   llvm::GlobalValue::LinkageTypes Linkage =
3199       getLLVMLinkageVarDefinition(D, GV->isConstant());
3200 
3201   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3202   // the device. [...]"
3203   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3204   // __device__, declares a variable that: [...]
3205   // Is accessible from all the threads within the grid and from the host
3206   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3207   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3208   if (GV && LangOpts.CUDA) {
3209     if (LangOpts.CUDAIsDevice) {
3210       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3211         GV->setExternallyInitialized(true);
3212     } else {
3213       // Host-side shadows of external declarations of device-side
3214       // global variables become internal definitions. These have to
3215       // be internal in order to prevent name conflicts with global
3216       // host variables with the same name in a different TUs.
3217       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3218         Linkage = llvm::GlobalValue::InternalLinkage;
3219 
3220         // Shadow variables and their properties must be registered
3221         // with CUDA runtime.
3222         unsigned Flags = 0;
3223         if (!D->hasDefinition())
3224           Flags |= CGCUDARuntime::ExternDeviceVar;
3225         if (D->hasAttr<CUDAConstantAttr>())
3226           Flags |= CGCUDARuntime::ConstantDeviceVar;
3227         getCUDARuntime().registerDeviceVar(*GV, Flags);
3228       } else if (D->hasAttr<CUDASharedAttr>())
3229         // __shared__ variables are odd. Shadows do get created, but
3230         // they are not registered with the CUDA runtime, so they
3231         // can't really be used to access their device-side
3232         // counterparts. It's not clear yet whether it's nvcc's bug or
3233         // a feature, but we've got to do the same for compatibility.
3234         Linkage = llvm::GlobalValue::InternalLinkage;
3235     }
3236   }
3237 
3238   GV->setInitializer(Init);
3239   if (emitter) emitter->finalize(GV);
3240 
3241   // If it is safe to mark the global 'constant', do so now.
3242   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3243                   isTypeConstant(D->getType(), true));
3244 
3245   // If it is in a read-only section, mark it 'constant'.
3246   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3247     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3248     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3249       GV->setConstant(true);
3250   }
3251 
3252   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3253 
3254 
3255   // On Darwin, if the normal linkage of a C++ thread_local variable is
3256   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3257   // copies within a linkage unit; otherwise, the backing variable has
3258   // internal linkage and all accesses should just be calls to the
3259   // Itanium-specified entry point, which has the normal linkage of the
3260   // variable. This is to preserve the ability to change the implementation
3261   // behind the scenes.
3262   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3263       Context.getTargetInfo().getTriple().isOSDarwin() &&
3264       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3265       !llvm::GlobalVariable::isWeakLinkage(Linkage))
3266     Linkage = llvm::GlobalValue::InternalLinkage;
3267 
3268   GV->setLinkage(Linkage);
3269   if (D->hasAttr<DLLImportAttr>())
3270     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3271   else if (D->hasAttr<DLLExportAttr>())
3272     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3273   else
3274     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3275 
3276   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3277     // common vars aren't constant even if declared const.
3278     GV->setConstant(false);
3279     // Tentative definition of global variables may be initialized with
3280     // non-zero null pointers. In this case they should have weak linkage
3281     // since common linkage must have zero initializer and must not have
3282     // explicit section therefore cannot have non-zero initial value.
3283     if (!GV->getInitializer()->isNullValue())
3284       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3285   }
3286 
3287   setNonAliasAttributes(D, GV);
3288 
3289   if (D->getTLSKind() && !GV->isThreadLocal()) {
3290     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3291       CXXThreadLocals.push_back(D);
3292     setTLSMode(GV, *D);
3293   }
3294 
3295   maybeSetTrivialComdat(*D, *GV);
3296 
3297   // Emit the initializer function if necessary.
3298   if (NeedsGlobalCtor || NeedsGlobalDtor)
3299     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3300 
3301   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3302 
3303   // Emit global variable debug information.
3304   if (CGDebugInfo *DI = getModuleDebugInfo())
3305     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3306       DI->EmitGlobalVariable(GV, D);
3307 }
3308 
3309 static bool isVarDeclStrongDefinition(const ASTContext &Context,
3310                                       CodeGenModule &CGM, const VarDecl *D,
3311                                       bool NoCommon) {
3312   // Don't give variables common linkage if -fno-common was specified unless it
3313   // was overridden by a NoCommon attribute.
3314   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3315     return true;
3316 
3317   // C11 6.9.2/2:
3318   //   A declaration of an identifier for an object that has file scope without
3319   //   an initializer, and without a storage-class specifier or with the
3320   //   storage-class specifier static, constitutes a tentative definition.
3321   if (D->getInit() || D->hasExternalStorage())
3322     return true;
3323 
3324   // A variable cannot be both common and exist in a section.
3325   if (D->hasAttr<SectionAttr>())
3326     return true;
3327 
3328   // A variable cannot be both common and exist in a section.
3329   // We dont try to determine which is the right section in the front-end.
3330   // If no specialized section name is applicable, it will resort to default.
3331   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3332       D->hasAttr<PragmaClangDataSectionAttr>() ||
3333       D->hasAttr<PragmaClangRodataSectionAttr>())
3334     return true;
3335 
3336   // Thread local vars aren't considered common linkage.
3337   if (D->getTLSKind())
3338     return true;
3339 
3340   // Tentative definitions marked with WeakImportAttr are true definitions.
3341   if (D->hasAttr<WeakImportAttr>())
3342     return true;
3343 
3344   // A variable cannot be both common and exist in a comdat.
3345   if (shouldBeInCOMDAT(CGM, *D))
3346     return true;
3347 
3348   // Declarations with a required alignment do not have common linkage in MSVC
3349   // mode.
3350   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3351     if (D->hasAttr<AlignedAttr>())
3352       return true;
3353     QualType VarType = D->getType();
3354     if (Context.isAlignmentRequired(VarType))
3355       return true;
3356 
3357     if (const auto *RT = VarType->getAs<RecordType>()) {
3358       const RecordDecl *RD = RT->getDecl();
3359       for (const FieldDecl *FD : RD->fields()) {
3360         if (FD->isBitField())
3361           continue;
3362         if (FD->hasAttr<AlignedAttr>())
3363           return true;
3364         if (Context.isAlignmentRequired(FD->getType()))
3365           return true;
3366       }
3367     }
3368   }
3369 
3370   return false;
3371 }
3372 
3373 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
3374     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
3375   if (Linkage == GVA_Internal)
3376     return llvm::Function::InternalLinkage;
3377 
3378   if (D->hasAttr<WeakAttr>()) {
3379     if (IsConstantVariable)
3380       return llvm::GlobalVariable::WeakODRLinkage;
3381     else
3382       return llvm::GlobalVariable::WeakAnyLinkage;
3383   }
3384 
3385   // We are guaranteed to have a strong definition somewhere else,
3386   // so we can use available_externally linkage.
3387   if (Linkage == GVA_AvailableExternally)
3388     return llvm::GlobalValue::AvailableExternallyLinkage;
3389 
3390   // Note that Apple's kernel linker doesn't support symbol
3391   // coalescing, so we need to avoid linkonce and weak linkages there.
3392   // Normally, this means we just map to internal, but for explicit
3393   // instantiations we'll map to external.
3394 
3395   // In C++, the compiler has to emit a definition in every translation unit
3396   // that references the function.  We should use linkonce_odr because
3397   // a) if all references in this translation unit are optimized away, we
3398   // don't need to codegen it.  b) if the function persists, it needs to be
3399   // merged with other definitions. c) C++ has the ODR, so we know the
3400   // definition is dependable.
3401   if (Linkage == GVA_DiscardableODR)
3402     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3403                                             : llvm::Function::InternalLinkage;
3404 
3405   // An explicit instantiation of a template has weak linkage, since
3406   // explicit instantiations can occur in multiple translation units
3407   // and must all be equivalent. However, we are not allowed to
3408   // throw away these explicit instantiations.
3409   //
3410   // We don't currently support CUDA device code spread out across multiple TUs,
3411   // so say that CUDA templates are either external (for kernels) or internal.
3412   // This lets llvm perform aggressive inter-procedural optimizations.
3413   if (Linkage == GVA_StrongODR) {
3414     if (Context.getLangOpts().AppleKext)
3415       return llvm::Function::ExternalLinkage;
3416     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3417       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3418                                           : llvm::Function::InternalLinkage;
3419     return llvm::Function::WeakODRLinkage;
3420   }
3421 
3422   // C++ doesn't have tentative definitions and thus cannot have common
3423   // linkage.
3424   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3425       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3426                                  CodeGenOpts.NoCommon))
3427     return llvm::GlobalVariable::CommonLinkage;
3428 
3429   // selectany symbols are externally visible, so use weak instead of
3430   // linkonce.  MSVC optimizes away references to const selectany globals, so
3431   // all definitions should be the same and ODR linkage should be used.
3432   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3433   if (D->hasAttr<SelectAnyAttr>())
3434     return llvm::GlobalVariable::WeakODRLinkage;
3435 
3436   // Otherwise, we have strong external linkage.
3437   assert(Linkage == GVA_StrongExternal);
3438   return llvm::GlobalVariable::ExternalLinkage;
3439 }
3440 
3441 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3442     const VarDecl *VD, bool IsConstant) {
3443   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
3444   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3445 }
3446 
3447 /// Replace the uses of a function that was declared with a non-proto type.
3448 /// We want to silently drop extra arguments from call sites
3449 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3450                                           llvm::Function *newFn) {
3451   // Fast path.
3452   if (old->use_empty()) return;
3453 
3454   llvm::Type *newRetTy = newFn->getReturnType();
3455   SmallVector<llvm::Value*, 4> newArgs;
3456   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3457 
3458   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3459          ui != ue; ) {
3460     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3461     llvm::User *user = use->getUser();
3462 
3463     // Recognize and replace uses of bitcasts.  Most calls to
3464     // unprototyped functions will use bitcasts.
3465     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3466       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3467         replaceUsesOfNonProtoConstant(bitcast, newFn);
3468       continue;
3469     }
3470 
3471     // Recognize calls to the function.
3472     llvm::CallSite callSite(user);
3473     if (!callSite) continue;
3474     if (!callSite.isCallee(&*use)) continue;
3475 
3476     // If the return types don't match exactly, then we can't
3477     // transform this call unless it's dead.
3478     if (callSite->getType() != newRetTy && !callSite->use_empty())
3479       continue;
3480 
3481     // Get the call site's attribute list.
3482     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3483     llvm::AttributeList oldAttrs = callSite.getAttributes();
3484 
3485     // If the function was passed too few arguments, don't transform.
3486     unsigned newNumArgs = newFn->arg_size();
3487     if (callSite.arg_size() < newNumArgs) continue;
3488 
3489     // If extra arguments were passed, we silently drop them.
3490     // If any of the types mismatch, we don't transform.
3491     unsigned argNo = 0;
3492     bool dontTransform = false;
3493     for (llvm::Argument &A : newFn->args()) {
3494       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3495         dontTransform = true;
3496         break;
3497       }
3498 
3499       // Add any parameter attributes.
3500       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3501       argNo++;
3502     }
3503     if (dontTransform)
3504       continue;
3505 
3506     // Okay, we can transform this.  Create the new call instruction and copy
3507     // over the required information.
3508     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3509 
3510     // Copy over any operand bundles.
3511     callSite.getOperandBundlesAsDefs(newBundles);
3512 
3513     llvm::CallSite newCall;
3514     if (callSite.isCall()) {
3515       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3516                                        callSite.getInstruction());
3517     } else {
3518       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3519       newCall = llvm::InvokeInst::Create(newFn,
3520                                          oldInvoke->getNormalDest(),
3521                                          oldInvoke->getUnwindDest(),
3522                                          newArgs, newBundles, "",
3523                                          callSite.getInstruction());
3524     }
3525     newArgs.clear(); // for the next iteration
3526 
3527     if (!newCall->getType()->isVoidTy())
3528       newCall->takeName(callSite.getInstruction());
3529     newCall.setAttributes(llvm::AttributeList::get(
3530         newFn->getContext(), oldAttrs.getFnAttributes(),
3531         oldAttrs.getRetAttributes(), newArgAttrs));
3532     newCall.setCallingConv(callSite.getCallingConv());
3533 
3534     // Finally, remove the old call, replacing any uses with the new one.
3535     if (!callSite->use_empty())
3536       callSite->replaceAllUsesWith(newCall.getInstruction());
3537 
3538     // Copy debug location attached to CI.
3539     if (callSite->getDebugLoc())
3540       newCall->setDebugLoc(callSite->getDebugLoc());
3541 
3542     callSite->eraseFromParent();
3543   }
3544 }
3545 
3546 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3547 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3548 /// existing call uses of the old function in the module, this adjusts them to
3549 /// call the new function directly.
3550 ///
3551 /// This is not just a cleanup: the always_inline pass requires direct calls to
3552 /// functions to be able to inline them.  If there is a bitcast in the way, it
3553 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3554 /// run at -O0.
3555 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3556                                                       llvm::Function *NewFn) {
3557   // If we're redefining a global as a function, don't transform it.
3558   if (!isa<llvm::Function>(Old)) return;
3559 
3560   replaceUsesOfNonProtoConstant(Old, NewFn);
3561 }
3562 
3563 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3564   auto DK = VD->isThisDeclarationADefinition();
3565   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3566     return;
3567 
3568   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3569   // If we have a definition, this might be a deferred decl. If the
3570   // instantiation is explicit, make sure we emit it at the end.
3571   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3572     GetAddrOfGlobalVar(VD);
3573 
3574   EmitTopLevelDecl(VD);
3575 }
3576 
3577 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3578                                                  llvm::GlobalValue *GV) {
3579   const auto *D = cast<FunctionDecl>(GD.getDecl());
3580 
3581   // Compute the function info and LLVM type.
3582   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3583   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3584 
3585   // Get or create the prototype for the function.
3586   if (!GV || (GV->getType()->getElementType() != Ty))
3587     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3588                                                    /*DontDefer=*/true,
3589                                                    ForDefinition));
3590 
3591   // Already emitted.
3592   if (!GV->isDeclaration())
3593     return;
3594 
3595   // We need to set linkage and visibility on the function before
3596   // generating code for it because various parts of IR generation
3597   // want to propagate this information down (e.g. to local static
3598   // declarations).
3599   auto *Fn = cast<llvm::Function>(GV);
3600   setFunctionLinkage(GD, Fn);
3601 
3602   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3603   setGVProperties(Fn, GD);
3604 
3605   MaybeHandleStaticInExternC(D, Fn);
3606 
3607   maybeSetTrivialComdat(*D, *Fn);
3608 
3609   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3610 
3611   setNonAliasAttributes(GD, Fn);
3612   SetLLVMFunctionAttributesForDefinition(D, Fn);
3613 
3614   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3615     AddGlobalCtor(Fn, CA->getPriority());
3616   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3617     AddGlobalDtor(Fn, DA->getPriority());
3618   if (D->hasAttr<AnnotateAttr>())
3619     AddGlobalAnnotations(D, Fn);
3620 }
3621 
3622 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3623   const auto *D = cast<ValueDecl>(GD.getDecl());
3624   const AliasAttr *AA = D->getAttr<AliasAttr>();
3625   assert(AA && "Not an alias?");
3626 
3627   StringRef MangledName = getMangledName(GD);
3628 
3629   if (AA->getAliasee() == MangledName) {
3630     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3631     return;
3632   }
3633 
3634   // If there is a definition in the module, then it wins over the alias.
3635   // This is dubious, but allow it to be safe.  Just ignore the alias.
3636   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3637   if (Entry && !Entry->isDeclaration())
3638     return;
3639 
3640   Aliases.push_back(GD);
3641 
3642   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3643 
3644   // Create a reference to the named value.  This ensures that it is emitted
3645   // if a deferred decl.
3646   llvm::Constant *Aliasee;
3647   if (isa<llvm::FunctionType>(DeclTy))
3648     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3649                                       /*ForVTable=*/false);
3650   else
3651     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3652                                     llvm::PointerType::getUnqual(DeclTy),
3653                                     /*D=*/nullptr);
3654 
3655   // Create the new alias itself, but don't set a name yet.
3656   auto *GA = llvm::GlobalAlias::create(
3657       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3658 
3659   if (Entry) {
3660     if (GA->getAliasee() == Entry) {
3661       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3662       return;
3663     }
3664 
3665     assert(Entry->isDeclaration());
3666 
3667     // If there is a declaration in the module, then we had an extern followed
3668     // by the alias, as in:
3669     //   extern int test6();
3670     //   ...
3671     //   int test6() __attribute__((alias("test7")));
3672     //
3673     // Remove it and replace uses of it with the alias.
3674     GA->takeName(Entry);
3675 
3676     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3677                                                           Entry->getType()));
3678     Entry->eraseFromParent();
3679   } else {
3680     GA->setName(MangledName);
3681   }
3682 
3683   // Set attributes which are particular to an alias; this is a
3684   // specialization of the attributes which may be set on a global
3685   // variable/function.
3686   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3687       D->isWeakImported()) {
3688     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3689   }
3690 
3691   if (const auto *VD = dyn_cast<VarDecl>(D))
3692     if (VD->getTLSKind())
3693       setTLSMode(GA, *VD);
3694 
3695   SetCommonAttributes(GD, GA);
3696 }
3697 
3698 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3699   const auto *D = cast<ValueDecl>(GD.getDecl());
3700   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3701   assert(IFA && "Not an ifunc?");
3702 
3703   StringRef MangledName = getMangledName(GD);
3704 
3705   if (IFA->getResolver() == MangledName) {
3706     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3707     return;
3708   }
3709 
3710   // Report an error if some definition overrides ifunc.
3711   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3712   if (Entry && !Entry->isDeclaration()) {
3713     GlobalDecl OtherGD;
3714     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3715         DiagnosedConflictingDefinitions.insert(GD).second) {
3716       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3717       Diags.Report(OtherGD.getDecl()->getLocation(),
3718                    diag::note_previous_definition);
3719     }
3720     return;
3721   }
3722 
3723   Aliases.push_back(GD);
3724 
3725   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3726   llvm::Constant *Resolver =
3727       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3728                               /*ForVTable=*/false);
3729   llvm::GlobalIFunc *GIF =
3730       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3731                                 "", Resolver, &getModule());
3732   if (Entry) {
3733     if (GIF->getResolver() == Entry) {
3734       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3735       return;
3736     }
3737     assert(Entry->isDeclaration());
3738 
3739     // If there is a declaration in the module, then we had an extern followed
3740     // by the ifunc, as in:
3741     //   extern int test();
3742     //   ...
3743     //   int test() __attribute__((ifunc("resolver")));
3744     //
3745     // Remove it and replace uses of it with the ifunc.
3746     GIF->takeName(Entry);
3747 
3748     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3749                                                           Entry->getType()));
3750     Entry->eraseFromParent();
3751   } else
3752     GIF->setName(MangledName);
3753 
3754   SetCommonAttributes(GD, GIF);
3755 }
3756 
3757 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3758                                             ArrayRef<llvm::Type*> Tys) {
3759   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3760                                          Tys);
3761 }
3762 
3763 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3764 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3765                          const StringLiteral *Literal, bool TargetIsLSB,
3766                          bool &IsUTF16, unsigned &StringLength) {
3767   StringRef String = Literal->getString();
3768   unsigned NumBytes = String.size();
3769 
3770   // Check for simple case.
3771   if (!Literal->containsNonAsciiOrNull()) {
3772     StringLength = NumBytes;
3773     return *Map.insert(std::make_pair(String, nullptr)).first;
3774   }
3775 
3776   // Otherwise, convert the UTF8 literals into a string of shorts.
3777   IsUTF16 = true;
3778 
3779   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3780   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3781   llvm::UTF16 *ToPtr = &ToBuf[0];
3782 
3783   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3784                                  ToPtr + NumBytes, llvm::strictConversion);
3785 
3786   // ConvertUTF8toUTF16 returns the length in ToPtr.
3787   StringLength = ToPtr - &ToBuf[0];
3788 
3789   // Add an explicit null.
3790   *ToPtr = 0;
3791   return *Map.insert(std::make_pair(
3792                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3793                                    (StringLength + 1) * 2),
3794                          nullptr)).first;
3795 }
3796 
3797 ConstantAddress
3798 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3799   unsigned StringLength = 0;
3800   bool isUTF16 = false;
3801   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3802       GetConstantCFStringEntry(CFConstantStringMap, Literal,
3803                                getDataLayout().isLittleEndian(), isUTF16,
3804                                StringLength);
3805 
3806   if (auto *C = Entry.second)
3807     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3808 
3809   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3810   llvm::Constant *Zeros[] = { Zero, Zero };
3811 
3812   // If we don't already have it, get __CFConstantStringClassReference.
3813   if (!CFConstantStringClassRef) {
3814     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3815     Ty = llvm::ArrayType::get(Ty, 0);
3816     llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
3817         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
3818 
3819     if (getTriple().isOSBinFormatCOFF()) {
3820       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3821       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3822       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3823 
3824       const VarDecl *VD = nullptr;
3825       for (const auto &Result : DC->lookup(&II))
3826         if ((VD = dyn_cast<VarDecl>(Result)))
3827           break;
3828 
3829       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3830         GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3831         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3832       } else {
3833         GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3834         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3835       }
3836     }
3837     setDSOLocal(GV);
3838 
3839     // Decay array -> ptr
3840     CFConstantStringClassRef =
3841         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3842   }
3843 
3844   QualType CFTy = getContext().getCFConstantStringType();
3845 
3846   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3847 
3848   ConstantInitBuilder Builder(*this);
3849   auto Fields = Builder.beginStruct(STy);
3850 
3851   // Class pointer.
3852   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3853 
3854   // Flags.
3855   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3856 
3857   // String pointer.
3858   llvm::Constant *C = nullptr;
3859   if (isUTF16) {
3860     auto Arr = llvm::makeArrayRef(
3861         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3862         Entry.first().size() / 2);
3863     C = llvm::ConstantDataArray::get(VMContext, Arr);
3864   } else {
3865     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3866   }
3867 
3868   // Note: -fwritable-strings doesn't make the backing store strings of
3869   // CFStrings writable. (See <rdar://problem/10657500>)
3870   auto *GV =
3871       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3872                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3873   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3874   // Don't enforce the target's minimum global alignment, since the only use
3875   // of the string is via this class initializer.
3876   CharUnits Align = isUTF16
3877                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3878                         : getContext().getTypeAlignInChars(getContext().CharTy);
3879   GV->setAlignment(Align.getQuantity());
3880 
3881   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3882   // Without it LLVM can merge the string with a non unnamed_addr one during
3883   // LTO.  Doing that changes the section it ends in, which surprises ld64.
3884   if (getTriple().isOSBinFormatMachO())
3885     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3886                            : "__TEXT,__cstring,cstring_literals");
3887 
3888   // String.
3889   llvm::Constant *Str =
3890       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3891 
3892   if (isUTF16)
3893     // Cast the UTF16 string to the correct type.
3894     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3895   Fields.add(Str);
3896 
3897   // String length.
3898   auto Ty = getTypes().ConvertType(getContext().LongTy);
3899   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3900 
3901   CharUnits Alignment = getPointerAlign();
3902 
3903   // The struct.
3904   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3905                                     /*isConstant=*/false,
3906                                     llvm::GlobalVariable::PrivateLinkage);
3907   switch (getTriple().getObjectFormat()) {
3908   case llvm::Triple::UnknownObjectFormat:
3909     llvm_unreachable("unknown file format");
3910   case llvm::Triple::COFF:
3911   case llvm::Triple::ELF:
3912   case llvm::Triple::Wasm:
3913     GV->setSection("cfstring");
3914     break;
3915   case llvm::Triple::MachO:
3916     GV->setSection("__DATA,__cfstring");
3917     break;
3918   }
3919   Entry.second = GV;
3920 
3921   return ConstantAddress(GV, Alignment);
3922 }
3923 
3924 bool CodeGenModule::getExpressionLocationsEnabled() const {
3925   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
3926 }
3927 
3928 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3929   if (ObjCFastEnumerationStateType.isNull()) {
3930     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3931     D->startDefinition();
3932 
3933     QualType FieldTypes[] = {
3934       Context.UnsignedLongTy,
3935       Context.getPointerType(Context.getObjCIdType()),
3936       Context.getPointerType(Context.UnsignedLongTy),
3937       Context.getConstantArrayType(Context.UnsignedLongTy,
3938                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3939     };
3940 
3941     for (size_t i = 0; i < 4; ++i) {
3942       FieldDecl *Field = FieldDecl::Create(Context,
3943                                            D,
3944                                            SourceLocation(),
3945                                            SourceLocation(), nullptr,
3946                                            FieldTypes[i], /*TInfo=*/nullptr,
3947                                            /*BitWidth=*/nullptr,
3948                                            /*Mutable=*/false,
3949                                            ICIS_NoInit);
3950       Field->setAccess(AS_public);
3951       D->addDecl(Field);
3952     }
3953 
3954     D->completeDefinition();
3955     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3956   }
3957 
3958   return ObjCFastEnumerationStateType;
3959 }
3960 
3961 llvm::Constant *
3962 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3963   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3964 
3965   // Don't emit it as the address of the string, emit the string data itself
3966   // as an inline array.
3967   if (E->getCharByteWidth() == 1) {
3968     SmallString<64> Str(E->getString());
3969 
3970     // Resize the string to the right size, which is indicated by its type.
3971     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3972     Str.resize(CAT->getSize().getZExtValue());
3973     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3974   }
3975 
3976   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3977   llvm::Type *ElemTy = AType->getElementType();
3978   unsigned NumElements = AType->getNumElements();
3979 
3980   // Wide strings have either 2-byte or 4-byte elements.
3981   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3982     SmallVector<uint16_t, 32> Elements;
3983     Elements.reserve(NumElements);
3984 
3985     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3986       Elements.push_back(E->getCodeUnit(i));
3987     Elements.resize(NumElements);
3988     return llvm::ConstantDataArray::get(VMContext, Elements);
3989   }
3990 
3991   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3992   SmallVector<uint32_t, 32> Elements;
3993   Elements.reserve(NumElements);
3994 
3995   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3996     Elements.push_back(E->getCodeUnit(i));
3997   Elements.resize(NumElements);
3998   return llvm::ConstantDataArray::get(VMContext, Elements);
3999 }
4000 
4001 static llvm::GlobalVariable *
4002 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4003                       CodeGenModule &CGM, StringRef GlobalName,
4004                       CharUnits Alignment) {
4005   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4006   unsigned AddrSpace = 0;
4007   if (CGM.getLangOpts().OpenCL)
4008     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
4009 
4010   llvm::Module &M = CGM.getModule();
4011   // Create a global variable for this string
4012   auto *GV = new llvm::GlobalVariable(
4013       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4014       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4015   GV->setAlignment(Alignment.getQuantity());
4016   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4017   if (GV->isWeakForLinker()) {
4018     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4019     GV->setComdat(M.getOrInsertComdat(GV->getName()));
4020   }
4021   CGM.setDSOLocal(GV);
4022 
4023   return GV;
4024 }
4025 
4026 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4027 /// constant array for the given string literal.
4028 ConstantAddress
4029 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4030                                                   StringRef Name) {
4031   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4032 
4033   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4034   llvm::GlobalVariable **Entry = nullptr;
4035   if (!LangOpts.WritableStrings) {
4036     Entry = &ConstantStringMap[C];
4037     if (auto GV = *Entry) {
4038       if (Alignment.getQuantity() > GV->getAlignment())
4039         GV->setAlignment(Alignment.getQuantity());
4040       return ConstantAddress(GV, Alignment);
4041     }
4042   }
4043 
4044   SmallString<256> MangledNameBuffer;
4045   StringRef GlobalVariableName;
4046   llvm::GlobalValue::LinkageTypes LT;
4047 
4048   // Mangle the string literal if the ABI allows for it.  However, we cannot
4049   // do this if  we are compiling with ASan or -fwritable-strings because they
4050   // rely on strings having normal linkage.
4051   if (!LangOpts.WritableStrings &&
4052       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4053       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
4054     llvm::raw_svector_ostream Out(MangledNameBuffer);
4055     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4056 
4057     LT = llvm::GlobalValue::LinkOnceODRLinkage;
4058     GlobalVariableName = MangledNameBuffer;
4059   } else {
4060     LT = llvm::GlobalValue::PrivateLinkage;
4061     GlobalVariableName = Name;
4062   }
4063 
4064   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4065   if (Entry)
4066     *Entry = GV;
4067 
4068   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4069                                   QualType());
4070   return ConstantAddress(GV, Alignment);
4071 }
4072 
4073 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4074 /// array for the given ObjCEncodeExpr node.
4075 ConstantAddress
4076 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4077   std::string Str;
4078   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4079 
4080   return GetAddrOfConstantCString(Str);
4081 }
4082 
4083 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4084 /// the literal and a terminating '\0' character.
4085 /// The result has pointer to array type.
4086 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4087     const std::string &Str, const char *GlobalName) {
4088   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4089   CharUnits Alignment =
4090     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4091 
4092   llvm::Constant *C =
4093       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4094 
4095   // Don't share any string literals if strings aren't constant.
4096   llvm::GlobalVariable **Entry = nullptr;
4097   if (!LangOpts.WritableStrings) {
4098     Entry = &ConstantStringMap[C];
4099     if (auto GV = *Entry) {
4100       if (Alignment.getQuantity() > GV->getAlignment())
4101         GV->setAlignment(Alignment.getQuantity());
4102       return ConstantAddress(GV, Alignment);
4103     }
4104   }
4105 
4106   // Get the default prefix if a name wasn't specified.
4107   if (!GlobalName)
4108     GlobalName = ".str";
4109   // Create a global variable for this.
4110   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4111                                   GlobalName, Alignment);
4112   if (Entry)
4113     *Entry = GV;
4114   return ConstantAddress(GV, Alignment);
4115 }
4116 
4117 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4118     const MaterializeTemporaryExpr *E, const Expr *Init) {
4119   assert((E->getStorageDuration() == SD_Static ||
4120           E->getStorageDuration() == SD_Thread) && "not a global temporary");
4121   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4122 
4123   // If we're not materializing a subobject of the temporary, keep the
4124   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4125   QualType MaterializedType = Init->getType();
4126   if (Init == E->GetTemporaryExpr())
4127     MaterializedType = E->getType();
4128 
4129   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4130 
4131   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4132     return ConstantAddress(Slot, Align);
4133 
4134   // FIXME: If an externally-visible declaration extends multiple temporaries,
4135   // we need to give each temporary the same name in every translation unit (and
4136   // we also need to make the temporaries externally-visible).
4137   SmallString<256> Name;
4138   llvm::raw_svector_ostream Out(Name);
4139   getCXXABI().getMangleContext().mangleReferenceTemporary(
4140       VD, E->getManglingNumber(), Out);
4141 
4142   APValue *Value = nullptr;
4143   if (E->getStorageDuration() == SD_Static) {
4144     // We might have a cached constant initializer for this temporary. Note
4145     // that this might have a different value from the value computed by
4146     // evaluating the initializer if the surrounding constant expression
4147     // modifies the temporary.
4148     Value = getContext().getMaterializedTemporaryValue(E, false);
4149     if (Value && Value->isUninit())
4150       Value = nullptr;
4151   }
4152 
4153   // Try evaluating it now, it might have a constant initializer.
4154   Expr::EvalResult EvalResult;
4155   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4156       !EvalResult.hasSideEffects())
4157     Value = &EvalResult.Val;
4158 
4159   LangAS AddrSpace =
4160       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4161 
4162   Optional<ConstantEmitter> emitter;
4163   llvm::Constant *InitialValue = nullptr;
4164   bool Constant = false;
4165   llvm::Type *Type;
4166   if (Value) {
4167     // The temporary has a constant initializer, use it.
4168     emitter.emplace(*this);
4169     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4170                                                MaterializedType);
4171     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4172     Type = InitialValue->getType();
4173   } else {
4174     // No initializer, the initialization will be provided when we
4175     // initialize the declaration which performed lifetime extension.
4176     Type = getTypes().ConvertTypeForMem(MaterializedType);
4177   }
4178 
4179   // Create a global variable for this lifetime-extended temporary.
4180   llvm::GlobalValue::LinkageTypes Linkage =
4181       getLLVMLinkageVarDefinition(VD, Constant);
4182   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4183     const VarDecl *InitVD;
4184     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4185         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4186       // Temporaries defined inside a class get linkonce_odr linkage because the
4187       // class can be defined in multipe translation units.
4188       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4189     } else {
4190       // There is no need for this temporary to have external linkage if the
4191       // VarDecl has external linkage.
4192       Linkage = llvm::GlobalVariable::InternalLinkage;
4193     }
4194   }
4195   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4196   auto *GV = new llvm::GlobalVariable(
4197       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4198       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4199   if (emitter) emitter->finalize(GV);
4200   setGVProperties(GV, VD);
4201   GV->setAlignment(Align.getQuantity());
4202   if (supportsCOMDAT() && GV->isWeakForLinker())
4203     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4204   if (VD->getTLSKind())
4205     setTLSMode(GV, *VD);
4206   llvm::Constant *CV = GV;
4207   if (AddrSpace != LangAS::Default)
4208     CV = getTargetCodeGenInfo().performAddrSpaceCast(
4209         *this, GV, AddrSpace, LangAS::Default,
4210         Type->getPointerTo(
4211             getContext().getTargetAddressSpace(LangAS::Default)));
4212   MaterializedGlobalTemporaryMap[E] = CV;
4213   return ConstantAddress(CV, Align);
4214 }
4215 
4216 /// EmitObjCPropertyImplementations - Emit information for synthesized
4217 /// properties for an implementation.
4218 void CodeGenModule::EmitObjCPropertyImplementations(const
4219                                                     ObjCImplementationDecl *D) {
4220   for (const auto *PID : D->property_impls()) {
4221     // Dynamic is just for type-checking.
4222     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4223       ObjCPropertyDecl *PD = PID->getPropertyDecl();
4224 
4225       // Determine which methods need to be implemented, some may have
4226       // been overridden. Note that ::isPropertyAccessor is not the method
4227       // we want, that just indicates if the decl came from a
4228       // property. What we want to know is if the method is defined in
4229       // this implementation.
4230       if (!D->getInstanceMethod(PD->getGetterName()))
4231         CodeGenFunction(*this).GenerateObjCGetter(
4232                                  const_cast<ObjCImplementationDecl *>(D), PID);
4233       if (!PD->isReadOnly() &&
4234           !D->getInstanceMethod(PD->getSetterName()))
4235         CodeGenFunction(*this).GenerateObjCSetter(
4236                                  const_cast<ObjCImplementationDecl *>(D), PID);
4237     }
4238   }
4239 }
4240 
4241 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
4242   const ObjCInterfaceDecl *iface = impl->getClassInterface();
4243   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4244        ivar; ivar = ivar->getNextIvar())
4245     if (ivar->getType().isDestructedType())
4246       return true;
4247 
4248   return false;
4249 }
4250 
4251 static bool AllTrivialInitializers(CodeGenModule &CGM,
4252                                    ObjCImplementationDecl *D) {
4253   CodeGenFunction CGF(CGM);
4254   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4255        E = D->init_end(); B != E; ++B) {
4256     CXXCtorInitializer *CtorInitExp = *B;
4257     Expr *Init = CtorInitExp->getInit();
4258     if (!CGF.isTrivialInitializer(Init))
4259       return false;
4260   }
4261   return true;
4262 }
4263 
4264 /// EmitObjCIvarInitializations - Emit information for ivar initialization
4265 /// for an implementation.
4266 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4267   // We might need a .cxx_destruct even if we don't have any ivar initializers.
4268   if (needsDestructMethod(D)) {
4269     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4270     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4271     ObjCMethodDecl *DTORMethod =
4272       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
4273                              cxxSelector, getContext().VoidTy, nullptr, D,
4274                              /*isInstance=*/true, /*isVariadic=*/false,
4275                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4276                              /*isDefined=*/false, ObjCMethodDecl::Required);
4277     D->addInstanceMethod(DTORMethod);
4278     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4279     D->setHasDestructors(true);
4280   }
4281 
4282   // If the implementation doesn't have any ivar initializers, we don't need
4283   // a .cxx_construct.
4284   if (D->getNumIvarInitializers() == 0 ||
4285       AllTrivialInitializers(*this, D))
4286     return;
4287 
4288   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4289   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4290   // The constructor returns 'self'.
4291   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
4292                                                 D->getLocation(),
4293                                                 D->getLocation(),
4294                                                 cxxSelector,
4295                                                 getContext().getObjCIdType(),
4296                                                 nullptr, D, /*isInstance=*/true,
4297                                                 /*isVariadic=*/false,
4298                                                 /*isPropertyAccessor=*/true,
4299                                                 /*isImplicitlyDeclared=*/true,
4300                                                 /*isDefined=*/false,
4301                                                 ObjCMethodDecl::Required);
4302   D->addInstanceMethod(CTORMethod);
4303   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
4304   D->setHasNonZeroConstructors(true);
4305 }
4306 
4307 // EmitLinkageSpec - Emit all declarations in a linkage spec.
4308 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4309   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4310       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
4311     ErrorUnsupported(LSD, "linkage spec");
4312     return;
4313   }
4314 
4315   EmitDeclContext(LSD);
4316 }
4317 
4318 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4319   for (auto *I : DC->decls()) {
4320     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4321     // are themselves considered "top-level", so EmitTopLevelDecl on an
4322     // ObjCImplDecl does not recursively visit them. We need to do that in
4323     // case they're nested inside another construct (LinkageSpecDecl /
4324     // ExportDecl) that does stop them from being considered "top-level".
4325     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4326       for (auto *M : OID->methods())
4327         EmitTopLevelDecl(M);
4328     }
4329 
4330     EmitTopLevelDecl(I);
4331   }
4332 }
4333 
4334 /// EmitTopLevelDecl - Emit code for a single top level declaration.
4335 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4336   // Ignore dependent declarations.
4337   if (D->isTemplated())
4338     return;
4339 
4340   switch (D->getKind()) {
4341   case Decl::CXXConversion:
4342   case Decl::CXXMethod:
4343   case Decl::Function:
4344     EmitGlobal(cast<FunctionDecl>(D));
4345     // Always provide some coverage mapping
4346     // even for the functions that aren't emitted.
4347     AddDeferredUnusedCoverageMapping(D);
4348     break;
4349 
4350   case Decl::CXXDeductionGuide:
4351     // Function-like, but does not result in code emission.
4352     break;
4353 
4354   case Decl::Var:
4355   case Decl::Decomposition:
4356   case Decl::VarTemplateSpecialization:
4357     EmitGlobal(cast<VarDecl>(D));
4358     if (auto *DD = dyn_cast<DecompositionDecl>(D))
4359       for (auto *B : DD->bindings())
4360         if (auto *HD = B->getHoldingVar())
4361           EmitGlobal(HD);
4362     break;
4363 
4364   // Indirect fields from global anonymous structs and unions can be
4365   // ignored; only the actual variable requires IR gen support.
4366   case Decl::IndirectField:
4367     break;
4368 
4369   // C++ Decls
4370   case Decl::Namespace:
4371     EmitDeclContext(cast<NamespaceDecl>(D));
4372     break;
4373   case Decl::ClassTemplateSpecialization: {
4374     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4375     if (DebugInfo &&
4376         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4377         Spec->hasDefinition())
4378       DebugInfo->completeTemplateDefinition(*Spec);
4379   } LLVM_FALLTHROUGH;
4380   case Decl::CXXRecord:
4381     if (DebugInfo) {
4382       if (auto *ES = D->getASTContext().getExternalSource())
4383         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4384           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4385     }
4386     // Emit any static data members, they may be definitions.
4387     for (auto *I : cast<CXXRecordDecl>(D)->decls())
4388       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4389         EmitTopLevelDecl(I);
4390     break;
4391     // No code generation needed.
4392   case Decl::UsingShadow:
4393   case Decl::ClassTemplate:
4394   case Decl::VarTemplate:
4395   case Decl::VarTemplatePartialSpecialization:
4396   case Decl::FunctionTemplate:
4397   case Decl::TypeAliasTemplate:
4398   case Decl::Block:
4399   case Decl::Empty:
4400     break;
4401   case Decl::Using:          // using X; [C++]
4402     if (CGDebugInfo *DI = getModuleDebugInfo())
4403         DI->EmitUsingDecl(cast<UsingDecl>(*D));
4404     return;
4405   case Decl::NamespaceAlias:
4406     if (CGDebugInfo *DI = getModuleDebugInfo())
4407         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4408     return;
4409   case Decl::UsingDirective: // using namespace X; [C++]
4410     if (CGDebugInfo *DI = getModuleDebugInfo())
4411       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4412     return;
4413   case Decl::CXXConstructor:
4414     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4415     break;
4416   case Decl::CXXDestructor:
4417     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4418     break;
4419 
4420   case Decl::StaticAssert:
4421     // Nothing to do.
4422     break;
4423 
4424   // Objective-C Decls
4425 
4426   // Forward declarations, no (immediate) code generation.
4427   case Decl::ObjCInterface:
4428   case Decl::ObjCCategory:
4429     break;
4430 
4431   case Decl::ObjCProtocol: {
4432     auto *Proto = cast<ObjCProtocolDecl>(D);
4433     if (Proto->isThisDeclarationADefinition())
4434       ObjCRuntime->GenerateProtocol(Proto);
4435     break;
4436   }
4437 
4438   case Decl::ObjCCategoryImpl:
4439     // Categories have properties but don't support synthesize so we
4440     // can ignore them here.
4441     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4442     break;
4443 
4444   case Decl::ObjCImplementation: {
4445     auto *OMD = cast<ObjCImplementationDecl>(D);
4446     EmitObjCPropertyImplementations(OMD);
4447     EmitObjCIvarInitializations(OMD);
4448     ObjCRuntime->GenerateClass(OMD);
4449     // Emit global variable debug information.
4450     if (CGDebugInfo *DI = getModuleDebugInfo())
4451       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4452         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4453             OMD->getClassInterface()), OMD->getLocation());
4454     break;
4455   }
4456   case Decl::ObjCMethod: {
4457     auto *OMD = cast<ObjCMethodDecl>(D);
4458     // If this is not a prototype, emit the body.
4459     if (OMD->getBody())
4460       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4461     break;
4462   }
4463   case Decl::ObjCCompatibleAlias:
4464     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4465     break;
4466 
4467   case Decl::PragmaComment: {
4468     const auto *PCD = cast<PragmaCommentDecl>(D);
4469     switch (PCD->getCommentKind()) {
4470     case PCK_Unknown:
4471       llvm_unreachable("unexpected pragma comment kind");
4472     case PCK_Linker:
4473       AppendLinkerOptions(PCD->getArg());
4474       break;
4475     case PCK_Lib:
4476       if (getTarget().getTriple().isOSBinFormatELF() &&
4477           !getTarget().getTriple().isPS4())
4478         AddELFLibDirective(PCD->getArg());
4479       else
4480         AddDependentLib(PCD->getArg());
4481       break;
4482     case PCK_Compiler:
4483     case PCK_ExeStr:
4484     case PCK_User:
4485       break; // We ignore all of these.
4486     }
4487     break;
4488   }
4489 
4490   case Decl::PragmaDetectMismatch: {
4491     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4492     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4493     break;
4494   }
4495 
4496   case Decl::LinkageSpec:
4497     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4498     break;
4499 
4500   case Decl::FileScopeAsm: {
4501     // File-scope asm is ignored during device-side CUDA compilation.
4502     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4503       break;
4504     // File-scope asm is ignored during device-side OpenMP compilation.
4505     if (LangOpts.OpenMPIsDevice)
4506       break;
4507     auto *AD = cast<FileScopeAsmDecl>(D);
4508     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4509     break;
4510   }
4511 
4512   case Decl::Import: {
4513     auto *Import = cast<ImportDecl>(D);
4514 
4515     // If we've already imported this module, we're done.
4516     if (!ImportedModules.insert(Import->getImportedModule()))
4517       break;
4518 
4519     // Emit debug information for direct imports.
4520     if (!Import->getImportedOwningModule()) {
4521       if (CGDebugInfo *DI = getModuleDebugInfo())
4522         DI->EmitImportDecl(*Import);
4523     }
4524 
4525     // Find all of the submodules and emit the module initializers.
4526     llvm::SmallPtrSet<clang::Module *, 16> Visited;
4527     SmallVector<clang::Module *, 16> Stack;
4528     Visited.insert(Import->getImportedModule());
4529     Stack.push_back(Import->getImportedModule());
4530 
4531     while (!Stack.empty()) {
4532       clang::Module *Mod = Stack.pop_back_val();
4533       if (!EmittedModuleInitializers.insert(Mod).second)
4534         continue;
4535 
4536       for (auto *D : Context.getModuleInitializers(Mod))
4537         EmitTopLevelDecl(D);
4538 
4539       // Visit the submodules of this module.
4540       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4541                                              SubEnd = Mod->submodule_end();
4542            Sub != SubEnd; ++Sub) {
4543         // Skip explicit children; they need to be explicitly imported to emit
4544         // the initializers.
4545         if ((*Sub)->IsExplicit)
4546           continue;
4547 
4548         if (Visited.insert(*Sub).second)
4549           Stack.push_back(*Sub);
4550       }
4551     }
4552     break;
4553   }
4554 
4555   case Decl::Export:
4556     EmitDeclContext(cast<ExportDecl>(D));
4557     break;
4558 
4559   case Decl::OMPThreadPrivate:
4560     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4561     break;
4562 
4563   case Decl::OMPDeclareReduction:
4564     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4565     break;
4566 
4567   default:
4568     // Make sure we handled everything we should, every other kind is a
4569     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4570     // function. Need to recode Decl::Kind to do that easily.
4571     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4572     break;
4573   }
4574 }
4575 
4576 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4577   // Do we need to generate coverage mapping?
4578   if (!CodeGenOpts.CoverageMapping)
4579     return;
4580   switch (D->getKind()) {
4581   case Decl::CXXConversion:
4582   case Decl::CXXMethod:
4583   case Decl::Function:
4584   case Decl::ObjCMethod:
4585   case Decl::CXXConstructor:
4586   case Decl::CXXDestructor: {
4587     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4588       return;
4589     SourceManager &SM = getContext().getSourceManager();
4590     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4591       return;
4592     auto I = DeferredEmptyCoverageMappingDecls.find(D);
4593     if (I == DeferredEmptyCoverageMappingDecls.end())
4594       DeferredEmptyCoverageMappingDecls[D] = true;
4595     break;
4596   }
4597   default:
4598     break;
4599   };
4600 }
4601 
4602 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4603   // Do we need to generate coverage mapping?
4604   if (!CodeGenOpts.CoverageMapping)
4605     return;
4606   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4607     if (Fn->isTemplateInstantiation())
4608       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4609   }
4610   auto I = DeferredEmptyCoverageMappingDecls.find(D);
4611   if (I == DeferredEmptyCoverageMappingDecls.end())
4612     DeferredEmptyCoverageMappingDecls[D] = false;
4613   else
4614     I->second = false;
4615 }
4616 
4617 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4618   // We call takeVector() here to avoid use-after-free.
4619   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4620   // we deserialize function bodies to emit coverage info for them, and that
4621   // deserializes more declarations. How should we handle that case?
4622   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4623     if (!Entry.second)
4624       continue;
4625     const Decl *D = Entry.first;
4626     switch (D->getKind()) {
4627     case Decl::CXXConversion:
4628     case Decl::CXXMethod:
4629     case Decl::Function:
4630     case Decl::ObjCMethod: {
4631       CodeGenPGO PGO(*this);
4632       GlobalDecl GD(cast<FunctionDecl>(D));
4633       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4634                                   getFunctionLinkage(GD));
4635       break;
4636     }
4637     case Decl::CXXConstructor: {
4638       CodeGenPGO PGO(*this);
4639       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4640       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4641                                   getFunctionLinkage(GD));
4642       break;
4643     }
4644     case Decl::CXXDestructor: {
4645       CodeGenPGO PGO(*this);
4646       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4647       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4648                                   getFunctionLinkage(GD));
4649       break;
4650     }
4651     default:
4652       break;
4653     };
4654   }
4655 }
4656 
4657 /// Turns the given pointer into a constant.
4658 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4659                                           const void *Ptr) {
4660   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4661   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4662   return llvm::ConstantInt::get(i64, PtrInt);
4663 }
4664 
4665 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4666                                    llvm::NamedMDNode *&GlobalMetadata,
4667                                    GlobalDecl D,
4668                                    llvm::GlobalValue *Addr) {
4669   if (!GlobalMetadata)
4670     GlobalMetadata =
4671       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4672 
4673   // TODO: should we report variant information for ctors/dtors?
4674   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4675                            llvm::ConstantAsMetadata::get(GetPointerConstant(
4676                                CGM.getLLVMContext(), D.getDecl()))};
4677   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4678 }
4679 
4680 /// For each function which is declared within an extern "C" region and marked
4681 /// as 'used', but has internal linkage, create an alias from the unmangled
4682 /// name to the mangled name if possible. People expect to be able to refer
4683 /// to such functions with an unmangled name from inline assembly within the
4684 /// same translation unit.
4685 void CodeGenModule::EmitStaticExternCAliases() {
4686   // Don't do anything if we're generating CUDA device code -- the NVPTX
4687   // assembly target doesn't support aliases.
4688   if (Context.getTargetInfo().getTriple().isNVPTX())
4689     return;
4690   for (auto &I : StaticExternCValues) {
4691     IdentifierInfo *Name = I.first;
4692     llvm::GlobalValue *Val = I.second;
4693     if (Val && !getModule().getNamedValue(Name->getName()))
4694       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4695   }
4696 }
4697 
4698 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4699                                              GlobalDecl &Result) const {
4700   auto Res = Manglings.find(MangledName);
4701   if (Res == Manglings.end())
4702     return false;
4703   Result = Res->getValue();
4704   return true;
4705 }
4706 
4707 /// Emits metadata nodes associating all the global values in the
4708 /// current module with the Decls they came from.  This is useful for
4709 /// projects using IR gen as a subroutine.
4710 ///
4711 /// Since there's currently no way to associate an MDNode directly
4712 /// with an llvm::GlobalValue, we create a global named metadata
4713 /// with the name 'clang.global.decl.ptrs'.
4714 void CodeGenModule::EmitDeclMetadata() {
4715   llvm::NamedMDNode *GlobalMetadata = nullptr;
4716 
4717   for (auto &I : MangledDeclNames) {
4718     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4719     // Some mangled names don't necessarily have an associated GlobalValue
4720     // in this module, e.g. if we mangled it for DebugInfo.
4721     if (Addr)
4722       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4723   }
4724 }
4725 
4726 /// Emits metadata nodes for all the local variables in the current
4727 /// function.
4728 void CodeGenFunction::EmitDeclMetadata() {
4729   if (LocalDeclMap.empty()) return;
4730 
4731   llvm::LLVMContext &Context = getLLVMContext();
4732 
4733   // Find the unique metadata ID for this name.
4734   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4735 
4736   llvm::NamedMDNode *GlobalMetadata = nullptr;
4737 
4738   for (auto &I : LocalDeclMap) {
4739     const Decl *D = I.first;
4740     llvm::Value *Addr = I.second.getPointer();
4741     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4742       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4743       Alloca->setMetadata(
4744           DeclPtrKind, llvm::MDNode::get(
4745                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4746     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4747       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4748       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4749     }
4750   }
4751 }
4752 
4753 void CodeGenModule::EmitVersionIdentMetadata() {
4754   llvm::NamedMDNode *IdentMetadata =
4755     TheModule.getOrInsertNamedMetadata("llvm.ident");
4756   std::string Version = getClangFullVersion();
4757   llvm::LLVMContext &Ctx = TheModule.getContext();
4758 
4759   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4760   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4761 }
4762 
4763 void CodeGenModule::EmitTargetMetadata() {
4764   // Warning, new MangledDeclNames may be appended within this loop.
4765   // We rely on MapVector insertions adding new elements to the end
4766   // of the container.
4767   // FIXME: Move this loop into the one target that needs it, and only
4768   // loop over those declarations for which we couldn't emit the target
4769   // metadata when we emitted the declaration.
4770   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4771     auto Val = *(MangledDeclNames.begin() + I);
4772     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4773     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4774     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4775   }
4776 }
4777 
4778 void CodeGenModule::EmitCoverageFile() {
4779   if (getCodeGenOpts().CoverageDataFile.empty() &&
4780       getCodeGenOpts().CoverageNotesFile.empty())
4781     return;
4782 
4783   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4784   if (!CUNode)
4785     return;
4786 
4787   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4788   llvm::LLVMContext &Ctx = TheModule.getContext();
4789   auto *CoverageDataFile =
4790       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4791   auto *CoverageNotesFile =
4792       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4793   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4794     llvm::MDNode *CU = CUNode->getOperand(i);
4795     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4796     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4797   }
4798 }
4799 
4800 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4801   // Sema has checked that all uuid strings are of the form
4802   // "12345678-1234-1234-1234-1234567890ab".
4803   assert(Uuid.size() == 36);
4804   for (unsigned i = 0; i < 36; ++i) {
4805     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4806     else                                         assert(isHexDigit(Uuid[i]));
4807   }
4808 
4809   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4810   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4811 
4812   llvm::Constant *Field3[8];
4813   for (unsigned Idx = 0; Idx < 8; ++Idx)
4814     Field3[Idx] = llvm::ConstantInt::get(
4815         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4816 
4817   llvm::Constant *Fields[4] = {
4818     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4819     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4820     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4821     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4822   };
4823 
4824   return llvm::ConstantStruct::getAnon(Fields);
4825 }
4826 
4827 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4828                                                        bool ForEH) {
4829   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4830   // FIXME: should we even be calling this method if RTTI is disabled
4831   // and it's not for EH?
4832   if (!ForEH && !getLangOpts().RTTI)
4833     return llvm::Constant::getNullValue(Int8PtrTy);
4834 
4835   if (ForEH && Ty->isObjCObjectPointerType() &&
4836       LangOpts.ObjCRuntime.isGNUFamily())
4837     return ObjCRuntime->GetEHType(Ty);
4838 
4839   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4840 }
4841 
4842 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4843   // Do not emit threadprivates in simd-only mode.
4844   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
4845     return;
4846   for (auto RefExpr : D->varlists()) {
4847     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4848     bool PerformInit =
4849         VD->getAnyInitializer() &&
4850         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4851                                                         /*ForRef=*/false);
4852 
4853     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4854     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4855             VD, Addr, RefExpr->getLocStart(), PerformInit))
4856       CXXGlobalInits.push_back(InitFunction);
4857   }
4858 }
4859 
4860 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4861   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4862   if (InternalId)
4863     return InternalId;
4864 
4865   if (isExternallyVisible(T->getLinkage())) {
4866     std::string OutName;
4867     llvm::raw_string_ostream Out(OutName);
4868     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4869 
4870     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4871   } else {
4872     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4873                                            llvm::ArrayRef<llvm::Metadata *>());
4874   }
4875 
4876   return InternalId;
4877 }
4878 
4879 // Generalize pointer types to a void pointer with the qualifiers of the
4880 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
4881 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
4882 // 'void *'.
4883 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
4884   if (!Ty->isPointerType())
4885     return Ty;
4886 
4887   return Ctx.getPointerType(
4888       QualType(Ctx.VoidTy).withCVRQualifiers(
4889           Ty->getPointeeType().getCVRQualifiers()));
4890 }
4891 
4892 // Apply type generalization to a FunctionType's return and argument types
4893 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
4894   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
4895     SmallVector<QualType, 8> GeneralizedParams;
4896     for (auto &Param : FnType->param_types())
4897       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
4898 
4899     return Ctx.getFunctionType(
4900         GeneralizeType(Ctx, FnType->getReturnType()),
4901         GeneralizedParams, FnType->getExtProtoInfo());
4902   }
4903 
4904   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
4905     return Ctx.getFunctionNoProtoType(
4906         GeneralizeType(Ctx, FnType->getReturnType()));
4907 
4908   llvm_unreachable("Encountered unknown FunctionType");
4909 }
4910 
4911 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
4912   T = GeneralizeFunctionType(getContext(), T);
4913 
4914   llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
4915   if (InternalId)
4916     return InternalId;
4917 
4918   if (isExternallyVisible(T->getLinkage())) {
4919     std::string OutName;
4920     llvm::raw_string_ostream Out(OutName);
4921     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4922     Out << ".generalized";
4923 
4924     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4925   } else {
4926     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4927                                            llvm::ArrayRef<llvm::Metadata *>());
4928   }
4929 
4930   return InternalId;
4931 }
4932 
4933 /// Returns whether this module needs the "all-vtables" type identifier.
4934 bool CodeGenModule::NeedAllVtablesTypeId() const {
4935   // Returns true if at least one of vtable-based CFI checkers is enabled and
4936   // is not in the trapping mode.
4937   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4938            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4939           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4940            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4941           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4942            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4943           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4944            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4945 }
4946 
4947 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4948                                           CharUnits Offset,
4949                                           const CXXRecordDecl *RD) {
4950   llvm::Metadata *MD =
4951       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4952   VTable->addTypeMetadata(Offset.getQuantity(), MD);
4953 
4954   if (CodeGenOpts.SanitizeCfiCrossDso)
4955     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4956       VTable->addTypeMetadata(Offset.getQuantity(),
4957                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4958 
4959   if (NeedAllVtablesTypeId()) {
4960     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4961     VTable->addTypeMetadata(Offset.getQuantity(), MD);
4962   }
4963 }
4964 
4965 // Fills in the supplied string map with the set of target features for the
4966 // passed in function.
4967 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4968                                           const FunctionDecl *FD) {
4969   StringRef TargetCPU = Target.getTargetOpts().CPU;
4970   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4971     // If we have a TargetAttr build up the feature map based on that.
4972     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4973 
4974     ParsedAttr.Features.erase(
4975         llvm::remove_if(ParsedAttr.Features,
4976                         [&](const std::string &Feat) {
4977                           return !Target.isValidFeatureName(
4978                               StringRef{Feat}.substr(1));
4979                         }),
4980         ParsedAttr.Features.end());
4981 
4982     // Make a copy of the features as passed on the command line into the
4983     // beginning of the additional features from the function to override.
4984     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
4985                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4986                             Target.getTargetOpts().FeaturesAsWritten.end());
4987 
4988     if (ParsedAttr.Architecture != "" &&
4989         Target.isValidCPUName(ParsedAttr.Architecture))
4990       TargetCPU = ParsedAttr.Architecture;
4991 
4992     // Now populate the feature map, first with the TargetCPU which is either
4993     // the default or a new one from the target attribute string. Then we'll use
4994     // the passed in features (FeaturesAsWritten) along with the new ones from
4995     // the attribute.
4996     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4997                           ParsedAttr.Features);
4998   } else {
4999     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5000                           Target.getTargetOpts().Features);
5001   }
5002 }
5003 
5004 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5005   if (!SanStats)
5006     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5007 
5008   return *SanStats;
5009 }
5010 llvm::Value *
5011 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5012                                                   CodeGenFunction &CGF) {
5013   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5014   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5015   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5016   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5017                                 "__translate_sampler_initializer"),
5018                                 {C});
5019 }
5020