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