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