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