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