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