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