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