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