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