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