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