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