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