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