xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision e6cf6c78f88ffb7eed69b0eaa60785eab9df2b88)
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(
2699         "CodeGen Function", [&]() { return FD->getQualifiedNameAsString(); });
2700 
2701     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2702       // Make sure to emit the definition(s) before we emit the thunks.
2703       // This is necessary for the generation of certain thunks.
2704       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2705         ABI->emitCXXStructor(GD);
2706       else if (FD->isMultiVersion())
2707         EmitMultiVersionFunctionDefinition(GD, GV);
2708       else
2709         EmitGlobalFunctionDefinition(GD, GV);
2710 
2711       if (Method->isVirtual())
2712         getVTables().EmitThunks(GD);
2713 
2714       return;
2715     }
2716 
2717     if (FD->isMultiVersion())
2718       return EmitMultiVersionFunctionDefinition(GD, GV);
2719     return EmitGlobalFunctionDefinition(GD, GV);
2720   }
2721 
2722   if (const auto *VD = dyn_cast<VarDecl>(D))
2723     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2724 
2725   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2726 }
2727 
2728 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2729                                                       llvm::Function *NewFn);
2730 
2731 static unsigned
2732 TargetMVPriority(const TargetInfo &TI,
2733                  const CodeGenFunction::MultiVersionResolverOption &RO) {
2734   unsigned Priority = 0;
2735   for (StringRef Feat : RO.Conditions.Features)
2736     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2737 
2738   if (!RO.Conditions.Architecture.empty())
2739     Priority = std::max(
2740         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2741   return Priority;
2742 }
2743 
2744 void CodeGenModule::emitMultiVersionFunctions() {
2745   for (GlobalDecl GD : MultiVersionFuncs) {
2746     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2747     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2748     getContext().forEachMultiversionedFunctionVersion(
2749         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2750           GlobalDecl CurGD{
2751               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2752           StringRef MangledName = getMangledName(CurGD);
2753           llvm::Constant *Func = GetGlobalValue(MangledName);
2754           if (!Func) {
2755             if (CurFD->isDefined()) {
2756               EmitGlobalFunctionDefinition(CurGD, nullptr);
2757               Func = GetGlobalValue(MangledName);
2758             } else {
2759               const CGFunctionInfo &FI =
2760                   getTypes().arrangeGlobalDeclaration(GD);
2761               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2762               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2763                                        /*DontDefer=*/false, ForDefinition);
2764             }
2765             assert(Func && "This should have just been created");
2766           }
2767 
2768           const auto *TA = CurFD->getAttr<TargetAttr>();
2769           llvm::SmallVector<StringRef, 8> Feats;
2770           TA->getAddedFeatures(Feats);
2771 
2772           Options.emplace_back(cast<llvm::Function>(Func),
2773                                TA->getArchitecture(), Feats);
2774         });
2775 
2776     llvm::Function *ResolverFunc;
2777     const TargetInfo &TI = getTarget();
2778 
2779     if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2780       ResolverFunc = cast<llvm::Function>(
2781           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2782     else
2783       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2784 
2785     if (supportsCOMDAT())
2786       ResolverFunc->setComdat(
2787           getModule().getOrInsertComdat(ResolverFunc->getName()));
2788 
2789     llvm::stable_sort(
2790         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2791                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
2792           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2793         });
2794     CodeGenFunction CGF(*this);
2795     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2796   }
2797 }
2798 
2799 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2800   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2801   assert(FD && "Not a FunctionDecl?");
2802   const auto *DD = FD->getAttr<CPUDispatchAttr>();
2803   assert(DD && "Not a cpu_dispatch Function?");
2804   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
2805 
2806   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2807     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2808     DeclTy = getTypes().GetFunctionType(FInfo);
2809   }
2810 
2811   StringRef ResolverName = getMangledName(GD);
2812 
2813   llvm::Type *ResolverType;
2814   GlobalDecl ResolverGD;
2815   if (getTarget().supportsIFunc())
2816     ResolverType = llvm::FunctionType::get(
2817         llvm::PointerType::get(DeclTy,
2818                                Context.getTargetAddressSpace(FD->getType())),
2819         false);
2820   else {
2821     ResolverType = DeclTy;
2822     ResolverGD = GD;
2823   }
2824 
2825   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2826       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
2827 
2828   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2829   const TargetInfo &Target = getTarget();
2830   unsigned Index = 0;
2831   for (const IdentifierInfo *II : DD->cpus()) {
2832     // Get the name of the target function so we can look it up/create it.
2833     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2834                               getCPUSpecificMangling(*this, II->getName());
2835 
2836     llvm::Constant *Func = GetGlobalValue(MangledName);
2837 
2838     if (!Func) {
2839       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2840       if (ExistingDecl.getDecl() &&
2841           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
2842         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
2843         Func = GetGlobalValue(MangledName);
2844       } else {
2845         if (!ExistingDecl.getDecl())
2846           ExistingDecl = GD.getWithMultiVersionIndex(Index);
2847 
2848       Func = GetOrCreateLLVMFunction(
2849           MangledName, DeclTy, ExistingDecl,
2850           /*ForVTable=*/false, /*DontDefer=*/true,
2851           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2852       }
2853     }
2854 
2855     llvm::SmallVector<StringRef, 32> Features;
2856     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2857     llvm::transform(Features, Features.begin(),
2858                     [](StringRef Str) { return Str.substr(1); });
2859     Features.erase(std::remove_if(
2860         Features.begin(), Features.end(), [&Target](StringRef Feat) {
2861           return !Target.validateCpuSupports(Feat);
2862         }), Features.end());
2863     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
2864     ++Index;
2865   }
2866 
2867   llvm::sort(
2868       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2869                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
2870         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2871                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2872       });
2873 
2874   // If the list contains multiple 'default' versions, such as when it contains
2875   // 'pentium' and 'generic', don't emit the call to the generic one (since we
2876   // always run on at least a 'pentium'). We do this by deleting the 'least
2877   // advanced' (read, lowest mangling letter).
2878   while (Options.size() > 1 &&
2879          CodeGenFunction::GetX86CpuSupportsMask(
2880              (Options.end() - 2)->Conditions.Features) == 0) {
2881     StringRef LHSName = (Options.end() - 2)->Function->getName();
2882     StringRef RHSName = (Options.end() - 1)->Function->getName();
2883     if (LHSName.compare(RHSName) < 0)
2884       Options.erase(Options.end() - 2);
2885     else
2886       Options.erase(Options.end() - 1);
2887   }
2888 
2889   CodeGenFunction CGF(*this);
2890   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2891 }
2892 
2893 /// If a dispatcher for the specified mangled name is not in the module, create
2894 /// and return an llvm Function with the specified type.
2895 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2896     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
2897   std::string MangledName =
2898       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2899 
2900   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2901   // a separate resolver).
2902   std::string ResolverName = MangledName;
2903   if (getTarget().supportsIFunc())
2904     ResolverName += ".ifunc";
2905   else if (FD->isTargetMultiVersion())
2906     ResolverName += ".resolver";
2907 
2908   // If this already exists, just return that one.
2909   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2910     return ResolverGV;
2911 
2912   // Since this is the first time we've created this IFunc, make sure
2913   // that we put this multiversioned function into the list to be
2914   // replaced later if necessary (target multiversioning only).
2915   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2916     MultiVersionFuncs.push_back(GD);
2917 
2918   if (getTarget().supportsIFunc()) {
2919     llvm::Type *ResolverType = llvm::FunctionType::get(
2920         llvm::PointerType::get(
2921             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
2922         false);
2923     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2924         MangledName + ".resolver", ResolverType, GlobalDecl{},
2925         /*ForVTable=*/false);
2926     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2927         DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2928     GIF->setName(ResolverName);
2929     SetCommonAttributes(FD, GIF);
2930 
2931     return GIF;
2932   }
2933 
2934   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2935       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2936   assert(isa<llvm::GlobalValue>(Resolver) &&
2937          "Resolver should be created for the first time");
2938   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2939   return Resolver;
2940 }
2941 
2942 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2943 /// module, create and return an llvm Function with the specified type. If there
2944 /// is something in the module with the specified name, return it potentially
2945 /// bitcasted to the right type.
2946 ///
2947 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2948 /// to set the attributes on the function when it is first created.
2949 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2950     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2951     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2952     ForDefinition_t IsForDefinition) {
2953   const Decl *D = GD.getDecl();
2954 
2955   // Any attempts to use a MultiVersion function should result in retrieving
2956   // the iFunc instead. Name Mangling will handle the rest of the changes.
2957   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2958     // For the device mark the function as one that should be emitted.
2959     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2960         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
2961         !DontDefer && !IsForDefinition) {
2962       if (const FunctionDecl *FDDef = FD->getDefinition()) {
2963         GlobalDecl GDDef;
2964         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2965           GDDef = GlobalDecl(CD, GD.getCtorType());
2966         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2967           GDDef = GlobalDecl(DD, GD.getDtorType());
2968         else
2969           GDDef = GlobalDecl(FDDef);
2970         EmitGlobal(GDDef);
2971       }
2972     }
2973 
2974     if (FD->isMultiVersion()) {
2975       const auto *TA = FD->getAttr<TargetAttr>();
2976       if (TA && TA->isDefaultVersion())
2977         UpdateMultiVersionNames(GD, FD);
2978       if (!IsForDefinition)
2979         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
2980     }
2981   }
2982 
2983   // Lookup the entry, lazily creating it if necessary.
2984   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2985   if (Entry) {
2986     if (WeakRefReferences.erase(Entry)) {
2987       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2988       if (FD && !FD->hasAttr<WeakAttr>())
2989         Entry->setLinkage(llvm::Function::ExternalLinkage);
2990     }
2991 
2992     // Handle dropped DLL attributes.
2993     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
2994       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2995       setDSOLocal(Entry);
2996     }
2997 
2998     // If there are two attempts to define the same mangled name, issue an
2999     // error.
3000     if (IsForDefinition && !Entry->isDeclaration()) {
3001       GlobalDecl OtherGD;
3002       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3003       // to make sure that we issue an error only once.
3004       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3005           (GD.getCanonicalDecl().getDecl() !=
3006            OtherGD.getCanonicalDecl().getDecl()) &&
3007           DiagnosedConflictingDefinitions.insert(GD).second) {
3008         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3009             << MangledName;
3010         getDiags().Report(OtherGD.getDecl()->getLocation(),
3011                           diag::note_previous_definition);
3012       }
3013     }
3014 
3015     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3016         (Entry->getType()->getElementType() == Ty)) {
3017       return Entry;
3018     }
3019 
3020     // Make sure the result is of the correct type.
3021     // (If function is requested for a definition, we always need to create a new
3022     // function, not just return a bitcast.)
3023     if (!IsForDefinition)
3024       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3025   }
3026 
3027   // This function doesn't have a complete type (for example, the return
3028   // type is an incomplete struct). Use a fake type instead, and make
3029   // sure not to try to set attributes.
3030   bool IsIncompleteFunction = false;
3031 
3032   llvm::FunctionType *FTy;
3033   if (isa<llvm::FunctionType>(Ty)) {
3034     FTy = cast<llvm::FunctionType>(Ty);
3035   } else {
3036     FTy = llvm::FunctionType::get(VoidTy, false);
3037     IsIncompleteFunction = true;
3038   }
3039 
3040   llvm::Function *F =
3041       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3042                              Entry ? StringRef() : MangledName, &getModule());
3043 
3044   // If we already created a function with the same mangled name (but different
3045   // type) before, take its name and add it to the list of functions to be
3046   // replaced with F at the end of CodeGen.
3047   //
3048   // This happens if there is a prototype for a function (e.g. "int f()") and
3049   // then a definition of a different type (e.g. "int f(int x)").
3050   if (Entry) {
3051     F->takeName(Entry);
3052 
3053     // This might be an implementation of a function without a prototype, in
3054     // which case, try to do special replacement of calls which match the new
3055     // prototype.  The really key thing here is that we also potentially drop
3056     // arguments from the call site so as to make a direct call, which makes the
3057     // inliner happier and suppresses a number of optimizer warnings (!) about
3058     // dropping arguments.
3059     if (!Entry->use_empty()) {
3060       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3061       Entry->removeDeadConstantUsers();
3062     }
3063 
3064     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3065         F, Entry->getType()->getElementType()->getPointerTo());
3066     addGlobalValReplacement(Entry, BC);
3067   }
3068 
3069   assert(F->getName() == MangledName && "name was uniqued!");
3070   if (D)
3071     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3072   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3073     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3074     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3075   }
3076 
3077   if (!DontDefer) {
3078     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3079     // each other bottoming out with the base dtor.  Therefore we emit non-base
3080     // dtors on usage, even if there is no dtor definition in the TU.
3081     if (D && isa<CXXDestructorDecl>(D) &&
3082         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3083                                            GD.getDtorType()))
3084       addDeferredDeclToEmit(GD);
3085 
3086     // This is the first use or definition of a mangled name.  If there is a
3087     // deferred decl with this name, remember that we need to emit it at the end
3088     // of the file.
3089     auto DDI = DeferredDecls.find(MangledName);
3090     if (DDI != DeferredDecls.end()) {
3091       // Move the potentially referenced deferred decl to the
3092       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3093       // don't need it anymore).
3094       addDeferredDeclToEmit(DDI->second);
3095       DeferredDecls.erase(DDI);
3096 
3097       // Otherwise, there are cases we have to worry about where we're
3098       // using a declaration for which we must emit a definition but where
3099       // we might not find a top-level definition:
3100       //   - member functions defined inline in their classes
3101       //   - friend functions defined inline in some class
3102       //   - special member functions with implicit definitions
3103       // If we ever change our AST traversal to walk into class methods,
3104       // this will be unnecessary.
3105       //
3106       // We also don't emit a definition for a function if it's going to be an
3107       // entry in a vtable, unless it's already marked as used.
3108     } else if (getLangOpts().CPlusPlus && D) {
3109       // Look for a declaration that's lexically in a record.
3110       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3111            FD = FD->getPreviousDecl()) {
3112         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3113           if (FD->doesThisDeclarationHaveABody()) {
3114             addDeferredDeclToEmit(GD.getWithDecl(FD));
3115             break;
3116           }
3117         }
3118       }
3119     }
3120   }
3121 
3122   // Make sure the result is of the requested type.
3123   if (!IsIncompleteFunction) {
3124     assert(F->getType()->getElementType() == Ty);
3125     return F;
3126   }
3127 
3128   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3129   return llvm::ConstantExpr::getBitCast(F, PTy);
3130 }
3131 
3132 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3133 /// non-null, then this function will use the specified type if it has to
3134 /// create it (this occurs when we see a definition of the function).
3135 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3136                                                  llvm::Type *Ty,
3137                                                  bool ForVTable,
3138                                                  bool DontDefer,
3139                                               ForDefinition_t IsForDefinition) {
3140   // If there was no specific requested type, just convert it now.
3141   if (!Ty) {
3142     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3143     Ty = getTypes().ConvertType(FD->getType());
3144   }
3145 
3146   // Devirtualized destructor calls may come through here instead of via
3147   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3148   // of the complete destructor when necessary.
3149   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3150     if (getTarget().getCXXABI().isMicrosoft() &&
3151         GD.getDtorType() == Dtor_Complete &&
3152         DD->getParent()->getNumVBases() == 0)
3153       GD = GlobalDecl(DD, Dtor_Base);
3154   }
3155 
3156   StringRef MangledName = getMangledName(GD);
3157   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3158                                  /*IsThunk=*/false, llvm::AttributeList(),
3159                                  IsForDefinition);
3160 }
3161 
3162 static const FunctionDecl *
3163 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3164   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3165   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3166 
3167   IdentifierInfo &CII = C.Idents.get(Name);
3168   for (const auto &Result : DC->lookup(&CII))
3169     if (const auto FD = dyn_cast<FunctionDecl>(Result))
3170       return FD;
3171 
3172   if (!C.getLangOpts().CPlusPlus)
3173     return nullptr;
3174 
3175   // Demangle the premangled name from getTerminateFn()
3176   IdentifierInfo &CXXII =
3177       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3178           ? C.Idents.get("terminate")
3179           : C.Idents.get(Name);
3180 
3181   for (const auto &N : {"__cxxabiv1", "std"}) {
3182     IdentifierInfo &NS = C.Idents.get(N);
3183     for (const auto &Result : DC->lookup(&NS)) {
3184       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3185       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3186         for (const auto &Result : LSD->lookup(&NS))
3187           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3188             break;
3189 
3190       if (ND)
3191         for (const auto &Result : ND->lookup(&CXXII))
3192           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3193             return FD;
3194     }
3195   }
3196 
3197   return nullptr;
3198 }
3199 
3200 /// CreateRuntimeFunction - Create a new runtime function with the specified
3201 /// type and name.
3202 llvm::FunctionCallee
3203 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3204                                      llvm::AttributeList ExtraAttrs,
3205                                      bool Local) {
3206   llvm::Constant *C =
3207       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3208                               /*DontDefer=*/false, /*IsThunk=*/false,
3209                               ExtraAttrs);
3210 
3211   if (auto *F = dyn_cast<llvm::Function>(C)) {
3212     if (F->empty()) {
3213       F->setCallingConv(getRuntimeCC());
3214 
3215       // In Windows Itanium environments, try to mark runtime functions
3216       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3217       // will link their standard library statically or dynamically. Marking
3218       // functions imported when they are not imported can cause linker errors
3219       // and warnings.
3220       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3221           !getCodeGenOpts().LTOVisibilityPublicStd) {
3222         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3223         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3224           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3225           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3226         }
3227       }
3228       setDSOLocal(F);
3229     }
3230   }
3231 
3232   return {FTy, C};
3233 }
3234 
3235 /// isTypeConstant - Determine whether an object of this type can be emitted
3236 /// as a constant.
3237 ///
3238 /// If ExcludeCtor is true, the duration when the object's constructor runs
3239 /// will not be considered. The caller will need to verify that the object is
3240 /// not written to during its construction.
3241 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3242   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3243     return false;
3244 
3245   if (Context.getLangOpts().CPlusPlus) {
3246     if (const CXXRecordDecl *Record
3247           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3248       return ExcludeCtor && !Record->hasMutableFields() &&
3249              Record->hasTrivialDestructor();
3250   }
3251 
3252   return true;
3253 }
3254 
3255 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3256 /// create and return an llvm GlobalVariable with the specified type.  If there
3257 /// is something in the module with the specified name, return it potentially
3258 /// bitcasted to the right type.
3259 ///
3260 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3261 /// to set the attributes on the global when it is first created.
3262 ///
3263 /// If IsForDefinition is true, it is guaranteed that an actual global with
3264 /// type Ty will be returned, not conversion of a variable with the same
3265 /// mangled name but some other type.
3266 llvm::Constant *
3267 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3268                                      llvm::PointerType *Ty,
3269                                      const VarDecl *D,
3270                                      ForDefinition_t IsForDefinition) {
3271   // Lookup the entry, lazily creating it if necessary.
3272   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3273   if (Entry) {
3274     if (WeakRefReferences.erase(Entry)) {
3275       if (D && !D->hasAttr<WeakAttr>())
3276         Entry->setLinkage(llvm::Function::ExternalLinkage);
3277     }
3278 
3279     // Handle dropped DLL attributes.
3280     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3281       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3282 
3283     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3284       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3285 
3286     if (Entry->getType() == Ty)
3287       return Entry;
3288 
3289     // If there are two attempts to define the same mangled name, issue an
3290     // error.
3291     if (IsForDefinition && !Entry->isDeclaration()) {
3292       GlobalDecl OtherGD;
3293       const VarDecl *OtherD;
3294 
3295       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3296       // to make sure that we issue an error only once.
3297       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3298           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3299           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3300           OtherD->hasInit() &&
3301           DiagnosedConflictingDefinitions.insert(D).second) {
3302         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3303             << MangledName;
3304         getDiags().Report(OtherGD.getDecl()->getLocation(),
3305                           diag::note_previous_definition);
3306       }
3307     }
3308 
3309     // Make sure the result is of the correct type.
3310     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3311       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3312 
3313     // (If global is requested for a definition, we always need to create a new
3314     // global, not just return a bitcast.)
3315     if (!IsForDefinition)
3316       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3317   }
3318 
3319   auto AddrSpace = GetGlobalVarAddressSpace(D);
3320   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3321 
3322   auto *GV = new llvm::GlobalVariable(
3323       getModule(), Ty->getElementType(), false,
3324       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3325       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3326 
3327   // If we already created a global with the same mangled name (but different
3328   // type) before, take its name and remove it from its parent.
3329   if (Entry) {
3330     GV->takeName(Entry);
3331 
3332     if (!Entry->use_empty()) {
3333       llvm::Constant *NewPtrForOldDecl =
3334           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3335       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3336     }
3337 
3338     Entry->eraseFromParent();
3339   }
3340 
3341   // This is the first use or definition of a mangled name.  If there is a
3342   // deferred decl with this name, remember that we need to emit it at the end
3343   // of the file.
3344   auto DDI = DeferredDecls.find(MangledName);
3345   if (DDI != DeferredDecls.end()) {
3346     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3347     // list, and remove it from DeferredDecls (since we don't need it anymore).
3348     addDeferredDeclToEmit(DDI->second);
3349     DeferredDecls.erase(DDI);
3350   }
3351 
3352   // Handle things which are present even on external declarations.
3353   if (D) {
3354     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3355       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3356 
3357     // FIXME: This code is overly simple and should be merged with other global
3358     // handling.
3359     GV->setConstant(isTypeConstant(D->getType(), false));
3360 
3361     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3362 
3363     setLinkageForGV(GV, D);
3364 
3365     if (D->getTLSKind()) {
3366       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3367         CXXThreadLocals.push_back(D);
3368       setTLSMode(GV, *D);
3369     }
3370 
3371     setGVProperties(GV, D);
3372 
3373     // If required by the ABI, treat declarations of static data members with
3374     // inline initializers as definitions.
3375     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3376       EmitGlobalVarDefinition(D);
3377     }
3378 
3379     // Emit section information for extern variables.
3380     if (D->hasExternalStorage()) {
3381       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3382         GV->setSection(SA->getName());
3383     }
3384 
3385     // Handle XCore specific ABI requirements.
3386     if (getTriple().getArch() == llvm::Triple::xcore &&
3387         D->getLanguageLinkage() == CLanguageLinkage &&
3388         D->getType().isConstant(Context) &&
3389         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3390       GV->setSection(".cp.rodata");
3391 
3392     // Check if we a have a const declaration with an initializer, we may be
3393     // able to emit it as available_externally to expose it's value to the
3394     // optimizer.
3395     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3396         D->getType().isConstQualified() && !GV->hasInitializer() &&
3397         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3398       const auto *Record =
3399           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3400       bool HasMutableFields = Record && Record->hasMutableFields();
3401       if (!HasMutableFields) {
3402         const VarDecl *InitDecl;
3403         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3404         if (InitExpr) {
3405           ConstantEmitter emitter(*this);
3406           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3407           if (Init) {
3408             auto *InitType = Init->getType();
3409             if (GV->getType()->getElementType() != InitType) {
3410               // The type of the initializer does not match the definition.
3411               // This happens when an initializer has a different type from
3412               // the type of the global (because of padding at the end of a
3413               // structure for instance).
3414               GV->setName(StringRef());
3415               // Make a new global with the correct type, this is now guaranteed
3416               // to work.
3417               auto *NewGV = cast<llvm::GlobalVariable>(
3418                   GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3419 
3420               // Erase the old global, since it is no longer used.
3421               GV->eraseFromParent();
3422               GV = NewGV;
3423             } else {
3424               GV->setInitializer(Init);
3425               GV->setConstant(true);
3426               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3427             }
3428             emitter.finalize(GV);
3429           }
3430         }
3431       }
3432     }
3433   }
3434 
3435   LangAS ExpectedAS =
3436       D ? D->getType().getAddressSpace()
3437         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3438   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3439          Ty->getPointerAddressSpace());
3440   if (AddrSpace != ExpectedAS)
3441     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3442                                                        ExpectedAS, Ty);
3443 
3444   if (GV->isDeclaration())
3445     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3446 
3447   return GV;
3448 }
3449 
3450 llvm::Constant *
3451 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3452                                ForDefinition_t IsForDefinition) {
3453   const Decl *D = GD.getDecl();
3454   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3455     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3456                                 /*DontDefer=*/false, IsForDefinition);
3457   else if (isa<CXXMethodDecl>(D)) {
3458     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3459         cast<CXXMethodDecl>(D));
3460     auto Ty = getTypes().GetFunctionType(*FInfo);
3461     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3462                              IsForDefinition);
3463   } else if (isa<FunctionDecl>(D)) {
3464     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3465     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3466     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3467                              IsForDefinition);
3468   } else
3469     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3470                               IsForDefinition);
3471 }
3472 
3473 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3474     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3475     unsigned Alignment) {
3476   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3477   llvm::GlobalVariable *OldGV = nullptr;
3478 
3479   if (GV) {
3480     // Check if the variable has the right type.
3481     if (GV->getType()->getElementType() == Ty)
3482       return GV;
3483 
3484     // Because C++ name mangling, the only way we can end up with an already
3485     // existing global with the same name is if it has been declared extern "C".
3486     assert(GV->isDeclaration() && "Declaration has wrong type!");
3487     OldGV = GV;
3488   }
3489 
3490   // Create a new variable.
3491   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3492                                 Linkage, nullptr, Name);
3493 
3494   if (OldGV) {
3495     // Replace occurrences of the old variable if needed.
3496     GV->takeName(OldGV);
3497 
3498     if (!OldGV->use_empty()) {
3499       llvm::Constant *NewPtrForOldDecl =
3500       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3501       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3502     }
3503 
3504     OldGV->eraseFromParent();
3505   }
3506 
3507   if (supportsCOMDAT() && GV->isWeakForLinker() &&
3508       !GV->hasAvailableExternallyLinkage())
3509     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3510 
3511   GV->setAlignment(Alignment);
3512 
3513   return GV;
3514 }
3515 
3516 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3517 /// given global variable.  If Ty is non-null and if the global doesn't exist,
3518 /// then it will be created with the specified type instead of whatever the
3519 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3520 /// that an actual global with type Ty will be returned, not conversion of a
3521 /// variable with the same mangled name but some other type.
3522 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3523                                                   llvm::Type *Ty,
3524                                            ForDefinition_t IsForDefinition) {
3525   assert(D->hasGlobalStorage() && "Not a global variable");
3526   QualType ASTTy = D->getType();
3527   if (!Ty)
3528     Ty = getTypes().ConvertTypeForMem(ASTTy);
3529 
3530   llvm::PointerType *PTy =
3531     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3532 
3533   StringRef MangledName = getMangledName(D);
3534   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3535 }
3536 
3537 /// CreateRuntimeVariable - Create a new runtime global variable with the
3538 /// specified type and name.
3539 llvm::Constant *
3540 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3541                                      StringRef Name) {
3542   auto *Ret =
3543       GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3544   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3545   return Ret;
3546 }
3547 
3548 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3549   assert(!D->getInit() && "Cannot emit definite definitions here!");
3550 
3551   StringRef MangledName = getMangledName(D);
3552   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3553 
3554   // We already have a definition, not declaration, with the same mangled name.
3555   // Emitting of declaration is not required (and actually overwrites emitted
3556   // definition).
3557   if (GV && !GV->isDeclaration())
3558     return;
3559 
3560   // If we have not seen a reference to this variable yet, place it into the
3561   // deferred declarations table to be emitted if needed later.
3562   if (!MustBeEmitted(D) && !GV) {
3563       DeferredDecls[MangledName] = D;
3564       return;
3565   }
3566 
3567   // The tentative definition is the only definition.
3568   EmitGlobalVarDefinition(D);
3569 }
3570 
3571 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3572   return Context.toCharUnitsFromBits(
3573       getDataLayout().getTypeStoreSizeInBits(Ty));
3574 }
3575 
3576 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3577   LangAS AddrSpace = LangAS::Default;
3578   if (LangOpts.OpenCL) {
3579     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3580     assert(AddrSpace == LangAS::opencl_global ||
3581            AddrSpace == LangAS::opencl_constant ||
3582            AddrSpace == LangAS::opencl_local ||
3583            AddrSpace >= LangAS::FirstTargetAddressSpace);
3584     return AddrSpace;
3585   }
3586 
3587   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3588     if (D && D->hasAttr<CUDAConstantAttr>())
3589       return LangAS::cuda_constant;
3590     else if (D && D->hasAttr<CUDASharedAttr>())
3591       return LangAS::cuda_shared;
3592     else if (D && D->hasAttr<CUDADeviceAttr>())
3593       return LangAS::cuda_device;
3594     else if (D && D->getType().isConstQualified())
3595       return LangAS::cuda_constant;
3596     else
3597       return LangAS::cuda_device;
3598   }
3599 
3600   if (LangOpts.OpenMP) {
3601     LangAS AS;
3602     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3603       return AS;
3604   }
3605   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3606 }
3607 
3608 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3609   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3610   if (LangOpts.OpenCL)
3611     return LangAS::opencl_constant;
3612   if (auto AS = getTarget().getConstantAddressSpace())
3613     return AS.getValue();
3614   return LangAS::Default;
3615 }
3616 
3617 // In address space agnostic languages, string literals are in default address
3618 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3619 // emitted in constant address space in LLVM IR. To be consistent with other
3620 // parts of AST, string literal global variables in constant address space
3621 // need to be casted to default address space before being put into address
3622 // map and referenced by other part of CodeGen.
3623 // In OpenCL, string literals are in constant address space in AST, therefore
3624 // they should not be casted to default address space.
3625 static llvm::Constant *
3626 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3627                                        llvm::GlobalVariable *GV) {
3628   llvm::Constant *Cast = GV;
3629   if (!CGM.getLangOpts().OpenCL) {
3630     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3631       if (AS != LangAS::Default)
3632         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3633             CGM, GV, AS.getValue(), LangAS::Default,
3634             GV->getValueType()->getPointerTo(
3635                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3636     }
3637   }
3638   return Cast;
3639 }
3640 
3641 template<typename SomeDecl>
3642 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3643                                                llvm::GlobalValue *GV) {
3644   if (!getLangOpts().CPlusPlus)
3645     return;
3646 
3647   // Must have 'used' attribute, or else inline assembly can't rely on
3648   // the name existing.
3649   if (!D->template hasAttr<UsedAttr>())
3650     return;
3651 
3652   // Must have internal linkage and an ordinary name.
3653   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3654     return;
3655 
3656   // Must be in an extern "C" context. Entities declared directly within
3657   // a record are not extern "C" even if the record is in such a context.
3658   const SomeDecl *First = D->getFirstDecl();
3659   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3660     return;
3661 
3662   // OK, this is an internal linkage entity inside an extern "C" linkage
3663   // specification. Make a note of that so we can give it the "expected"
3664   // mangled name if nothing else is using that name.
3665   std::pair<StaticExternCMap::iterator, bool> R =
3666       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3667 
3668   // If we have multiple internal linkage entities with the same name
3669   // in extern "C" regions, none of them gets that name.
3670   if (!R.second)
3671     R.first->second = nullptr;
3672 }
3673 
3674 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3675   if (!CGM.supportsCOMDAT())
3676     return false;
3677 
3678   if (D.hasAttr<SelectAnyAttr>())
3679     return true;
3680 
3681   GVALinkage Linkage;
3682   if (auto *VD = dyn_cast<VarDecl>(&D))
3683     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3684   else
3685     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3686 
3687   switch (Linkage) {
3688   case GVA_Internal:
3689   case GVA_AvailableExternally:
3690   case GVA_StrongExternal:
3691     return false;
3692   case GVA_DiscardableODR:
3693   case GVA_StrongODR:
3694     return true;
3695   }
3696   llvm_unreachable("No such linkage");
3697 }
3698 
3699 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3700                                           llvm::GlobalObject &GO) {
3701   if (!shouldBeInCOMDAT(*this, D))
3702     return;
3703   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3704 }
3705 
3706 /// Pass IsTentative as true if you want to create a tentative definition.
3707 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3708                                             bool IsTentative) {
3709   // OpenCL global variables of sampler type are translated to function calls,
3710   // therefore no need to be translated.
3711   QualType ASTTy = D->getType();
3712   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3713     return;
3714 
3715   // If this is OpenMP device, check if it is legal to emit this global
3716   // normally.
3717   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3718       OpenMPRuntime->emitTargetGlobalVariable(D))
3719     return;
3720 
3721   llvm::Constant *Init = nullptr;
3722   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3723   bool NeedsGlobalCtor = false;
3724   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3725 
3726   const VarDecl *InitDecl;
3727   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3728 
3729   Optional<ConstantEmitter> emitter;
3730 
3731   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3732   // as part of their declaration."  Sema has already checked for
3733   // error cases, so we just need to set Init to UndefValue.
3734   bool IsCUDASharedVar =
3735       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3736   // Shadows of initialized device-side global variables are also left
3737   // undefined.
3738   bool IsCUDAShadowVar =
3739       !getLangOpts().CUDAIsDevice &&
3740       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3741        D->hasAttr<CUDASharedAttr>());
3742   if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
3743     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3744   else if (!InitExpr) {
3745     // This is a tentative definition; tentative definitions are
3746     // implicitly initialized with { 0 }.
3747     //
3748     // Note that tentative definitions are only emitted at the end of
3749     // a translation unit, so they should never have incomplete
3750     // type. In addition, EmitTentativeDefinition makes sure that we
3751     // never attempt to emit a tentative definition if a real one
3752     // exists. A use may still exists, however, so we still may need
3753     // to do a RAUW.
3754     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3755     Init = EmitNullConstant(D->getType());
3756   } else {
3757     initializedGlobalDecl = GlobalDecl(D);
3758     emitter.emplace(*this);
3759     Init = emitter->tryEmitForInitializer(*InitDecl);
3760 
3761     if (!Init) {
3762       QualType T = InitExpr->getType();
3763       if (D->getType()->isReferenceType())
3764         T = D->getType();
3765 
3766       if (getLangOpts().CPlusPlus) {
3767         Init = EmitNullConstant(T);
3768         NeedsGlobalCtor = true;
3769       } else {
3770         ErrorUnsupported(D, "static initializer");
3771         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3772       }
3773     } else {
3774       // We don't need an initializer, so remove the entry for the delayed
3775       // initializer position (just in case this entry was delayed) if we
3776       // also don't need to register a destructor.
3777       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3778         DelayedCXXInitPosition.erase(D);
3779     }
3780   }
3781 
3782   llvm::Type* InitType = Init->getType();
3783   llvm::Constant *Entry =
3784       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3785 
3786   // Strip off a bitcast if we got one back.
3787   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3788     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3789            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3790            // All zero index gep.
3791            CE->getOpcode() == llvm::Instruction::GetElementPtr);
3792     Entry = CE->getOperand(0);
3793   }
3794 
3795   // Entry is now either a Function or GlobalVariable.
3796   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3797 
3798   // We have a definition after a declaration with the wrong type.
3799   // We must make a new GlobalVariable* and update everything that used OldGV
3800   // (a declaration or tentative definition) with the new GlobalVariable*
3801   // (which will be a definition).
3802   //
3803   // This happens if there is a prototype for a global (e.g.
3804   // "extern int x[];") and then a definition of a different type (e.g.
3805   // "int x[10];"). This also happens when an initializer has a different type
3806   // from the type of the global (this happens with unions).
3807   if (!GV || GV->getType()->getElementType() != InitType ||
3808       GV->getType()->getAddressSpace() !=
3809           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3810 
3811     // Move the old entry aside so that we'll create a new one.
3812     Entry->setName(StringRef());
3813 
3814     // Make a new global with the correct type, this is now guaranteed to work.
3815     GV = cast<llvm::GlobalVariable>(
3816         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3817 
3818     // Replace all uses of the old global with the new global
3819     llvm::Constant *NewPtrForOldDecl =
3820         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3821     Entry->replaceAllUsesWith(NewPtrForOldDecl);
3822 
3823     // Erase the old global, since it is no longer used.
3824     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3825   }
3826 
3827   MaybeHandleStaticInExternC(D, GV);
3828 
3829   if (D->hasAttr<AnnotateAttr>())
3830     AddGlobalAnnotations(D, GV);
3831 
3832   // Set the llvm linkage type as appropriate.
3833   llvm::GlobalValue::LinkageTypes Linkage =
3834       getLLVMLinkageVarDefinition(D, GV->isConstant());
3835 
3836   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3837   // the device. [...]"
3838   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3839   // __device__, declares a variable that: [...]
3840   // Is accessible from all the threads within the grid and from the host
3841   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3842   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3843   if (GV && LangOpts.CUDA) {
3844     if (LangOpts.CUDAIsDevice) {
3845       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3846         GV->setExternallyInitialized(true);
3847     } else {
3848       // Host-side shadows of external declarations of device-side
3849       // global variables become internal definitions. These have to
3850       // be internal in order to prevent name conflicts with global
3851       // host variables with the same name in a different TUs.
3852       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3853         Linkage = llvm::GlobalValue::InternalLinkage;
3854 
3855         // Shadow variables and their properties must be registered
3856         // with CUDA runtime.
3857         unsigned Flags = 0;
3858         if (!D->hasDefinition())
3859           Flags |= CGCUDARuntime::ExternDeviceVar;
3860         if (D->hasAttr<CUDAConstantAttr>())
3861           Flags |= CGCUDARuntime::ConstantDeviceVar;
3862         // Extern global variables will be registered in the TU where they are
3863         // defined.
3864         if (!D->hasExternalStorage())
3865           getCUDARuntime().registerDeviceVar(D, *GV, Flags);
3866       } else if (D->hasAttr<CUDASharedAttr>())
3867         // __shared__ variables are odd. Shadows do get created, but
3868         // they are not registered with the CUDA runtime, so they
3869         // can't really be used to access their device-side
3870         // counterparts. It's not clear yet whether it's nvcc's bug or
3871         // a feature, but we've got to do the same for compatibility.
3872         Linkage = llvm::GlobalValue::InternalLinkage;
3873     }
3874   }
3875 
3876   GV->setInitializer(Init);
3877   if (emitter) emitter->finalize(GV);
3878 
3879   // If it is safe to mark the global 'constant', do so now.
3880   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3881                   isTypeConstant(D->getType(), true));
3882 
3883   // If it is in a read-only section, mark it 'constant'.
3884   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3885     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3886     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3887       GV->setConstant(true);
3888   }
3889 
3890   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3891 
3892 
3893   // On Darwin, if the normal linkage of a C++ thread_local variable is
3894   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3895   // copies within a linkage unit; otherwise, the backing variable has
3896   // internal linkage and all accesses should just be calls to the
3897   // Itanium-specified entry point, which has the normal linkage of the
3898   // variable. This is to preserve the ability to change the implementation
3899   // behind the scenes.
3900   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3901       Context.getTargetInfo().getTriple().isOSDarwin() &&
3902       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3903       !llvm::GlobalVariable::isWeakLinkage(Linkage))
3904     Linkage = llvm::GlobalValue::InternalLinkage;
3905 
3906   GV->setLinkage(Linkage);
3907   if (D->hasAttr<DLLImportAttr>())
3908     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3909   else if (D->hasAttr<DLLExportAttr>())
3910     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3911   else
3912     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3913 
3914   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3915     // common vars aren't constant even if declared const.
3916     GV->setConstant(false);
3917     // Tentative definition of global variables may be initialized with
3918     // non-zero null pointers. In this case they should have weak linkage
3919     // since common linkage must have zero initializer and must not have
3920     // explicit section therefore cannot have non-zero initial value.
3921     if (!GV->getInitializer()->isNullValue())
3922       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3923   }
3924 
3925   setNonAliasAttributes(D, GV);
3926 
3927   if (D->getTLSKind() && !GV->isThreadLocal()) {
3928     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3929       CXXThreadLocals.push_back(D);
3930     setTLSMode(GV, *D);
3931   }
3932 
3933   maybeSetTrivialComdat(*D, *GV);
3934 
3935   // Emit the initializer function if necessary.
3936   if (NeedsGlobalCtor || NeedsGlobalDtor)
3937     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3938 
3939   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3940 
3941   // Emit global variable debug information.
3942   if (CGDebugInfo *DI = getModuleDebugInfo())
3943     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3944       DI->EmitGlobalVariable(GV, D);
3945 }
3946 
3947 static bool isVarDeclStrongDefinition(const ASTContext &Context,
3948                                       CodeGenModule &CGM, const VarDecl *D,
3949                                       bool NoCommon) {
3950   // Don't give variables common linkage if -fno-common was specified unless it
3951   // was overridden by a NoCommon attribute.
3952   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3953     return true;
3954 
3955   // C11 6.9.2/2:
3956   //   A declaration of an identifier for an object that has file scope without
3957   //   an initializer, and without a storage-class specifier or with the
3958   //   storage-class specifier static, constitutes a tentative definition.
3959   if (D->getInit() || D->hasExternalStorage())
3960     return true;
3961 
3962   // A variable cannot be both common and exist in a section.
3963   if (D->hasAttr<SectionAttr>())
3964     return true;
3965 
3966   // A variable cannot be both common and exist in a section.
3967   // We don't try to determine which is the right section in the front-end.
3968   // If no specialized section name is applicable, it will resort to default.
3969   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3970       D->hasAttr<PragmaClangDataSectionAttr>() ||
3971       D->hasAttr<PragmaClangRodataSectionAttr>())
3972     return true;
3973 
3974   // Thread local vars aren't considered common linkage.
3975   if (D->getTLSKind())
3976     return true;
3977 
3978   // Tentative definitions marked with WeakImportAttr are true definitions.
3979   if (D->hasAttr<WeakImportAttr>())
3980     return true;
3981 
3982   // A variable cannot be both common and exist in a comdat.
3983   if (shouldBeInCOMDAT(CGM, *D))
3984     return true;
3985 
3986   // Declarations with a required alignment do not have common linkage in MSVC
3987   // mode.
3988   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3989     if (D->hasAttr<AlignedAttr>())
3990       return true;
3991     QualType VarType = D->getType();
3992     if (Context.isAlignmentRequired(VarType))
3993       return true;
3994 
3995     if (const auto *RT = VarType->getAs<RecordType>()) {
3996       const RecordDecl *RD = RT->getDecl();
3997       for (const FieldDecl *FD : RD->fields()) {
3998         if (FD->isBitField())
3999           continue;
4000         if (FD->hasAttr<AlignedAttr>())
4001           return true;
4002         if (Context.isAlignmentRequired(FD->getType()))
4003           return true;
4004       }
4005     }
4006   }
4007 
4008   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4009   // common symbols, so symbols with greater alignment requirements cannot be
4010   // common.
4011   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4012   // alignments for common symbols via the aligncomm directive, so this
4013   // restriction only applies to MSVC environments.
4014   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4015       Context.getTypeAlignIfKnown(D->getType()) >
4016           Context.toBits(CharUnits::fromQuantity(32)))
4017     return true;
4018 
4019   return false;
4020 }
4021 
4022 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4023     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4024   if (Linkage == GVA_Internal)
4025     return llvm::Function::InternalLinkage;
4026 
4027   if (D->hasAttr<WeakAttr>()) {
4028     if (IsConstantVariable)
4029       return llvm::GlobalVariable::WeakODRLinkage;
4030     else
4031       return llvm::GlobalVariable::WeakAnyLinkage;
4032   }
4033 
4034   if (const auto *FD = D->getAsFunction())
4035     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4036       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4037 
4038   // We are guaranteed to have a strong definition somewhere else,
4039   // so we can use available_externally linkage.
4040   if (Linkage == GVA_AvailableExternally)
4041     return llvm::GlobalValue::AvailableExternallyLinkage;
4042 
4043   // Note that Apple's kernel linker doesn't support symbol
4044   // coalescing, so we need to avoid linkonce and weak linkages there.
4045   // Normally, this means we just map to internal, but for explicit
4046   // instantiations we'll map to external.
4047 
4048   // In C++, the compiler has to emit a definition in every translation unit
4049   // that references the function.  We should use linkonce_odr because
4050   // a) if all references in this translation unit are optimized away, we
4051   // don't need to codegen it.  b) if the function persists, it needs to be
4052   // merged with other definitions. c) C++ has the ODR, so we know the
4053   // definition is dependable.
4054   if (Linkage == GVA_DiscardableODR)
4055     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4056                                             : llvm::Function::InternalLinkage;
4057 
4058   // An explicit instantiation of a template has weak linkage, since
4059   // explicit instantiations can occur in multiple translation units
4060   // and must all be equivalent. However, we are not allowed to
4061   // throw away these explicit instantiations.
4062   //
4063   // We don't currently support CUDA device code spread out across multiple TUs,
4064   // so say that CUDA templates are either external (for kernels) or internal.
4065   // This lets llvm perform aggressive inter-procedural optimizations.
4066   if (Linkage == GVA_StrongODR) {
4067     if (Context.getLangOpts().AppleKext)
4068       return llvm::Function::ExternalLinkage;
4069     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4070       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4071                                           : llvm::Function::InternalLinkage;
4072     return llvm::Function::WeakODRLinkage;
4073   }
4074 
4075   // C++ doesn't have tentative definitions and thus cannot have common
4076   // linkage.
4077   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4078       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4079                                  CodeGenOpts.NoCommon))
4080     return llvm::GlobalVariable::CommonLinkage;
4081 
4082   // selectany symbols are externally visible, so use weak instead of
4083   // linkonce.  MSVC optimizes away references to const selectany globals, so
4084   // all definitions should be the same and ODR linkage should be used.
4085   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4086   if (D->hasAttr<SelectAnyAttr>())
4087     return llvm::GlobalVariable::WeakODRLinkage;
4088 
4089   // Otherwise, we have strong external linkage.
4090   assert(Linkage == GVA_StrongExternal);
4091   return llvm::GlobalVariable::ExternalLinkage;
4092 }
4093 
4094 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4095     const VarDecl *VD, bool IsConstant) {
4096   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4097   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4098 }
4099 
4100 /// Replace the uses of a function that was declared with a non-proto type.
4101 /// We want to silently drop extra arguments from call sites
4102 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4103                                           llvm::Function *newFn) {
4104   // Fast path.
4105   if (old->use_empty()) return;
4106 
4107   llvm::Type *newRetTy = newFn->getReturnType();
4108   SmallVector<llvm::Value*, 4> newArgs;
4109   SmallVector<llvm::OperandBundleDef, 1> newBundles;
4110 
4111   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4112          ui != ue; ) {
4113     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4114     llvm::User *user = use->getUser();
4115 
4116     // Recognize and replace uses of bitcasts.  Most calls to
4117     // unprototyped functions will use bitcasts.
4118     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4119       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4120         replaceUsesOfNonProtoConstant(bitcast, newFn);
4121       continue;
4122     }
4123 
4124     // Recognize calls to the function.
4125     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4126     if (!callSite) continue;
4127     if (!callSite->isCallee(&*use))
4128       continue;
4129 
4130     // If the return types don't match exactly, then we can't
4131     // transform this call unless it's dead.
4132     if (callSite->getType() != newRetTy && !callSite->use_empty())
4133       continue;
4134 
4135     // Get the call site's attribute list.
4136     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4137     llvm::AttributeList oldAttrs = callSite->getAttributes();
4138 
4139     // If the function was passed too few arguments, don't transform.
4140     unsigned newNumArgs = newFn->arg_size();
4141     if (callSite->arg_size() < newNumArgs)
4142       continue;
4143 
4144     // If extra arguments were passed, we silently drop them.
4145     // If any of the types mismatch, we don't transform.
4146     unsigned argNo = 0;
4147     bool dontTransform = false;
4148     for (llvm::Argument &A : newFn->args()) {
4149       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4150         dontTransform = true;
4151         break;
4152       }
4153 
4154       // Add any parameter attributes.
4155       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4156       argNo++;
4157     }
4158     if (dontTransform)
4159       continue;
4160 
4161     // Okay, we can transform this.  Create the new call instruction and copy
4162     // over the required information.
4163     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4164 
4165     // Copy over any operand bundles.
4166     callSite->getOperandBundlesAsDefs(newBundles);
4167 
4168     llvm::CallBase *newCall;
4169     if (dyn_cast<llvm::CallInst>(callSite)) {
4170       newCall =
4171           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4172     } else {
4173       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4174       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4175                                          oldInvoke->getUnwindDest(), newArgs,
4176                                          newBundles, "", callSite);
4177     }
4178     newArgs.clear(); // for the next iteration
4179 
4180     if (!newCall->getType()->isVoidTy())
4181       newCall->takeName(callSite);
4182     newCall->setAttributes(llvm::AttributeList::get(
4183         newFn->getContext(), oldAttrs.getFnAttributes(),
4184         oldAttrs.getRetAttributes(), newArgAttrs));
4185     newCall->setCallingConv(callSite->getCallingConv());
4186 
4187     // Finally, remove the old call, replacing any uses with the new one.
4188     if (!callSite->use_empty())
4189       callSite->replaceAllUsesWith(newCall);
4190 
4191     // Copy debug location attached to CI.
4192     if (callSite->getDebugLoc())
4193       newCall->setDebugLoc(callSite->getDebugLoc());
4194 
4195     callSite->eraseFromParent();
4196   }
4197 }
4198 
4199 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4200 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4201 /// existing call uses of the old function in the module, this adjusts them to
4202 /// call the new function directly.
4203 ///
4204 /// This is not just a cleanup: the always_inline pass requires direct calls to
4205 /// functions to be able to inline them.  If there is a bitcast in the way, it
4206 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4207 /// run at -O0.
4208 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4209                                                       llvm::Function *NewFn) {
4210   // If we're redefining a global as a function, don't transform it.
4211   if (!isa<llvm::Function>(Old)) return;
4212 
4213   replaceUsesOfNonProtoConstant(Old, NewFn);
4214 }
4215 
4216 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4217   auto DK = VD->isThisDeclarationADefinition();
4218   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4219     return;
4220 
4221   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4222   // If we have a definition, this might be a deferred decl. If the
4223   // instantiation is explicit, make sure we emit it at the end.
4224   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4225     GetAddrOfGlobalVar(VD);
4226 
4227   EmitTopLevelDecl(VD);
4228 }
4229 
4230 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4231                                                  llvm::GlobalValue *GV) {
4232   const auto *D = cast<FunctionDecl>(GD.getDecl());
4233 
4234   // Compute the function info and LLVM type.
4235   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4236   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4237 
4238   // Get or create the prototype for the function.
4239   if (!GV || (GV->getType()->getElementType() != Ty))
4240     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4241                                                    /*DontDefer=*/true,
4242                                                    ForDefinition));
4243 
4244   // Already emitted.
4245   if (!GV->isDeclaration())
4246     return;
4247 
4248   // We need to set linkage and visibility on the function before
4249   // generating code for it because various parts of IR generation
4250   // want to propagate this information down (e.g. to local static
4251   // declarations).
4252   auto *Fn = cast<llvm::Function>(GV);
4253   setFunctionLinkage(GD, Fn);
4254 
4255   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4256   setGVProperties(Fn, GD);
4257 
4258   MaybeHandleStaticInExternC(D, Fn);
4259 
4260 
4261   maybeSetTrivialComdat(*D, *Fn);
4262 
4263   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
4264 
4265   setNonAliasAttributes(GD, Fn);
4266   SetLLVMFunctionAttributesForDefinition(D, Fn);
4267 
4268   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4269     AddGlobalCtor(Fn, CA->getPriority());
4270   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4271     AddGlobalDtor(Fn, DA->getPriority());
4272   if (D->hasAttr<AnnotateAttr>())
4273     AddGlobalAnnotations(D, Fn);
4274 }
4275 
4276 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4277   const auto *D = cast<ValueDecl>(GD.getDecl());
4278   const AliasAttr *AA = D->getAttr<AliasAttr>();
4279   assert(AA && "Not an alias?");
4280 
4281   StringRef MangledName = getMangledName(GD);
4282 
4283   if (AA->getAliasee() == MangledName) {
4284     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4285     return;
4286   }
4287 
4288   // If there is a definition in the module, then it wins over the alias.
4289   // This is dubious, but allow it to be safe.  Just ignore the alias.
4290   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4291   if (Entry && !Entry->isDeclaration())
4292     return;
4293 
4294   Aliases.push_back(GD);
4295 
4296   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4297 
4298   // Create a reference to the named value.  This ensures that it is emitted
4299   // if a deferred decl.
4300   llvm::Constant *Aliasee;
4301   if (isa<llvm::FunctionType>(DeclTy))
4302     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4303                                       /*ForVTable=*/false);
4304   else
4305     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4306                                     llvm::PointerType::getUnqual(DeclTy),
4307                                     /*D=*/nullptr);
4308 
4309   // Create the new alias itself, but don't set a name yet.
4310   auto *GA = llvm::GlobalAlias::create(
4311       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
4312 
4313   if (Entry) {
4314     if (GA->getAliasee() == Entry) {
4315       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4316       return;
4317     }
4318 
4319     assert(Entry->isDeclaration());
4320 
4321     // If there is a declaration in the module, then we had an extern followed
4322     // by the alias, as in:
4323     //   extern int test6();
4324     //   ...
4325     //   int test6() __attribute__((alias("test7")));
4326     //
4327     // Remove it and replace uses of it with the alias.
4328     GA->takeName(Entry);
4329 
4330     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4331                                                           Entry->getType()));
4332     Entry->eraseFromParent();
4333   } else {
4334     GA->setName(MangledName);
4335   }
4336 
4337   // Set attributes which are particular to an alias; this is a
4338   // specialization of the attributes which may be set on a global
4339   // variable/function.
4340   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4341       D->isWeakImported()) {
4342     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4343   }
4344 
4345   if (const auto *VD = dyn_cast<VarDecl>(D))
4346     if (VD->getTLSKind())
4347       setTLSMode(GA, *VD);
4348 
4349   SetCommonAttributes(GD, GA);
4350 }
4351 
4352 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4353   const auto *D = cast<ValueDecl>(GD.getDecl());
4354   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4355   assert(IFA && "Not an ifunc?");
4356 
4357   StringRef MangledName = getMangledName(GD);
4358 
4359   if (IFA->getResolver() == MangledName) {
4360     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4361     return;
4362   }
4363 
4364   // Report an error if some definition overrides ifunc.
4365   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4366   if (Entry && !Entry->isDeclaration()) {
4367     GlobalDecl OtherGD;
4368     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4369         DiagnosedConflictingDefinitions.insert(GD).second) {
4370       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4371           << MangledName;
4372       Diags.Report(OtherGD.getDecl()->getLocation(),
4373                    diag::note_previous_definition);
4374     }
4375     return;
4376   }
4377 
4378   Aliases.push_back(GD);
4379 
4380   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4381   llvm::Constant *Resolver =
4382       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4383                               /*ForVTable=*/false);
4384   llvm::GlobalIFunc *GIF =
4385       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4386                                 "", Resolver, &getModule());
4387   if (Entry) {
4388     if (GIF->getResolver() == Entry) {
4389       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4390       return;
4391     }
4392     assert(Entry->isDeclaration());
4393 
4394     // If there is a declaration in the module, then we had an extern followed
4395     // by the ifunc, as in:
4396     //   extern int test();
4397     //   ...
4398     //   int test() __attribute__((ifunc("resolver")));
4399     //
4400     // Remove it and replace uses of it with the ifunc.
4401     GIF->takeName(Entry);
4402 
4403     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4404                                                           Entry->getType()));
4405     Entry->eraseFromParent();
4406   } else
4407     GIF->setName(MangledName);
4408 
4409   SetCommonAttributes(GD, GIF);
4410 }
4411 
4412 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4413                                             ArrayRef<llvm::Type*> Tys) {
4414   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4415                                          Tys);
4416 }
4417 
4418 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4419 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4420                          const StringLiteral *Literal, bool TargetIsLSB,
4421                          bool &IsUTF16, unsigned &StringLength) {
4422   StringRef String = Literal->getString();
4423   unsigned NumBytes = String.size();
4424 
4425   // Check for simple case.
4426   if (!Literal->containsNonAsciiOrNull()) {
4427     StringLength = NumBytes;
4428     return *Map.insert(std::make_pair(String, nullptr)).first;
4429   }
4430 
4431   // Otherwise, convert the UTF8 literals into a string of shorts.
4432   IsUTF16 = true;
4433 
4434   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4435   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4436   llvm::UTF16 *ToPtr = &ToBuf[0];
4437 
4438   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4439                                  ToPtr + NumBytes, llvm::strictConversion);
4440 
4441   // ConvertUTF8toUTF16 returns the length in ToPtr.
4442   StringLength = ToPtr - &ToBuf[0];
4443 
4444   // Add an explicit null.
4445   *ToPtr = 0;
4446   return *Map.insert(std::make_pair(
4447                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4448                                    (StringLength + 1) * 2),
4449                          nullptr)).first;
4450 }
4451 
4452 ConstantAddress
4453 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4454   unsigned StringLength = 0;
4455   bool isUTF16 = false;
4456   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4457       GetConstantCFStringEntry(CFConstantStringMap, Literal,
4458                                getDataLayout().isLittleEndian(), isUTF16,
4459                                StringLength);
4460 
4461   if (auto *C = Entry.second)
4462     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4463 
4464   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4465   llvm::Constant *Zeros[] = { Zero, Zero };
4466 
4467   const ASTContext &Context = getContext();
4468   const llvm::Triple &Triple = getTriple();
4469 
4470   const auto CFRuntime = getLangOpts().CFRuntime;
4471   const bool IsSwiftABI =
4472       static_cast<unsigned>(CFRuntime) >=
4473       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4474   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4475 
4476   // If we don't already have it, get __CFConstantStringClassReference.
4477   if (!CFConstantStringClassRef) {
4478     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4479     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4480     Ty = llvm::ArrayType::get(Ty, 0);
4481 
4482     switch (CFRuntime) {
4483     default: break;
4484     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4485     case LangOptions::CoreFoundationABI::Swift5_0:
4486       CFConstantStringClassName =
4487           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4488                               : "$s10Foundation19_NSCFConstantStringCN";
4489       Ty = IntPtrTy;
4490       break;
4491     case LangOptions::CoreFoundationABI::Swift4_2:
4492       CFConstantStringClassName =
4493           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4494                               : "$S10Foundation19_NSCFConstantStringCN";
4495       Ty = IntPtrTy;
4496       break;
4497     case LangOptions::CoreFoundationABI::Swift4_1:
4498       CFConstantStringClassName =
4499           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4500                               : "__T010Foundation19_NSCFConstantStringCN";
4501       Ty = IntPtrTy;
4502       break;
4503     }
4504 
4505     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4506 
4507     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4508       llvm::GlobalValue *GV = nullptr;
4509 
4510       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4511         IdentifierInfo &II = Context.Idents.get(GV->getName());
4512         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4513         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4514 
4515         const VarDecl *VD = nullptr;
4516         for (const auto &Result : DC->lookup(&II))
4517           if ((VD = dyn_cast<VarDecl>(Result)))
4518             break;
4519 
4520         if (Triple.isOSBinFormatELF()) {
4521           if (!VD)
4522             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4523         } else {
4524           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4525           if (!VD || !VD->hasAttr<DLLExportAttr>())
4526             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4527           else
4528             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4529         }
4530 
4531         setDSOLocal(GV);
4532       }
4533     }
4534 
4535     // Decay array -> ptr
4536     CFConstantStringClassRef =
4537         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4538                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4539   }
4540 
4541   QualType CFTy = Context.getCFConstantStringType();
4542 
4543   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4544 
4545   ConstantInitBuilder Builder(*this);
4546   auto Fields = Builder.beginStruct(STy);
4547 
4548   // Class pointer.
4549   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4550 
4551   // Flags.
4552   if (IsSwiftABI) {
4553     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4554     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4555   } else {
4556     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4557   }
4558 
4559   // String pointer.
4560   llvm::Constant *C = nullptr;
4561   if (isUTF16) {
4562     auto Arr = llvm::makeArrayRef(
4563         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4564         Entry.first().size() / 2);
4565     C = llvm::ConstantDataArray::get(VMContext, Arr);
4566   } else {
4567     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4568   }
4569 
4570   // Note: -fwritable-strings doesn't make the backing store strings of
4571   // CFStrings writable. (See <rdar://problem/10657500>)
4572   auto *GV =
4573       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4574                                llvm::GlobalValue::PrivateLinkage, C, ".str");
4575   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4576   // Don't enforce the target's minimum global alignment, since the only use
4577   // of the string is via this class initializer.
4578   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4579                             : Context.getTypeAlignInChars(Context.CharTy);
4580   GV->setAlignment(Align.getQuantity());
4581 
4582   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4583   // Without it LLVM can merge the string with a non unnamed_addr one during
4584   // LTO.  Doing that changes the section it ends in, which surprises ld64.
4585   if (Triple.isOSBinFormatMachO())
4586     GV->setSection(isUTF16 ? "__TEXT,__ustring"
4587                            : "__TEXT,__cstring,cstring_literals");
4588   // Make sure the literal ends up in .rodata to allow for safe ICF and for
4589   // the static linker to adjust permissions to read-only later on.
4590   else if (Triple.isOSBinFormatELF())
4591     GV->setSection(".rodata");
4592 
4593   // String.
4594   llvm::Constant *Str =
4595       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4596 
4597   if (isUTF16)
4598     // Cast the UTF16 string to the correct type.
4599     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4600   Fields.add(Str);
4601 
4602   // String length.
4603   llvm::IntegerType *LengthTy =
4604       llvm::IntegerType::get(getModule().getContext(),
4605                              Context.getTargetInfo().getLongWidth());
4606   if (IsSwiftABI) {
4607     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4608         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4609       LengthTy = Int32Ty;
4610     else
4611       LengthTy = IntPtrTy;
4612   }
4613   Fields.addInt(LengthTy, StringLength);
4614 
4615   CharUnits Alignment = getPointerAlign();
4616 
4617   // The struct.
4618   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4619                                     /*isConstant=*/false,
4620                                     llvm::GlobalVariable::PrivateLinkage);
4621   switch (Triple.getObjectFormat()) {
4622   case llvm::Triple::UnknownObjectFormat:
4623     llvm_unreachable("unknown file format");
4624   case llvm::Triple::XCOFF:
4625     llvm_unreachable("XCOFF is not yet implemented");
4626   case llvm::Triple::COFF:
4627   case llvm::Triple::ELF:
4628   case llvm::Triple::Wasm:
4629     GV->setSection("cfstring");
4630     break;
4631   case llvm::Triple::MachO:
4632     GV->setSection("__DATA,__cfstring");
4633     break;
4634   }
4635   Entry.second = GV;
4636 
4637   return ConstantAddress(GV, Alignment);
4638 }
4639 
4640 bool CodeGenModule::getExpressionLocationsEnabled() const {
4641   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4642 }
4643 
4644 QualType CodeGenModule::getObjCFastEnumerationStateType() {
4645   if (ObjCFastEnumerationStateType.isNull()) {
4646     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4647     D->startDefinition();
4648 
4649     QualType FieldTypes[] = {
4650       Context.UnsignedLongTy,
4651       Context.getPointerType(Context.getObjCIdType()),
4652       Context.getPointerType(Context.UnsignedLongTy),
4653       Context.getConstantArrayType(Context.UnsignedLongTy,
4654                            llvm::APInt(32, 5), ArrayType::Normal, 0)
4655     };
4656 
4657     for (size_t i = 0; i < 4; ++i) {
4658       FieldDecl *Field = FieldDecl::Create(Context,
4659                                            D,
4660                                            SourceLocation(),
4661                                            SourceLocation(), nullptr,
4662                                            FieldTypes[i], /*TInfo=*/nullptr,
4663                                            /*BitWidth=*/nullptr,
4664                                            /*Mutable=*/false,
4665                                            ICIS_NoInit);
4666       Field->setAccess(AS_public);
4667       D->addDecl(Field);
4668     }
4669 
4670     D->completeDefinition();
4671     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4672   }
4673 
4674   return ObjCFastEnumerationStateType;
4675 }
4676 
4677 llvm::Constant *
4678 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4679   assert(!E->getType()->isPointerType() && "Strings are always arrays");
4680 
4681   // Don't emit it as the address of the string, emit the string data itself
4682   // as an inline array.
4683   if (E->getCharByteWidth() == 1) {
4684     SmallString<64> Str(E->getString());
4685 
4686     // Resize the string to the right size, which is indicated by its type.
4687     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4688     Str.resize(CAT->getSize().getZExtValue());
4689     return llvm::ConstantDataArray::getString(VMContext, Str, false);
4690   }
4691 
4692   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4693   llvm::Type *ElemTy = AType->getElementType();
4694   unsigned NumElements = AType->getNumElements();
4695 
4696   // Wide strings have either 2-byte or 4-byte elements.
4697   if (ElemTy->getPrimitiveSizeInBits() == 16) {
4698     SmallVector<uint16_t, 32> Elements;
4699     Elements.reserve(NumElements);
4700 
4701     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4702       Elements.push_back(E->getCodeUnit(i));
4703     Elements.resize(NumElements);
4704     return llvm::ConstantDataArray::get(VMContext, Elements);
4705   }
4706 
4707   assert(ElemTy->getPrimitiveSizeInBits() == 32);
4708   SmallVector<uint32_t, 32> Elements;
4709   Elements.reserve(NumElements);
4710 
4711   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4712     Elements.push_back(E->getCodeUnit(i));
4713   Elements.resize(NumElements);
4714   return llvm::ConstantDataArray::get(VMContext, Elements);
4715 }
4716 
4717 static llvm::GlobalVariable *
4718 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4719                       CodeGenModule &CGM, StringRef GlobalName,
4720                       CharUnits Alignment) {
4721   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4722       CGM.getStringLiteralAddressSpace());
4723 
4724   llvm::Module &M = CGM.getModule();
4725   // Create a global variable for this string
4726   auto *GV = new llvm::GlobalVariable(
4727       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4728       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4729   GV->setAlignment(Alignment.getQuantity());
4730   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4731   if (GV->isWeakForLinker()) {
4732     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4733     GV->setComdat(M.getOrInsertComdat(GV->getName()));
4734   }
4735   CGM.setDSOLocal(GV);
4736 
4737   return GV;
4738 }
4739 
4740 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4741 /// constant array for the given string literal.
4742 ConstantAddress
4743 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4744                                                   StringRef Name) {
4745   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4746 
4747   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4748   llvm::GlobalVariable **Entry = nullptr;
4749   if (!LangOpts.WritableStrings) {
4750     Entry = &ConstantStringMap[C];
4751     if (auto GV = *Entry) {
4752       if (Alignment.getQuantity() > GV->getAlignment())
4753         GV->setAlignment(Alignment.getQuantity());
4754       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4755                              Alignment);
4756     }
4757   }
4758 
4759   SmallString<256> MangledNameBuffer;
4760   StringRef GlobalVariableName;
4761   llvm::GlobalValue::LinkageTypes LT;
4762 
4763   // Mangle the string literal if that's how the ABI merges duplicate strings.
4764   // Don't do it if they are writable, since we don't want writes in one TU to
4765   // affect strings in another.
4766   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4767       !LangOpts.WritableStrings) {
4768     llvm::raw_svector_ostream Out(MangledNameBuffer);
4769     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4770     LT = llvm::GlobalValue::LinkOnceODRLinkage;
4771     GlobalVariableName = MangledNameBuffer;
4772   } else {
4773     LT = llvm::GlobalValue::PrivateLinkage;
4774     GlobalVariableName = Name;
4775   }
4776 
4777   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4778   if (Entry)
4779     *Entry = GV;
4780 
4781   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4782                                   QualType());
4783 
4784   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4785                          Alignment);
4786 }
4787 
4788 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4789 /// array for the given ObjCEncodeExpr node.
4790 ConstantAddress
4791 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4792   std::string Str;
4793   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4794 
4795   return GetAddrOfConstantCString(Str);
4796 }
4797 
4798 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4799 /// the literal and a terminating '\0' character.
4800 /// The result has pointer to array type.
4801 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4802     const std::string &Str, const char *GlobalName) {
4803   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4804   CharUnits Alignment =
4805     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4806 
4807   llvm::Constant *C =
4808       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4809 
4810   // Don't share any string literals if strings aren't constant.
4811   llvm::GlobalVariable **Entry = nullptr;
4812   if (!LangOpts.WritableStrings) {
4813     Entry = &ConstantStringMap[C];
4814     if (auto GV = *Entry) {
4815       if (Alignment.getQuantity() > GV->getAlignment())
4816         GV->setAlignment(Alignment.getQuantity());
4817       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4818                              Alignment);
4819     }
4820   }
4821 
4822   // Get the default prefix if a name wasn't specified.
4823   if (!GlobalName)
4824     GlobalName = ".str";
4825   // Create a global variable for this.
4826   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4827                                   GlobalName, Alignment);
4828   if (Entry)
4829     *Entry = GV;
4830 
4831   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4832                          Alignment);
4833 }
4834 
4835 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4836     const MaterializeTemporaryExpr *E, const Expr *Init) {
4837   assert((E->getStorageDuration() == SD_Static ||
4838           E->getStorageDuration() == SD_Thread) && "not a global temporary");
4839   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4840 
4841   // If we're not materializing a subobject of the temporary, keep the
4842   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4843   QualType MaterializedType = Init->getType();
4844   if (Init == E->GetTemporaryExpr())
4845     MaterializedType = E->getType();
4846 
4847   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4848 
4849   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4850     return ConstantAddress(Slot, Align);
4851 
4852   // FIXME: If an externally-visible declaration extends multiple temporaries,
4853   // we need to give each temporary the same name in every translation unit (and
4854   // we also need to make the temporaries externally-visible).
4855   SmallString<256> Name;
4856   llvm::raw_svector_ostream Out(Name);
4857   getCXXABI().getMangleContext().mangleReferenceTemporary(
4858       VD, E->getManglingNumber(), Out);
4859 
4860   APValue *Value = nullptr;
4861   if (E->getStorageDuration() == SD_Static) {
4862     // We might have a cached constant initializer for this temporary. Note
4863     // that this might have a different value from the value computed by
4864     // evaluating the initializer if the surrounding constant expression
4865     // modifies the temporary.
4866     Value = getContext().getMaterializedTemporaryValue(E, false);
4867     if (Value && Value->isUninit())
4868       Value = nullptr;
4869   }
4870 
4871   // Try evaluating it now, it might have a constant initializer.
4872   Expr::EvalResult EvalResult;
4873   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4874       !EvalResult.hasSideEffects())
4875     Value = &EvalResult.Val;
4876 
4877   LangAS AddrSpace =
4878       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4879 
4880   Optional<ConstantEmitter> emitter;
4881   llvm::Constant *InitialValue = nullptr;
4882   bool Constant = false;
4883   llvm::Type *Type;
4884   if (Value) {
4885     // The temporary has a constant initializer, use it.
4886     emitter.emplace(*this);
4887     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4888                                                MaterializedType);
4889     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4890     Type = InitialValue->getType();
4891   } else {
4892     // No initializer, the initialization will be provided when we
4893     // initialize the declaration which performed lifetime extension.
4894     Type = getTypes().ConvertTypeForMem(MaterializedType);
4895   }
4896 
4897   // Create a global variable for this lifetime-extended temporary.
4898   llvm::GlobalValue::LinkageTypes Linkage =
4899       getLLVMLinkageVarDefinition(VD, Constant);
4900   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4901     const VarDecl *InitVD;
4902     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4903         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4904       // Temporaries defined inside a class get linkonce_odr linkage because the
4905       // class can be defined in multiple translation units.
4906       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4907     } else {
4908       // There is no need for this temporary to have external linkage if the
4909       // VarDecl has external linkage.
4910       Linkage = llvm::GlobalVariable::InternalLinkage;
4911     }
4912   }
4913   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4914   auto *GV = new llvm::GlobalVariable(
4915       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4916       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4917   if (emitter) emitter->finalize(GV);
4918   setGVProperties(GV, VD);
4919   GV->setAlignment(Align.getQuantity());
4920   if (supportsCOMDAT() && GV->isWeakForLinker())
4921     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4922   if (VD->getTLSKind())
4923     setTLSMode(GV, *VD);
4924   llvm::Constant *CV = GV;
4925   if (AddrSpace != LangAS::Default)
4926     CV = getTargetCodeGenInfo().performAddrSpaceCast(
4927         *this, GV, AddrSpace, LangAS::Default,
4928         Type->getPointerTo(
4929             getContext().getTargetAddressSpace(LangAS::Default)));
4930   MaterializedGlobalTemporaryMap[E] = CV;
4931   return ConstantAddress(CV, Align);
4932 }
4933 
4934 /// EmitObjCPropertyImplementations - Emit information for synthesized
4935 /// properties for an implementation.
4936 void CodeGenModule::EmitObjCPropertyImplementations(const
4937                                                     ObjCImplementationDecl *D) {
4938   for (const auto *PID : D->property_impls()) {
4939     // Dynamic is just for type-checking.
4940     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4941       ObjCPropertyDecl *PD = PID->getPropertyDecl();
4942 
4943       // Determine which methods need to be implemented, some may have
4944       // been overridden. Note that ::isPropertyAccessor is not the method
4945       // we want, that just indicates if the decl came from a
4946       // property. What we want to know is if the method is defined in
4947       // this implementation.
4948       if (!D->getInstanceMethod(PD->getGetterName()))
4949         CodeGenFunction(*this).GenerateObjCGetter(
4950                                  const_cast<ObjCImplementationDecl *>(D), PID);
4951       if (!PD->isReadOnly() &&
4952           !D->getInstanceMethod(PD->getSetterName()))
4953         CodeGenFunction(*this).GenerateObjCSetter(
4954                                  const_cast<ObjCImplementationDecl *>(D), PID);
4955     }
4956   }
4957 }
4958 
4959 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
4960   const ObjCInterfaceDecl *iface = impl->getClassInterface();
4961   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4962        ivar; ivar = ivar->getNextIvar())
4963     if (ivar->getType().isDestructedType())
4964       return true;
4965 
4966   return false;
4967 }
4968 
4969 static bool AllTrivialInitializers(CodeGenModule &CGM,
4970                                    ObjCImplementationDecl *D) {
4971   CodeGenFunction CGF(CGM);
4972   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4973        E = D->init_end(); B != E; ++B) {
4974     CXXCtorInitializer *CtorInitExp = *B;
4975     Expr *Init = CtorInitExp->getInit();
4976     if (!CGF.isTrivialInitializer(Init))
4977       return false;
4978   }
4979   return true;
4980 }
4981 
4982 /// EmitObjCIvarInitializations - Emit information for ivar initialization
4983 /// for an implementation.
4984 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4985   // We might need a .cxx_destruct even if we don't have any ivar initializers.
4986   if (needsDestructMethod(D)) {
4987     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4988     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4989     ObjCMethodDecl *DTORMethod =
4990       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
4991                              cxxSelector, getContext().VoidTy, nullptr, D,
4992                              /*isInstance=*/true, /*isVariadic=*/false,
4993                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4994                              /*isDefined=*/false, ObjCMethodDecl::Required);
4995     D->addInstanceMethod(DTORMethod);
4996     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4997     D->setHasDestructors(true);
4998   }
4999 
5000   // If the implementation doesn't have any ivar initializers, we don't need
5001   // a .cxx_construct.
5002   if (D->getNumIvarInitializers() == 0 ||
5003       AllTrivialInitializers(*this, D))
5004     return;
5005 
5006   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5007   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5008   // The constructor returns 'self'.
5009   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
5010                                                 D->getLocation(),
5011                                                 D->getLocation(),
5012                                                 cxxSelector,
5013                                                 getContext().getObjCIdType(),
5014                                                 nullptr, D, /*isInstance=*/true,
5015                                                 /*isVariadic=*/false,
5016                                                 /*isPropertyAccessor=*/true,
5017                                                 /*isImplicitlyDeclared=*/true,
5018                                                 /*isDefined=*/false,
5019                                                 ObjCMethodDecl::Required);
5020   D->addInstanceMethod(CTORMethod);
5021   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5022   D->setHasNonZeroConstructors(true);
5023 }
5024 
5025 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5026 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5027   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5028       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5029     ErrorUnsupported(LSD, "linkage spec");
5030     return;
5031   }
5032 
5033   EmitDeclContext(LSD);
5034 }
5035 
5036 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5037   for (auto *I : DC->decls()) {
5038     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5039     // are themselves considered "top-level", so EmitTopLevelDecl on an
5040     // ObjCImplDecl does not recursively visit them. We need to do that in
5041     // case they're nested inside another construct (LinkageSpecDecl /
5042     // ExportDecl) that does stop them from being considered "top-level".
5043     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5044       for (auto *M : OID->methods())
5045         EmitTopLevelDecl(M);
5046     }
5047 
5048     EmitTopLevelDecl(I);
5049   }
5050 }
5051 
5052 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5053 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5054   // Ignore dependent declarations.
5055   if (D->isTemplated())
5056     return;
5057 
5058   switch (D->getKind()) {
5059   case Decl::CXXConversion:
5060   case Decl::CXXMethod:
5061   case Decl::Function:
5062     EmitGlobal(cast<FunctionDecl>(D));
5063     // Always provide some coverage mapping
5064     // even for the functions that aren't emitted.
5065     AddDeferredUnusedCoverageMapping(D);
5066     break;
5067 
5068   case Decl::CXXDeductionGuide:
5069     // Function-like, but does not result in code emission.
5070     break;
5071 
5072   case Decl::Var:
5073   case Decl::Decomposition:
5074   case Decl::VarTemplateSpecialization:
5075     EmitGlobal(cast<VarDecl>(D));
5076     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5077       for (auto *B : DD->bindings())
5078         if (auto *HD = B->getHoldingVar())
5079           EmitGlobal(HD);
5080     break;
5081 
5082   // Indirect fields from global anonymous structs and unions can be
5083   // ignored; only the actual variable requires IR gen support.
5084   case Decl::IndirectField:
5085     break;
5086 
5087   // C++ Decls
5088   case Decl::Namespace:
5089     EmitDeclContext(cast<NamespaceDecl>(D));
5090     break;
5091   case Decl::ClassTemplateSpecialization: {
5092     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5093     if (DebugInfo &&
5094         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
5095         Spec->hasDefinition())
5096       DebugInfo->completeTemplateDefinition(*Spec);
5097   } LLVM_FALLTHROUGH;
5098   case Decl::CXXRecord:
5099     if (DebugInfo) {
5100       if (auto *ES = D->getASTContext().getExternalSource())
5101         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5102           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
5103     }
5104     // Emit any static data members, they may be definitions.
5105     for (auto *I : cast<CXXRecordDecl>(D)->decls())
5106       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5107         EmitTopLevelDecl(I);
5108     break;
5109     // No code generation needed.
5110   case Decl::UsingShadow:
5111   case Decl::ClassTemplate:
5112   case Decl::VarTemplate:
5113   case Decl::VarTemplatePartialSpecialization:
5114   case Decl::FunctionTemplate:
5115   case Decl::TypeAliasTemplate:
5116   case Decl::Block:
5117   case Decl::Empty:
5118   case Decl::Binding:
5119     break;
5120   case Decl::Using:          // using X; [C++]
5121     if (CGDebugInfo *DI = getModuleDebugInfo())
5122         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5123     return;
5124   case Decl::NamespaceAlias:
5125     if (CGDebugInfo *DI = getModuleDebugInfo())
5126         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5127     return;
5128   case Decl::UsingDirective: // using namespace X; [C++]
5129     if (CGDebugInfo *DI = getModuleDebugInfo())
5130       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5131     return;
5132   case Decl::CXXConstructor:
5133     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5134     break;
5135   case Decl::CXXDestructor:
5136     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5137     break;
5138 
5139   case Decl::StaticAssert:
5140     // Nothing to do.
5141     break;
5142 
5143   // Objective-C Decls
5144 
5145   // Forward declarations, no (immediate) code generation.
5146   case Decl::ObjCInterface:
5147   case Decl::ObjCCategory:
5148     break;
5149 
5150   case Decl::ObjCProtocol: {
5151     auto *Proto = cast<ObjCProtocolDecl>(D);
5152     if (Proto->isThisDeclarationADefinition())
5153       ObjCRuntime->GenerateProtocol(Proto);
5154     break;
5155   }
5156 
5157   case Decl::ObjCCategoryImpl:
5158     // Categories have properties but don't support synthesize so we
5159     // can ignore them here.
5160     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5161     break;
5162 
5163   case Decl::ObjCImplementation: {
5164     auto *OMD = cast<ObjCImplementationDecl>(D);
5165     EmitObjCPropertyImplementations(OMD);
5166     EmitObjCIvarInitializations(OMD);
5167     ObjCRuntime->GenerateClass(OMD);
5168     // Emit global variable debug information.
5169     if (CGDebugInfo *DI = getModuleDebugInfo())
5170       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
5171         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5172             OMD->getClassInterface()), OMD->getLocation());
5173     break;
5174   }
5175   case Decl::ObjCMethod: {
5176     auto *OMD = cast<ObjCMethodDecl>(D);
5177     // If this is not a prototype, emit the body.
5178     if (OMD->getBody())
5179       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5180     break;
5181   }
5182   case Decl::ObjCCompatibleAlias:
5183     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5184     break;
5185 
5186   case Decl::PragmaComment: {
5187     const auto *PCD = cast<PragmaCommentDecl>(D);
5188     switch (PCD->getCommentKind()) {
5189     case PCK_Unknown:
5190       llvm_unreachable("unexpected pragma comment kind");
5191     case PCK_Linker:
5192       AppendLinkerOptions(PCD->getArg());
5193       break;
5194     case PCK_Lib:
5195       if (getTarget().getTriple().isOSBinFormatELF() &&
5196           !getTarget().getTriple().isPS4())
5197         AddELFLibDirective(PCD->getArg());
5198       else
5199         AddDependentLib(PCD->getArg());
5200       break;
5201     case PCK_Compiler:
5202     case PCK_ExeStr:
5203     case PCK_User:
5204       break; // We ignore all of these.
5205     }
5206     break;
5207   }
5208 
5209   case Decl::PragmaDetectMismatch: {
5210     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5211     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5212     break;
5213   }
5214 
5215   case Decl::LinkageSpec:
5216     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5217     break;
5218 
5219   case Decl::FileScopeAsm: {
5220     // File-scope asm is ignored during device-side CUDA compilation.
5221     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5222       break;
5223     // File-scope asm is ignored during device-side OpenMP compilation.
5224     if (LangOpts.OpenMPIsDevice)
5225       break;
5226     auto *AD = cast<FileScopeAsmDecl>(D);
5227     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5228     break;
5229   }
5230 
5231   case Decl::Import: {
5232     auto *Import = cast<ImportDecl>(D);
5233 
5234     // If we've already imported this module, we're done.
5235     if (!ImportedModules.insert(Import->getImportedModule()))
5236       break;
5237 
5238     // Emit debug information for direct imports.
5239     if (!Import->getImportedOwningModule()) {
5240       if (CGDebugInfo *DI = getModuleDebugInfo())
5241         DI->EmitImportDecl(*Import);
5242     }
5243 
5244     // Find all of the submodules and emit the module initializers.
5245     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5246     SmallVector<clang::Module *, 16> Stack;
5247     Visited.insert(Import->getImportedModule());
5248     Stack.push_back(Import->getImportedModule());
5249 
5250     while (!Stack.empty()) {
5251       clang::Module *Mod = Stack.pop_back_val();
5252       if (!EmittedModuleInitializers.insert(Mod).second)
5253         continue;
5254 
5255       for (auto *D : Context.getModuleInitializers(Mod))
5256         EmitTopLevelDecl(D);
5257 
5258       // Visit the submodules of this module.
5259       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5260                                              SubEnd = Mod->submodule_end();
5261            Sub != SubEnd; ++Sub) {
5262         // Skip explicit children; they need to be explicitly imported to emit
5263         // the initializers.
5264         if ((*Sub)->IsExplicit)
5265           continue;
5266 
5267         if (Visited.insert(*Sub).second)
5268           Stack.push_back(*Sub);
5269       }
5270     }
5271     break;
5272   }
5273 
5274   case Decl::Export:
5275     EmitDeclContext(cast<ExportDecl>(D));
5276     break;
5277 
5278   case Decl::OMPThreadPrivate:
5279     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5280     break;
5281 
5282   case Decl::OMPAllocate:
5283     break;
5284 
5285   case Decl::OMPDeclareReduction:
5286     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5287     break;
5288 
5289   case Decl::OMPDeclareMapper:
5290     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5291     break;
5292 
5293   case Decl::OMPRequires:
5294     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5295     break;
5296 
5297   default:
5298     // Make sure we handled everything we should, every other kind is a
5299     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5300     // function. Need to recode Decl::Kind to do that easily.
5301     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5302     break;
5303   }
5304 }
5305 
5306 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5307   // Do we need to generate coverage mapping?
5308   if (!CodeGenOpts.CoverageMapping)
5309     return;
5310   switch (D->getKind()) {
5311   case Decl::CXXConversion:
5312   case Decl::CXXMethod:
5313   case Decl::Function:
5314   case Decl::ObjCMethod:
5315   case Decl::CXXConstructor:
5316   case Decl::CXXDestructor: {
5317     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5318       return;
5319     SourceManager &SM = getContext().getSourceManager();
5320     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5321       return;
5322     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5323     if (I == DeferredEmptyCoverageMappingDecls.end())
5324       DeferredEmptyCoverageMappingDecls[D] = true;
5325     break;
5326   }
5327   default:
5328     break;
5329   };
5330 }
5331 
5332 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5333   // Do we need to generate coverage mapping?
5334   if (!CodeGenOpts.CoverageMapping)
5335     return;
5336   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5337     if (Fn->isTemplateInstantiation())
5338       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5339   }
5340   auto I = DeferredEmptyCoverageMappingDecls.find(D);
5341   if (I == DeferredEmptyCoverageMappingDecls.end())
5342     DeferredEmptyCoverageMappingDecls[D] = false;
5343   else
5344     I->second = false;
5345 }
5346 
5347 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5348   // We call takeVector() here to avoid use-after-free.
5349   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5350   // we deserialize function bodies to emit coverage info for them, and that
5351   // deserializes more declarations. How should we handle that case?
5352   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5353     if (!Entry.second)
5354       continue;
5355     const Decl *D = Entry.first;
5356     switch (D->getKind()) {
5357     case Decl::CXXConversion:
5358     case Decl::CXXMethod:
5359     case Decl::Function:
5360     case Decl::ObjCMethod: {
5361       CodeGenPGO PGO(*this);
5362       GlobalDecl GD(cast<FunctionDecl>(D));
5363       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5364                                   getFunctionLinkage(GD));
5365       break;
5366     }
5367     case Decl::CXXConstructor: {
5368       CodeGenPGO PGO(*this);
5369       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5370       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5371                                   getFunctionLinkage(GD));
5372       break;
5373     }
5374     case Decl::CXXDestructor: {
5375       CodeGenPGO PGO(*this);
5376       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5377       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5378                                   getFunctionLinkage(GD));
5379       break;
5380     }
5381     default:
5382       break;
5383     };
5384   }
5385 }
5386 
5387 /// Turns the given pointer into a constant.
5388 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5389                                           const void *Ptr) {
5390   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5391   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5392   return llvm::ConstantInt::get(i64, PtrInt);
5393 }
5394 
5395 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5396                                    llvm::NamedMDNode *&GlobalMetadata,
5397                                    GlobalDecl D,
5398                                    llvm::GlobalValue *Addr) {
5399   if (!GlobalMetadata)
5400     GlobalMetadata =
5401       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5402 
5403   // TODO: should we report variant information for ctors/dtors?
5404   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5405                            llvm::ConstantAsMetadata::get(GetPointerConstant(
5406                                CGM.getLLVMContext(), D.getDecl()))};
5407   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5408 }
5409 
5410 /// For each function which is declared within an extern "C" region and marked
5411 /// as 'used', but has internal linkage, create an alias from the unmangled
5412 /// name to the mangled name if possible. People expect to be able to refer
5413 /// to such functions with an unmangled name from inline assembly within the
5414 /// same translation unit.
5415 void CodeGenModule::EmitStaticExternCAliases() {
5416   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5417     return;
5418   for (auto &I : StaticExternCValues) {
5419     IdentifierInfo *Name = I.first;
5420     llvm::GlobalValue *Val = I.second;
5421     if (Val && !getModule().getNamedValue(Name->getName()))
5422       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5423   }
5424 }
5425 
5426 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5427                                              GlobalDecl &Result) const {
5428   auto Res = Manglings.find(MangledName);
5429   if (Res == Manglings.end())
5430     return false;
5431   Result = Res->getValue();
5432   return true;
5433 }
5434 
5435 /// Emits metadata nodes associating all the global values in the
5436 /// current module with the Decls they came from.  This is useful for
5437 /// projects using IR gen as a subroutine.
5438 ///
5439 /// Since there's currently no way to associate an MDNode directly
5440 /// with an llvm::GlobalValue, we create a global named metadata
5441 /// with the name 'clang.global.decl.ptrs'.
5442 void CodeGenModule::EmitDeclMetadata() {
5443   llvm::NamedMDNode *GlobalMetadata = nullptr;
5444 
5445   for (auto &I : MangledDeclNames) {
5446     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5447     // Some mangled names don't necessarily have an associated GlobalValue
5448     // in this module, e.g. if we mangled it for DebugInfo.
5449     if (Addr)
5450       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5451   }
5452 }
5453 
5454 /// Emits metadata nodes for all the local variables in the current
5455 /// function.
5456 void CodeGenFunction::EmitDeclMetadata() {
5457   if (LocalDeclMap.empty()) return;
5458 
5459   llvm::LLVMContext &Context = getLLVMContext();
5460 
5461   // Find the unique metadata ID for this name.
5462   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5463 
5464   llvm::NamedMDNode *GlobalMetadata = nullptr;
5465 
5466   for (auto &I : LocalDeclMap) {
5467     const Decl *D = I.first;
5468     llvm::Value *Addr = I.second.getPointer();
5469     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5470       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5471       Alloca->setMetadata(
5472           DeclPtrKind, llvm::MDNode::get(
5473                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5474     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5475       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5476       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5477     }
5478   }
5479 }
5480 
5481 void CodeGenModule::EmitVersionIdentMetadata() {
5482   llvm::NamedMDNode *IdentMetadata =
5483     TheModule.getOrInsertNamedMetadata("llvm.ident");
5484   std::string Version = getClangFullVersion();
5485   llvm::LLVMContext &Ctx = TheModule.getContext();
5486 
5487   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5488   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5489 }
5490 
5491 void CodeGenModule::EmitCommandLineMetadata() {
5492   llvm::NamedMDNode *CommandLineMetadata =
5493     TheModule.getOrInsertNamedMetadata("llvm.commandline");
5494   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5495   llvm::LLVMContext &Ctx = TheModule.getContext();
5496 
5497   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5498   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5499 }
5500 
5501 void CodeGenModule::EmitTargetMetadata() {
5502   // Warning, new MangledDeclNames may be appended within this loop.
5503   // We rely on MapVector insertions adding new elements to the end
5504   // of the container.
5505   // FIXME: Move this loop into the one target that needs it, and only
5506   // loop over those declarations for which we couldn't emit the target
5507   // metadata when we emitted the declaration.
5508   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5509     auto Val = *(MangledDeclNames.begin() + I);
5510     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5511     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
5512     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5513   }
5514 }
5515 
5516 void CodeGenModule::EmitCoverageFile() {
5517   if (getCodeGenOpts().CoverageDataFile.empty() &&
5518       getCodeGenOpts().CoverageNotesFile.empty())
5519     return;
5520 
5521   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5522   if (!CUNode)
5523     return;
5524 
5525   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5526   llvm::LLVMContext &Ctx = TheModule.getContext();
5527   auto *CoverageDataFile =
5528       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5529   auto *CoverageNotesFile =
5530       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5531   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5532     llvm::MDNode *CU = CUNode->getOperand(i);
5533     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5534     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5535   }
5536 }
5537 
5538 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5539   // Sema has checked that all uuid strings are of the form
5540   // "12345678-1234-1234-1234-1234567890ab".
5541   assert(Uuid.size() == 36);
5542   for (unsigned i = 0; i < 36; ++i) {
5543     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5544     else                                         assert(isHexDigit(Uuid[i]));
5545   }
5546 
5547   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5548   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5549 
5550   llvm::Constant *Field3[8];
5551   for (unsigned Idx = 0; Idx < 8; ++Idx)
5552     Field3[Idx] = llvm::ConstantInt::get(
5553         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5554 
5555   llvm::Constant *Fields[4] = {
5556     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
5557     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
5558     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5559     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5560   };
5561 
5562   return llvm::ConstantStruct::getAnon(Fields);
5563 }
5564 
5565 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5566                                                        bool ForEH) {
5567   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5568   // FIXME: should we even be calling this method if RTTI is disabled
5569   // and it's not for EH?
5570   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5571     return llvm::Constant::getNullValue(Int8PtrTy);
5572 
5573   if (ForEH && Ty->isObjCObjectPointerType() &&
5574       LangOpts.ObjCRuntime.isGNUFamily())
5575     return ObjCRuntime->GetEHType(Ty);
5576 
5577   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5578 }
5579 
5580 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5581   // Do not emit threadprivates in simd-only mode.
5582   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5583     return;
5584   for (auto RefExpr : D->varlists()) {
5585     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5586     bool PerformInit =
5587         VD->getAnyInitializer() &&
5588         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5589                                                         /*ForRef=*/false);
5590 
5591     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5592     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5593             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5594       CXXGlobalInits.push_back(InitFunction);
5595   }
5596 }
5597 
5598 llvm::Metadata *
5599 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5600                                             StringRef Suffix) {
5601   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5602   if (InternalId)
5603     return InternalId;
5604 
5605   if (isExternallyVisible(T->getLinkage())) {
5606     std::string OutName;
5607     llvm::raw_string_ostream Out(OutName);
5608     getCXXABI().getMangleContext().mangleTypeName(T, Out);
5609     Out << Suffix;
5610 
5611     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5612   } else {
5613     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5614                                            llvm::ArrayRef<llvm::Metadata *>());
5615   }
5616 
5617   return InternalId;
5618 }
5619 
5620 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5621   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5622 }
5623 
5624 llvm::Metadata *
5625 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5626   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5627 }
5628 
5629 // Generalize pointer types to a void pointer with the qualifiers of the
5630 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5631 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5632 // 'void *'.
5633 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5634   if (!Ty->isPointerType())
5635     return Ty;
5636 
5637   return Ctx.getPointerType(
5638       QualType(Ctx.VoidTy).withCVRQualifiers(
5639           Ty->getPointeeType().getCVRQualifiers()));
5640 }
5641 
5642 // Apply type generalization to a FunctionType's return and argument types
5643 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5644   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5645     SmallVector<QualType, 8> GeneralizedParams;
5646     for (auto &Param : FnType->param_types())
5647       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5648 
5649     return Ctx.getFunctionType(
5650         GeneralizeType(Ctx, FnType->getReturnType()),
5651         GeneralizedParams, FnType->getExtProtoInfo());
5652   }
5653 
5654   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5655     return Ctx.getFunctionNoProtoType(
5656         GeneralizeType(Ctx, FnType->getReturnType()));
5657 
5658   llvm_unreachable("Encountered unknown FunctionType");
5659 }
5660 
5661 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5662   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5663                                       GeneralizedMetadataIdMap, ".generalized");
5664 }
5665 
5666 /// Returns whether this module needs the "all-vtables" type identifier.
5667 bool CodeGenModule::NeedAllVtablesTypeId() const {
5668   // Returns true if at least one of vtable-based CFI checkers is enabled and
5669   // is not in the trapping mode.
5670   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5671            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5672           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5673            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5674           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5675            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5676           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5677            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5678 }
5679 
5680 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5681                                           CharUnits Offset,
5682                                           const CXXRecordDecl *RD) {
5683   llvm::Metadata *MD =
5684       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5685   VTable->addTypeMetadata(Offset.getQuantity(), MD);
5686 
5687   if (CodeGenOpts.SanitizeCfiCrossDso)
5688     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5689       VTable->addTypeMetadata(Offset.getQuantity(),
5690                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5691 
5692   if (NeedAllVtablesTypeId()) {
5693     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5694     VTable->addTypeMetadata(Offset.getQuantity(), MD);
5695   }
5696 }
5697 
5698 TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5699   assert(TD != nullptr);
5700   TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5701 
5702   ParsedAttr.Features.erase(
5703       llvm::remove_if(ParsedAttr.Features,
5704                       [&](const std::string &Feat) {
5705                         return !Target.isValidFeatureName(
5706                             StringRef{Feat}.substr(1));
5707                       }),
5708       ParsedAttr.Features.end());
5709   return ParsedAttr;
5710 }
5711 
5712 
5713 // Fills in the supplied string map with the set of target features for the
5714 // passed in function.
5715 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5716                                           GlobalDecl GD) {
5717   StringRef TargetCPU = Target.getTargetOpts().CPU;
5718   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
5719   if (const auto *TD = FD->getAttr<TargetAttr>()) {
5720     TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
5721 
5722     // Make a copy of the features as passed on the command line into the
5723     // beginning of the additional features from the function to override.
5724     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5725                             Target.getTargetOpts().FeaturesAsWritten.begin(),
5726                             Target.getTargetOpts().FeaturesAsWritten.end());
5727 
5728     if (ParsedAttr.Architecture != "" &&
5729         Target.isValidCPUName(ParsedAttr.Architecture))
5730       TargetCPU = ParsedAttr.Architecture;
5731 
5732     // Now populate the feature map, first with the TargetCPU which is either
5733     // the default or a new one from the target attribute string. Then we'll use
5734     // the passed in features (FeaturesAsWritten) along with the new ones from
5735     // the attribute.
5736     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5737                           ParsedAttr.Features);
5738   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5739     llvm::SmallVector<StringRef, 32> FeaturesTmp;
5740     Target.getCPUSpecificCPUDispatchFeatures(
5741         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
5742     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5743     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
5744   } else {
5745     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5746                           Target.getTargetOpts().Features);
5747   }
5748 }
5749 
5750 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5751   if (!SanStats)
5752     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5753 
5754   return *SanStats;
5755 }
5756 llvm::Value *
5757 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5758                                                   CodeGenFunction &CGF) {
5759   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5760   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5761   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5762   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5763                                 "__translate_sampler_initializer"),
5764                                 {C});
5765 }
5766