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