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