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