xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/CodeGen/CodeGenModule.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This coordinates the per-module state used while generating code.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "CodeGenModule.h"
147330f729Sjoerg #include "CGBlocks.h"
157330f729Sjoerg #include "CGCUDARuntime.h"
167330f729Sjoerg #include "CGCXXABI.h"
177330f729Sjoerg #include "CGCall.h"
187330f729Sjoerg #include "CGDebugInfo.h"
197330f729Sjoerg #include "CGObjCRuntime.h"
207330f729Sjoerg #include "CGOpenCLRuntime.h"
217330f729Sjoerg #include "CGOpenMPRuntime.h"
22*e038c9c4Sjoerg #include "CGOpenMPRuntimeAMDGCN.h"
237330f729Sjoerg #include "CGOpenMPRuntimeNVPTX.h"
247330f729Sjoerg #include "CodeGenFunction.h"
257330f729Sjoerg #include "CodeGenPGO.h"
267330f729Sjoerg #include "ConstantEmitter.h"
277330f729Sjoerg #include "CoverageMappingGen.h"
287330f729Sjoerg #include "TargetInfo.h"
297330f729Sjoerg #include "clang/AST/ASTContext.h"
307330f729Sjoerg #include "clang/AST/CharUnits.h"
317330f729Sjoerg #include "clang/AST/DeclCXX.h"
327330f729Sjoerg #include "clang/AST/DeclObjC.h"
337330f729Sjoerg #include "clang/AST/DeclTemplate.h"
347330f729Sjoerg #include "clang/AST/Mangle.h"
357330f729Sjoerg #include "clang/AST/RecordLayout.h"
367330f729Sjoerg #include "clang/AST/RecursiveASTVisitor.h"
377330f729Sjoerg #include "clang/AST/StmtVisitor.h"
387330f729Sjoerg #include "clang/Basic/Builtins.h"
397330f729Sjoerg #include "clang/Basic/CharInfo.h"
407330f729Sjoerg #include "clang/Basic/CodeGenOptions.h"
417330f729Sjoerg #include "clang/Basic/Diagnostic.h"
42*e038c9c4Sjoerg #include "clang/Basic/FileManager.h"
437330f729Sjoerg #include "clang/Basic/Module.h"
447330f729Sjoerg #include "clang/Basic/SourceManager.h"
457330f729Sjoerg #include "clang/Basic/TargetInfo.h"
467330f729Sjoerg #include "clang/Basic/Version.h"
477330f729Sjoerg #include "clang/CodeGen/ConstantInitBuilder.h"
487330f729Sjoerg #include "clang/Frontend/FrontendDiagnostic.h"
497330f729Sjoerg #include "llvm/ADT/StringSwitch.h"
507330f729Sjoerg #include "llvm/ADT/Triple.h"
517330f729Sjoerg #include "llvm/Analysis/TargetLibraryInfo.h"
52*e038c9c4Sjoerg #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
537330f729Sjoerg #include "llvm/IR/CallingConv.h"
547330f729Sjoerg #include "llvm/IR/DataLayout.h"
557330f729Sjoerg #include "llvm/IR/Intrinsics.h"
567330f729Sjoerg #include "llvm/IR/LLVMContext.h"
577330f729Sjoerg #include "llvm/IR/Module.h"
587330f729Sjoerg #include "llvm/IR/ProfileSummary.h"
597330f729Sjoerg #include "llvm/ProfileData/InstrProfReader.h"
607330f729Sjoerg #include "llvm/Support/CodeGen.h"
61*e038c9c4Sjoerg #include "llvm/Support/CommandLine.h"
627330f729Sjoerg #include "llvm/Support/ConvertUTF.h"
637330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
647330f729Sjoerg #include "llvm/Support/MD5.h"
657330f729Sjoerg #include "llvm/Support/TimeProfiler.h"
667330f729Sjoerg 
677330f729Sjoerg using namespace clang;
687330f729Sjoerg using namespace CodeGen;
697330f729Sjoerg 
707330f729Sjoerg static llvm::cl::opt<bool> LimitedCoverage(
717330f729Sjoerg     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
727330f729Sjoerg     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
737330f729Sjoerg     llvm::cl::init(false));
747330f729Sjoerg 
757330f729Sjoerg static const char AnnotationSection[] = "llvm.metadata";
767330f729Sjoerg 
createCXXABI(CodeGenModule & CGM)777330f729Sjoerg static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
78*e038c9c4Sjoerg   switch (CGM.getContext().getCXXABIKind()) {
79*e038c9c4Sjoerg   case TargetCXXABI::AppleARM64:
80*e038c9c4Sjoerg   case TargetCXXABI::Fuchsia:
817330f729Sjoerg   case TargetCXXABI::GenericAArch64:
827330f729Sjoerg   case TargetCXXABI::GenericARM:
837330f729Sjoerg   case TargetCXXABI::iOS:
847330f729Sjoerg   case TargetCXXABI::WatchOS:
857330f729Sjoerg   case TargetCXXABI::GenericMIPS:
867330f729Sjoerg   case TargetCXXABI::GenericItanium:
877330f729Sjoerg   case TargetCXXABI::WebAssembly:
88*e038c9c4Sjoerg   case TargetCXXABI::XL:
897330f729Sjoerg     return CreateItaniumCXXABI(CGM);
907330f729Sjoerg   case TargetCXXABI::Microsoft:
917330f729Sjoerg     return CreateMicrosoftCXXABI(CGM);
927330f729Sjoerg   }
937330f729Sjoerg 
947330f729Sjoerg   llvm_unreachable("invalid C++ ABI kind");
957330f729Sjoerg }
967330f729Sjoerg 
CodeGenModule(ASTContext & C,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::Module & M,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)977330f729Sjoerg CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
987330f729Sjoerg                              const PreprocessorOptions &PPO,
997330f729Sjoerg                              const CodeGenOptions &CGO, llvm::Module &M,
1007330f729Sjoerg                              DiagnosticsEngine &diags,
1017330f729Sjoerg                              CoverageSourceInfo *CoverageInfo)
1027330f729Sjoerg     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
1037330f729Sjoerg       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
1047330f729Sjoerg       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
1057330f729Sjoerg       VMContext(M.getContext()), Types(*this), VTables(*this),
1067330f729Sjoerg       SanitizerMD(new SanitizerMetadata(*this)) {
1077330f729Sjoerg 
1087330f729Sjoerg   // Initialize the type cache.
1097330f729Sjoerg   llvm::LLVMContext &LLVMContext = M.getContext();
1107330f729Sjoerg   VoidTy = llvm::Type::getVoidTy(LLVMContext);
1117330f729Sjoerg   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1127330f729Sjoerg   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
1137330f729Sjoerg   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1147330f729Sjoerg   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1157330f729Sjoerg   HalfTy = llvm::Type::getHalfTy(LLVMContext);
116*e038c9c4Sjoerg   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
1177330f729Sjoerg   FloatTy = llvm::Type::getFloatTy(LLVMContext);
1187330f729Sjoerg   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
1197330f729Sjoerg   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
1207330f729Sjoerg   PointerAlignInBytes =
1217330f729Sjoerg     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1227330f729Sjoerg   SizeSizeInBytes =
1237330f729Sjoerg     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1247330f729Sjoerg   IntAlignInBytes =
1257330f729Sjoerg     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
126*e038c9c4Sjoerg   CharTy =
127*e038c9c4Sjoerg     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
1287330f729Sjoerg   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1297330f729Sjoerg   IntPtrTy = llvm::IntegerType::get(LLVMContext,
1307330f729Sjoerg     C.getTargetInfo().getMaxPointerWidth());
1317330f729Sjoerg   Int8PtrTy = Int8Ty->getPointerTo(0);
1327330f729Sjoerg   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1337330f729Sjoerg   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1347330f729Sjoerg       M.getDataLayout().getAllocaAddrSpace());
1357330f729Sjoerg   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
1367330f729Sjoerg 
1377330f729Sjoerg   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
1387330f729Sjoerg 
1397330f729Sjoerg   if (LangOpts.ObjC)
1407330f729Sjoerg     createObjCRuntime();
1417330f729Sjoerg   if (LangOpts.OpenCL)
1427330f729Sjoerg     createOpenCLRuntime();
1437330f729Sjoerg   if (LangOpts.OpenMP)
1447330f729Sjoerg     createOpenMPRuntime();
1457330f729Sjoerg   if (LangOpts.CUDA)
1467330f729Sjoerg     createCUDARuntime();
1477330f729Sjoerg 
1487330f729Sjoerg   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
1497330f729Sjoerg   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1507330f729Sjoerg       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1517330f729Sjoerg     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
1527330f729Sjoerg                                getCXXABI().getMangleContext()));
1537330f729Sjoerg 
1547330f729Sjoerg   // If debug info or coverage generation is enabled, create the CGDebugInfo
1557330f729Sjoerg   // object.
1567330f729Sjoerg   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
1577330f729Sjoerg       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
1587330f729Sjoerg     DebugInfo.reset(new CGDebugInfo(*this));
1597330f729Sjoerg 
1607330f729Sjoerg   Block.GlobalUniqueCount = 0;
1617330f729Sjoerg 
1627330f729Sjoerg   if (C.getLangOpts().ObjC)
1637330f729Sjoerg     ObjCData.reset(new ObjCEntrypoints());
1647330f729Sjoerg 
1657330f729Sjoerg   if (CodeGenOpts.hasProfileClangUse()) {
1667330f729Sjoerg     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
1677330f729Sjoerg         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
1687330f729Sjoerg     if (auto E = ReaderOrErr.takeError()) {
1697330f729Sjoerg       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1707330f729Sjoerg                                               "Could not read profile %0: %1");
1717330f729Sjoerg       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1727330f729Sjoerg         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
1737330f729Sjoerg                                   << EI.message();
1747330f729Sjoerg       });
1757330f729Sjoerg     } else
1767330f729Sjoerg       PGOReader = std::move(ReaderOrErr.get());
1777330f729Sjoerg   }
1787330f729Sjoerg 
1797330f729Sjoerg   // If coverage mapping generation is enabled, create the
1807330f729Sjoerg   // CoverageMappingModuleGen object.
1817330f729Sjoerg   if (CodeGenOpts.CoverageMapping)
1827330f729Sjoerg     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
183*e038c9c4Sjoerg 
184*e038c9c4Sjoerg   // Generate the module name hash here if needed.
185*e038c9c4Sjoerg   if (CodeGenOpts.UniqueInternalLinkageNames &&
186*e038c9c4Sjoerg       !getModule().getSourceFileName().empty()) {
187*e038c9c4Sjoerg     std::string Path = getModule().getSourceFileName();
188*e038c9c4Sjoerg     // Check if a path substitution is needed from the MacroPrefixMap.
189*e038c9c4Sjoerg     for (const auto &Entry : PPO.MacroPrefixMap)
190*e038c9c4Sjoerg       if (Path.rfind(Entry.first, 0) != std::string::npos) {
191*e038c9c4Sjoerg         Path = Entry.second + Path.substr(Entry.first.size());
192*e038c9c4Sjoerg         break;
193*e038c9c4Sjoerg       }
194*e038c9c4Sjoerg     llvm::MD5 Md5;
195*e038c9c4Sjoerg     Md5.update(Path);
196*e038c9c4Sjoerg     llvm::MD5::MD5Result R;
197*e038c9c4Sjoerg     Md5.final(R);
198*e038c9c4Sjoerg     SmallString<32> Str;
199*e038c9c4Sjoerg     llvm::MD5::stringifyResult(R, Str);
200*e038c9c4Sjoerg     // Convert MD5hash to Decimal. Demangler suffixes can either contain
201*e038c9c4Sjoerg     // numbers or characters but not both.
202*e038c9c4Sjoerg     llvm::APInt IntHash(128, Str.str(), 16);
203*e038c9c4Sjoerg     // Prepend "__uniq" before the hash for tools like profilers to understand
204*e038c9c4Sjoerg     // that this symbol is of internal linkage type.  The "__uniq" is the
205*e038c9c4Sjoerg     // pre-determined prefix that is used to tell tools that this symbol was
206*e038c9c4Sjoerg     // created with -funique-internal-linakge-symbols and the tools can strip or
207*e038c9c4Sjoerg     // keep the prefix as needed.
208*e038c9c4Sjoerg     ModuleNameHash = (Twine(".__uniq.") +
209*e038c9c4Sjoerg         Twine(IntHash.toString(/* Radix = */ 10, /* Signed = */false))).str();
210*e038c9c4Sjoerg   }
2117330f729Sjoerg }
2127330f729Sjoerg 
~CodeGenModule()2137330f729Sjoerg CodeGenModule::~CodeGenModule() {}
2147330f729Sjoerg 
createObjCRuntime()2157330f729Sjoerg void CodeGenModule::createObjCRuntime() {
2167330f729Sjoerg   // This is just isGNUFamily(), but we want to force implementors of
2177330f729Sjoerg   // new ABIs to decide how best to do this.
2187330f729Sjoerg   switch (LangOpts.ObjCRuntime.getKind()) {
2197330f729Sjoerg   case ObjCRuntime::GNUstep:
2207330f729Sjoerg   case ObjCRuntime::GCC:
2217330f729Sjoerg   case ObjCRuntime::ObjFW:
2227330f729Sjoerg     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
2237330f729Sjoerg     return;
2247330f729Sjoerg 
2257330f729Sjoerg   case ObjCRuntime::FragileMacOSX:
2267330f729Sjoerg   case ObjCRuntime::MacOSX:
2277330f729Sjoerg   case ObjCRuntime::iOS:
2287330f729Sjoerg   case ObjCRuntime::WatchOS:
2297330f729Sjoerg     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
2307330f729Sjoerg     return;
2317330f729Sjoerg   }
2327330f729Sjoerg   llvm_unreachable("bad runtime kind");
2337330f729Sjoerg }
2347330f729Sjoerg 
createOpenCLRuntime()2357330f729Sjoerg void CodeGenModule::createOpenCLRuntime() {
2367330f729Sjoerg   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
2377330f729Sjoerg }
2387330f729Sjoerg 
createOpenMPRuntime()2397330f729Sjoerg void CodeGenModule::createOpenMPRuntime() {
2407330f729Sjoerg   // Select a specialized code generation class based on the target, if any.
2417330f729Sjoerg   // If it does not exist use the default implementation.
2427330f729Sjoerg   switch (getTriple().getArch()) {
2437330f729Sjoerg   case llvm::Triple::nvptx:
2447330f729Sjoerg   case llvm::Triple::nvptx64:
2457330f729Sjoerg     assert(getLangOpts().OpenMPIsDevice &&
2467330f729Sjoerg            "OpenMP NVPTX is only prepared to deal with device code.");
2477330f729Sjoerg     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
2487330f729Sjoerg     break;
249*e038c9c4Sjoerg   case llvm::Triple::amdgcn:
250*e038c9c4Sjoerg     assert(getLangOpts().OpenMPIsDevice &&
251*e038c9c4Sjoerg            "OpenMP AMDGCN is only prepared to deal with device code.");
252*e038c9c4Sjoerg     OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this));
253*e038c9c4Sjoerg     break;
2547330f729Sjoerg   default:
2557330f729Sjoerg     if (LangOpts.OpenMPSimd)
2567330f729Sjoerg       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
2577330f729Sjoerg     else
2587330f729Sjoerg       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
2597330f729Sjoerg     break;
2607330f729Sjoerg   }
2617330f729Sjoerg }
2627330f729Sjoerg 
createCUDARuntime()2637330f729Sjoerg void CodeGenModule::createCUDARuntime() {
2647330f729Sjoerg   CUDARuntime.reset(CreateNVCUDARuntime(*this));
2657330f729Sjoerg }
2667330f729Sjoerg 
addReplacement(StringRef Name,llvm::Constant * C)2677330f729Sjoerg void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
2687330f729Sjoerg   Replacements[Name] = C;
2697330f729Sjoerg }
2707330f729Sjoerg 
applyReplacements()2717330f729Sjoerg void CodeGenModule::applyReplacements() {
2727330f729Sjoerg   for (auto &I : Replacements) {
2737330f729Sjoerg     StringRef MangledName = I.first();
2747330f729Sjoerg     llvm::Constant *Replacement = I.second;
2757330f729Sjoerg     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2767330f729Sjoerg     if (!Entry)
2777330f729Sjoerg       continue;
2787330f729Sjoerg     auto *OldF = cast<llvm::Function>(Entry);
2797330f729Sjoerg     auto *NewF = dyn_cast<llvm::Function>(Replacement);
2807330f729Sjoerg     if (!NewF) {
2817330f729Sjoerg       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
2827330f729Sjoerg         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
2837330f729Sjoerg       } else {
2847330f729Sjoerg         auto *CE = cast<llvm::ConstantExpr>(Replacement);
2857330f729Sjoerg         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2867330f729Sjoerg                CE->getOpcode() == llvm::Instruction::GetElementPtr);
2877330f729Sjoerg         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
2887330f729Sjoerg       }
2897330f729Sjoerg     }
2907330f729Sjoerg 
2917330f729Sjoerg     // Replace old with new, but keep the old order.
2927330f729Sjoerg     OldF->replaceAllUsesWith(Replacement);
2937330f729Sjoerg     if (NewF) {
2947330f729Sjoerg       NewF->removeFromParent();
2957330f729Sjoerg       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2967330f729Sjoerg                                                        NewF);
2977330f729Sjoerg     }
2987330f729Sjoerg     OldF->eraseFromParent();
2997330f729Sjoerg   }
3007330f729Sjoerg }
3017330f729Sjoerg 
addGlobalValReplacement(llvm::GlobalValue * GV,llvm::Constant * C)3027330f729Sjoerg void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
3037330f729Sjoerg   GlobalValReplacements.push_back(std::make_pair(GV, C));
3047330f729Sjoerg }
3057330f729Sjoerg 
applyGlobalValReplacements()3067330f729Sjoerg void CodeGenModule::applyGlobalValReplacements() {
3077330f729Sjoerg   for (auto &I : GlobalValReplacements) {
3087330f729Sjoerg     llvm::GlobalValue *GV = I.first;
3097330f729Sjoerg     llvm::Constant *C = I.second;
3107330f729Sjoerg 
3117330f729Sjoerg     GV->replaceAllUsesWith(C);
3127330f729Sjoerg     GV->eraseFromParent();
3137330f729Sjoerg   }
3147330f729Sjoerg }
3157330f729Sjoerg 
3167330f729Sjoerg // This is only used in aliases that we created and we know they have a
3177330f729Sjoerg // linear structure.
getAliasedGlobal(const llvm::GlobalIndirectSymbol & GIS)3187330f729Sjoerg static const llvm::GlobalObject *getAliasedGlobal(
3197330f729Sjoerg     const llvm::GlobalIndirectSymbol &GIS) {
3207330f729Sjoerg   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
3217330f729Sjoerg   const llvm::Constant *C = &GIS;
3227330f729Sjoerg   for (;;) {
3237330f729Sjoerg     C = C->stripPointerCasts();
3247330f729Sjoerg     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
3257330f729Sjoerg       return GO;
3267330f729Sjoerg     // stripPointerCasts will not walk over weak aliases.
3277330f729Sjoerg     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
3287330f729Sjoerg     if (!GIS2)
3297330f729Sjoerg       return nullptr;
3307330f729Sjoerg     if (!Visited.insert(GIS2).second)
3317330f729Sjoerg       return nullptr;
3327330f729Sjoerg     C = GIS2->getIndirectSymbol();
3337330f729Sjoerg   }
3347330f729Sjoerg }
3357330f729Sjoerg 
checkAliases()3367330f729Sjoerg void CodeGenModule::checkAliases() {
3377330f729Sjoerg   // Check if the constructed aliases are well formed. It is really unfortunate
3387330f729Sjoerg   // that we have to do this in CodeGen, but we only construct mangled names
3397330f729Sjoerg   // and aliases during codegen.
3407330f729Sjoerg   bool Error = false;
3417330f729Sjoerg   DiagnosticsEngine &Diags = getDiags();
3427330f729Sjoerg   for (const GlobalDecl &GD : Aliases) {
3437330f729Sjoerg     const auto *D = cast<ValueDecl>(GD.getDecl());
3447330f729Sjoerg     SourceLocation Location;
3457330f729Sjoerg     bool IsIFunc = D->hasAttr<IFuncAttr>();
3467330f729Sjoerg     if (const Attr *A = D->getDefiningAttr())
3477330f729Sjoerg       Location = A->getLocation();
3487330f729Sjoerg     else
3497330f729Sjoerg       llvm_unreachable("Not an alias or ifunc?");
3507330f729Sjoerg     StringRef MangledName = getMangledName(GD);
3517330f729Sjoerg     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3527330f729Sjoerg     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
3537330f729Sjoerg     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
3547330f729Sjoerg     if (!GV) {
3557330f729Sjoerg       Error = true;
3567330f729Sjoerg       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
3577330f729Sjoerg     } else if (GV->isDeclaration()) {
3587330f729Sjoerg       Error = true;
3597330f729Sjoerg       Diags.Report(Location, diag::err_alias_to_undefined)
3607330f729Sjoerg           << IsIFunc << IsIFunc;
3617330f729Sjoerg     } else if (IsIFunc) {
3627330f729Sjoerg       // Check resolver function type.
3637330f729Sjoerg       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
3647330f729Sjoerg           GV->getType()->getPointerElementType());
3657330f729Sjoerg       assert(FTy);
3667330f729Sjoerg       if (!FTy->getReturnType()->isPointerTy())
3677330f729Sjoerg         Diags.Report(Location, diag::err_ifunc_resolver_return);
3687330f729Sjoerg     }
3697330f729Sjoerg 
3707330f729Sjoerg     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
3717330f729Sjoerg     llvm::GlobalValue *AliaseeGV;
3727330f729Sjoerg     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
3737330f729Sjoerg       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
3747330f729Sjoerg     else
3757330f729Sjoerg       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
3767330f729Sjoerg 
3777330f729Sjoerg     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3787330f729Sjoerg       StringRef AliasSection = SA->getName();
3797330f729Sjoerg       if (AliasSection != AliaseeGV->getSection())
3807330f729Sjoerg         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
3817330f729Sjoerg             << AliasSection << IsIFunc << IsIFunc;
3827330f729Sjoerg     }
3837330f729Sjoerg 
3847330f729Sjoerg     // We have to handle alias to weak aliases in here. LLVM itself disallows
3857330f729Sjoerg     // this since the object semantics would not match the IL one. For
3867330f729Sjoerg     // compatibility with gcc we implement it by just pointing the alias
3877330f729Sjoerg     // to its aliasee's aliasee. We also warn, since the user is probably
3887330f729Sjoerg     // expecting the link to be weak.
3897330f729Sjoerg     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
3907330f729Sjoerg       if (GA->isInterposable()) {
3917330f729Sjoerg         Diags.Report(Location, diag::warn_alias_to_weak_alias)
3927330f729Sjoerg             << GV->getName() << GA->getName() << IsIFunc;
3937330f729Sjoerg         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3947330f729Sjoerg             GA->getIndirectSymbol(), Alias->getType());
3957330f729Sjoerg         Alias->setIndirectSymbol(Aliasee);
3967330f729Sjoerg       }
3977330f729Sjoerg     }
3987330f729Sjoerg   }
3997330f729Sjoerg   if (!Error)
4007330f729Sjoerg     return;
4017330f729Sjoerg 
4027330f729Sjoerg   for (const GlobalDecl &GD : Aliases) {
4037330f729Sjoerg     StringRef MangledName = getMangledName(GD);
4047330f729Sjoerg     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
405*e038c9c4Sjoerg     auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
4067330f729Sjoerg     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
4077330f729Sjoerg     Alias->eraseFromParent();
4087330f729Sjoerg   }
4097330f729Sjoerg }
4107330f729Sjoerg 
clear()4117330f729Sjoerg void CodeGenModule::clear() {
4127330f729Sjoerg   DeferredDeclsToEmit.clear();
4137330f729Sjoerg   if (OpenMPRuntime)
4147330f729Sjoerg     OpenMPRuntime->clear();
4157330f729Sjoerg }
4167330f729Sjoerg 
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)4177330f729Sjoerg void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
4187330f729Sjoerg                                        StringRef MainFile) {
4197330f729Sjoerg   if (!hasDiagnostics())
4207330f729Sjoerg     return;
4217330f729Sjoerg   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
4227330f729Sjoerg     if (MainFile.empty())
4237330f729Sjoerg       MainFile = "<stdin>";
4247330f729Sjoerg     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
4257330f729Sjoerg   } else {
4267330f729Sjoerg     if (Mismatched > 0)
4277330f729Sjoerg       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
4287330f729Sjoerg 
4297330f729Sjoerg     if (Missing > 0)
4307330f729Sjoerg       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
4317330f729Sjoerg   }
4327330f729Sjoerg }
4337330f729Sjoerg 
setVisibilityFromDLLStorageClass(const clang::LangOptions & LO,llvm::Module & M)434*e038c9c4Sjoerg static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
435*e038c9c4Sjoerg                                              llvm::Module &M) {
436*e038c9c4Sjoerg   if (!LO.VisibilityFromDLLStorageClass)
437*e038c9c4Sjoerg     return;
438*e038c9c4Sjoerg 
439*e038c9c4Sjoerg   llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
440*e038c9c4Sjoerg       CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
441*e038c9c4Sjoerg   llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
442*e038c9c4Sjoerg       CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
443*e038c9c4Sjoerg   llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
444*e038c9c4Sjoerg       CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
445*e038c9c4Sjoerg   llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
446*e038c9c4Sjoerg       CodeGenModule::GetLLVMVisibility(
447*e038c9c4Sjoerg           LO.getExternDeclNoDLLStorageClassVisibility());
448*e038c9c4Sjoerg 
449*e038c9c4Sjoerg   for (llvm::GlobalValue &GV : M.global_values()) {
450*e038c9c4Sjoerg     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
451*e038c9c4Sjoerg       continue;
452*e038c9c4Sjoerg 
453*e038c9c4Sjoerg     // Reset DSO locality before setting the visibility. This removes
454*e038c9c4Sjoerg     // any effects that visibility options and annotations may have
455*e038c9c4Sjoerg     // had on the DSO locality. Setting the visibility will implicitly set
456*e038c9c4Sjoerg     // appropriate globals to DSO Local; however, this will be pessimistic
457*e038c9c4Sjoerg     // w.r.t. to the normal compiler IRGen.
458*e038c9c4Sjoerg     GV.setDSOLocal(false);
459*e038c9c4Sjoerg 
460*e038c9c4Sjoerg     if (GV.isDeclarationForLinker()) {
461*e038c9c4Sjoerg       GV.setVisibility(GV.getDLLStorageClass() ==
462*e038c9c4Sjoerg                                llvm::GlobalValue::DLLImportStorageClass
463*e038c9c4Sjoerg                            ? ExternDeclDLLImportVisibility
464*e038c9c4Sjoerg                            : ExternDeclNoDLLStorageClassVisibility);
465*e038c9c4Sjoerg     } else {
466*e038c9c4Sjoerg       GV.setVisibility(GV.getDLLStorageClass() ==
467*e038c9c4Sjoerg                                llvm::GlobalValue::DLLExportStorageClass
468*e038c9c4Sjoerg                            ? DLLExportVisibility
469*e038c9c4Sjoerg                            : NoDLLStorageClassVisibility);
470*e038c9c4Sjoerg     }
471*e038c9c4Sjoerg 
472*e038c9c4Sjoerg     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
473*e038c9c4Sjoerg   }
474*e038c9c4Sjoerg }
475*e038c9c4Sjoerg 
Release()4767330f729Sjoerg void CodeGenModule::Release() {
4777330f729Sjoerg   EmitDeferred();
4787330f729Sjoerg   EmitVTablesOpportunistically();
4797330f729Sjoerg   applyGlobalValReplacements();
4807330f729Sjoerg   applyReplacements();
4817330f729Sjoerg   checkAliases();
4827330f729Sjoerg   emitMultiVersionFunctions();
4837330f729Sjoerg   EmitCXXGlobalInitFunc();
484*e038c9c4Sjoerg   EmitCXXGlobalCleanUpFunc();
4857330f729Sjoerg   registerGlobalDtorsWithAtExit();
4867330f729Sjoerg   EmitCXXThreadLocalInitFunc();
4877330f729Sjoerg   if (ObjCRuntime)
4887330f729Sjoerg     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
4897330f729Sjoerg       AddGlobalCtor(ObjCInitFunction);
490*e038c9c4Sjoerg   if (Context.getLangOpts().CUDA && CUDARuntime) {
491*e038c9c4Sjoerg     if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
4927330f729Sjoerg       AddGlobalCtor(CudaCtorFunction);
4937330f729Sjoerg   }
4947330f729Sjoerg   if (OpenMPRuntime) {
4957330f729Sjoerg     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
4967330f729Sjoerg             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
4977330f729Sjoerg       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
4987330f729Sjoerg     }
4997330f729Sjoerg     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
5007330f729Sjoerg     OpenMPRuntime->clear();
5017330f729Sjoerg   }
5027330f729Sjoerg   if (PGOReader) {
5037330f729Sjoerg     getModule().setProfileSummary(
5047330f729Sjoerg         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
5057330f729Sjoerg         llvm::ProfileSummary::PSK_Instr);
5067330f729Sjoerg     if (PGOStats.hasDiagnostics())
5077330f729Sjoerg       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
5087330f729Sjoerg   }
5097330f729Sjoerg   EmitCtorList(GlobalCtors, "llvm.global_ctors");
5107330f729Sjoerg   EmitCtorList(GlobalDtors, "llvm.global_dtors");
5117330f729Sjoerg   EmitGlobalAnnotations();
5127330f729Sjoerg   EmitStaticExternCAliases();
5137330f729Sjoerg   EmitDeferredUnusedCoverageMappings();
514*e038c9c4Sjoerg   CodeGenPGO(*this).setValueProfilingFlag(getModule());
5157330f729Sjoerg   if (CoverageMapping)
5167330f729Sjoerg     CoverageMapping->emit();
5177330f729Sjoerg   if (CodeGenOpts.SanitizeCfiCrossDso) {
5187330f729Sjoerg     CodeGenFunction(*this).EmitCfiCheckFail();
5197330f729Sjoerg     CodeGenFunction(*this).EmitCfiCheckStub();
5207330f729Sjoerg   }
5217330f729Sjoerg   emitAtAvailableLinkGuard();
522*e038c9c4Sjoerg   if (Context.getTargetInfo().getTriple().isWasm() &&
523*e038c9c4Sjoerg       !Context.getTargetInfo().getTriple().isOSEmscripten()) {
524*e038c9c4Sjoerg     EmitMainVoidAlias();
525*e038c9c4Sjoerg   }
5267330f729Sjoerg   emitLLVMUsed();
5277330f729Sjoerg   if (SanStats)
5287330f729Sjoerg     SanStats->finish();
5297330f729Sjoerg 
5307330f729Sjoerg   if (CodeGenOpts.Autolink &&
5317330f729Sjoerg       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
5327330f729Sjoerg     EmitModuleLinkOptions();
5337330f729Sjoerg   }
5347330f729Sjoerg 
5357330f729Sjoerg   // On ELF we pass the dependent library specifiers directly to the linker
5367330f729Sjoerg   // without manipulating them. This is in contrast to other platforms where
5377330f729Sjoerg   // they are mapped to a specific linker option by the compiler. This
5387330f729Sjoerg   // difference is a result of the greater variety of ELF linkers and the fact
5397330f729Sjoerg   // that ELF linkers tend to handle libraries in a more complicated fashion
5407330f729Sjoerg   // than on other platforms. This forces us to defer handling the dependent
5417330f729Sjoerg   // libs to the linker.
5427330f729Sjoerg   //
5437330f729Sjoerg   // CUDA/HIP device and host libraries are different. Currently there is no
5447330f729Sjoerg   // way to differentiate dependent libraries for host or device. Existing
5457330f729Sjoerg   // usage of #pragma comment(lib, *) is intended for host libraries on
5467330f729Sjoerg   // Windows. Therefore emit llvm.dependent-libraries only for host.
5477330f729Sjoerg   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
5487330f729Sjoerg     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
5497330f729Sjoerg     for (auto *MD : ELFDependentLibraries)
5507330f729Sjoerg       NMD->addOperand(MD);
5517330f729Sjoerg   }
5527330f729Sjoerg 
5537330f729Sjoerg   // Record mregparm value now so it is visible through rest of codegen.
5547330f729Sjoerg   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5557330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
5567330f729Sjoerg                               CodeGenOpts.NumRegisterParameters);
5577330f729Sjoerg 
5587330f729Sjoerg   if (CodeGenOpts.DwarfVersion) {
559*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
5607330f729Sjoerg                               CodeGenOpts.DwarfVersion);
5617330f729Sjoerg   }
562*e038c9c4Sjoerg 
563*e038c9c4Sjoerg   if (CodeGenOpts.Dwarf64)
564*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
565*e038c9c4Sjoerg 
566*e038c9c4Sjoerg   if (Context.getLangOpts().SemanticInterposition)
567*e038c9c4Sjoerg     // Require various optimization to respect semantic interposition.
568*e038c9c4Sjoerg     getModule().setSemanticInterposition(1);
569*e038c9c4Sjoerg 
5707330f729Sjoerg   if (CodeGenOpts.EmitCodeView) {
5717330f729Sjoerg     // Indicate that we want CodeView in the metadata.
5727330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
5737330f729Sjoerg   }
5747330f729Sjoerg   if (CodeGenOpts.CodeViewGHash) {
5757330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
5767330f729Sjoerg   }
5777330f729Sjoerg   if (CodeGenOpts.ControlFlowGuard) {
5787330f729Sjoerg     // Function ID tables and checks for Control Flow Guard (cfguard=2).
5797330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
5807330f729Sjoerg   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
5817330f729Sjoerg     // Function ID tables for Control Flow Guard (cfguard=1).
5827330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
5837330f729Sjoerg   }
584*e038c9c4Sjoerg   if (CodeGenOpts.EHContGuard) {
585*e038c9c4Sjoerg     // Function ID tables for EH Continuation Guard.
586*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
587*e038c9c4Sjoerg   }
5887330f729Sjoerg   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
5897330f729Sjoerg     // We don't support LTO with 2 with different StrictVTablePointers
5907330f729Sjoerg     // FIXME: we could support it by stripping all the information introduced
5917330f729Sjoerg     // by StrictVTablePointers.
5927330f729Sjoerg 
5937330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
5947330f729Sjoerg 
5957330f729Sjoerg     llvm::Metadata *Ops[2] = {
5967330f729Sjoerg               llvm::MDString::get(VMContext, "StrictVTablePointers"),
5977330f729Sjoerg               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5987330f729Sjoerg                   llvm::Type::getInt32Ty(VMContext), 1))};
5997330f729Sjoerg 
6007330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Require,
6017330f729Sjoerg                               "StrictVTablePointersRequirement",
6027330f729Sjoerg                               llvm::MDNode::get(VMContext, Ops));
6037330f729Sjoerg   }
604*e038c9c4Sjoerg   if (getModuleDebugInfo())
6057330f729Sjoerg     // We support a single version in the linked module. The LLVM
6067330f729Sjoerg     // parser will drop debug info with a different version number
6077330f729Sjoerg     // (and warn about it, too).
6087330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
6097330f729Sjoerg                               llvm::DEBUG_METADATA_VERSION);
6107330f729Sjoerg 
6117330f729Sjoerg   // We need to record the widths of enums and wchar_t, so that we can generate
6127330f729Sjoerg   // the correct build attributes in the ARM backend. wchar_size is also used by
6137330f729Sjoerg   // TargetLibraryInfo.
6147330f729Sjoerg   uint64_t WCharWidth =
6157330f729Sjoerg       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
6167330f729Sjoerg   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
6177330f729Sjoerg 
6187330f729Sjoerg   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
6197330f729Sjoerg   if (   Arch == llvm::Triple::arm
6207330f729Sjoerg       || Arch == llvm::Triple::armeb
6217330f729Sjoerg       || Arch == llvm::Triple::thumb
6227330f729Sjoerg       || Arch == llvm::Triple::thumbeb) {
6237330f729Sjoerg     // The minimum width of an enum in bytes
6247330f729Sjoerg     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
6257330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
6267330f729Sjoerg   }
6277330f729Sjoerg 
628*e038c9c4Sjoerg   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
629*e038c9c4Sjoerg     StringRef ABIStr = Target.getABI();
630*e038c9c4Sjoerg     llvm::LLVMContext &Ctx = TheModule.getContext();
631*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
632*e038c9c4Sjoerg                               llvm::MDString::get(Ctx, ABIStr));
633*e038c9c4Sjoerg   }
634*e038c9c4Sjoerg 
6357330f729Sjoerg   if (CodeGenOpts.SanitizeCfiCrossDso) {
6367330f729Sjoerg     // Indicate that we want cross-DSO control flow integrity checks.
6377330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
6387330f729Sjoerg   }
6397330f729Sjoerg 
640*e038c9c4Sjoerg   if (CodeGenOpts.WholeProgramVTables) {
641*e038c9c4Sjoerg     // Indicate whether VFE was enabled for this module, so that the
642*e038c9c4Sjoerg     // vcall_visibility metadata added under whole program vtables is handled
643*e038c9c4Sjoerg     // appropriately in the optimizer.
644*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
645*e038c9c4Sjoerg                               CodeGenOpts.VirtualFunctionElimination);
646*e038c9c4Sjoerg   }
647*e038c9c4Sjoerg 
6487330f729Sjoerg   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
6497330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Override,
6507330f729Sjoerg                               "CFI Canonical Jump Tables",
6517330f729Sjoerg                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
6527330f729Sjoerg   }
6537330f729Sjoerg 
6547330f729Sjoerg   if (CodeGenOpts.CFProtectionReturn &&
6557330f729Sjoerg       Target.checkCFProtectionReturnSupported(getDiags())) {
6567330f729Sjoerg     // Indicate that we want to instrument return control flow protection.
6577330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
6587330f729Sjoerg                               1);
6597330f729Sjoerg   }
6607330f729Sjoerg 
6617330f729Sjoerg   if (CodeGenOpts.CFProtectionBranch &&
6627330f729Sjoerg       Target.checkCFProtectionBranchSupported(getDiags())) {
6637330f729Sjoerg     // Indicate that we want to instrument branch control flow protection.
6647330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
6657330f729Sjoerg                               1);
6667330f729Sjoerg   }
6677330f729Sjoerg 
668*e038c9c4Sjoerg   if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
669*e038c9c4Sjoerg       Arch == llvm::Triple::aarch64_be) {
670*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error,
671*e038c9c4Sjoerg                               "branch-target-enforcement",
672*e038c9c4Sjoerg                               LangOpts.BranchTargetEnforcement);
673*e038c9c4Sjoerg 
674*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
675*e038c9c4Sjoerg                               LangOpts.hasSignReturnAddress());
676*e038c9c4Sjoerg 
677*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
678*e038c9c4Sjoerg                               LangOpts.isSignReturnAddressScopeAll());
679*e038c9c4Sjoerg 
680*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error,
681*e038c9c4Sjoerg                               "sign-return-address-with-bkey",
682*e038c9c4Sjoerg                               !LangOpts.isSignReturnAddressWithAKey());
683*e038c9c4Sjoerg   }
684*e038c9c4Sjoerg 
685*e038c9c4Sjoerg   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
686*e038c9c4Sjoerg     llvm::LLVMContext &Ctx = TheModule.getContext();
687*e038c9c4Sjoerg     getModule().addModuleFlag(
688*e038c9c4Sjoerg         llvm::Module::Error, "MemProfProfileFilename",
689*e038c9c4Sjoerg         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
690*e038c9c4Sjoerg   }
691*e038c9c4Sjoerg 
6927330f729Sjoerg   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
6937330f729Sjoerg     // Indicate whether __nvvm_reflect should be configured to flush denormal
6947330f729Sjoerg     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
6957330f729Sjoerg     // property.)
6967330f729Sjoerg     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
697*e038c9c4Sjoerg                               CodeGenOpts.FP32DenormalMode.Output !=
698*e038c9c4Sjoerg                                   llvm::DenormalMode::IEEE);
6997330f729Sjoerg   }
7007330f729Sjoerg 
701*e038c9c4Sjoerg   if (LangOpts.EHAsynch)
702*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
703*e038c9c4Sjoerg 
7047330f729Sjoerg   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
7057330f729Sjoerg   if (LangOpts.OpenCL) {
7067330f729Sjoerg     EmitOpenCLMetadata();
7077330f729Sjoerg     // Emit SPIR version.
7087330f729Sjoerg     if (getTriple().isSPIR()) {
7097330f729Sjoerg       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7107330f729Sjoerg       // opencl.spir.version named metadata.
7117330f729Sjoerg       // C++ is backwards compatible with OpenCL v2.0.
7127330f729Sjoerg       auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
7137330f729Sjoerg       llvm::Metadata *SPIRVerElts[] = {
7147330f729Sjoerg           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7157330f729Sjoerg               Int32Ty, Version / 100)),
7167330f729Sjoerg           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7177330f729Sjoerg               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
7187330f729Sjoerg       llvm::NamedMDNode *SPIRVerMD =
7197330f729Sjoerg           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
7207330f729Sjoerg       llvm::LLVMContext &Ctx = TheModule.getContext();
7217330f729Sjoerg       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7227330f729Sjoerg     }
7237330f729Sjoerg   }
7247330f729Sjoerg 
7257330f729Sjoerg   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
7267330f729Sjoerg     assert(PLevel < 3 && "Invalid PIC Level");
7277330f729Sjoerg     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
7287330f729Sjoerg     if (Context.getLangOpts().PIE)
7297330f729Sjoerg       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
7307330f729Sjoerg   }
7317330f729Sjoerg 
7327330f729Sjoerg   if (getCodeGenOpts().CodeModel.size() > 0) {
7337330f729Sjoerg     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
7347330f729Sjoerg                   .Case("tiny", llvm::CodeModel::Tiny)
7357330f729Sjoerg                   .Case("small", llvm::CodeModel::Small)
7367330f729Sjoerg                   .Case("kernel", llvm::CodeModel::Kernel)
7377330f729Sjoerg                   .Case("medium", llvm::CodeModel::Medium)
7387330f729Sjoerg                   .Case("large", llvm::CodeModel::Large)
7397330f729Sjoerg                   .Default(~0u);
7407330f729Sjoerg     if (CM != ~0u) {
7417330f729Sjoerg       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
7427330f729Sjoerg       getModule().setCodeModel(codeModel);
7437330f729Sjoerg     }
7447330f729Sjoerg   }
7457330f729Sjoerg 
7467330f729Sjoerg   if (CodeGenOpts.NoPLT)
7477330f729Sjoerg     getModule().setRtLibUseGOT();
748*e038c9c4Sjoerg   if (CodeGenOpts.UnwindTables)
749*e038c9c4Sjoerg     getModule().setUwtable();
750*e038c9c4Sjoerg 
751*e038c9c4Sjoerg   switch (CodeGenOpts.getFramePointer()) {
752*e038c9c4Sjoerg   case CodeGenOptions::FramePointerKind::None:
753*e038c9c4Sjoerg     // 0 ("none") is the default.
754*e038c9c4Sjoerg     break;
755*e038c9c4Sjoerg   case CodeGenOptions::FramePointerKind::NonLeaf:
756*e038c9c4Sjoerg     getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
757*e038c9c4Sjoerg     break;
758*e038c9c4Sjoerg   case CodeGenOptions::FramePointerKind::All:
759*e038c9c4Sjoerg     getModule().setFramePointer(llvm::FramePointerKind::All);
760*e038c9c4Sjoerg     break;
761*e038c9c4Sjoerg   }
7627330f729Sjoerg 
7637330f729Sjoerg   SimplifyPersonality();
7647330f729Sjoerg 
7657330f729Sjoerg   if (getCodeGenOpts().EmitDeclMetadata)
7667330f729Sjoerg     EmitDeclMetadata();
7677330f729Sjoerg 
7687330f729Sjoerg   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
7697330f729Sjoerg     EmitCoverageFile();
7707330f729Sjoerg 
771*e038c9c4Sjoerg   if (CGDebugInfo *DI = getModuleDebugInfo())
772*e038c9c4Sjoerg     DI->finalize();
7737330f729Sjoerg 
7747330f729Sjoerg   if (getCodeGenOpts().EmitVersionIdentMetadata)
7757330f729Sjoerg     EmitVersionIdentMetadata();
7767330f729Sjoerg 
7777330f729Sjoerg   if (!getCodeGenOpts().RecordCommandLine.empty())
7787330f729Sjoerg     EmitCommandLineMetadata();
7797330f729Sjoerg 
780*e038c9c4Sjoerg   if (!getCodeGenOpts().StackProtectorGuard.empty())
781*e038c9c4Sjoerg     getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
782*e038c9c4Sjoerg   if (!getCodeGenOpts().StackProtectorGuardReg.empty())
783*e038c9c4Sjoerg     getModule().setStackProtectorGuardReg(
784*e038c9c4Sjoerg         getCodeGenOpts().StackProtectorGuardReg);
785*e038c9c4Sjoerg   if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
786*e038c9c4Sjoerg     getModule().setStackProtectorGuardOffset(
787*e038c9c4Sjoerg         getCodeGenOpts().StackProtectorGuardOffset);
788*e038c9c4Sjoerg 
789*e038c9c4Sjoerg   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
790*e038c9c4Sjoerg 
791*e038c9c4Sjoerg   EmitBackendOptionsMetadata(getCodeGenOpts());
792*e038c9c4Sjoerg 
793*e038c9c4Sjoerg   // Set visibility from DLL storage class
794*e038c9c4Sjoerg   // We do this at the end of LLVM IR generation; after any operation
795*e038c9c4Sjoerg   // that might affect the DLL storage class or the visibility, and
796*e038c9c4Sjoerg   // before anything that might act on these.
797*e038c9c4Sjoerg   setVisibilityFromDLLStorageClass(LangOpts, getModule());
7987330f729Sjoerg }
7997330f729Sjoerg 
EmitOpenCLMetadata()8007330f729Sjoerg void CodeGenModule::EmitOpenCLMetadata() {
8017330f729Sjoerg   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8027330f729Sjoerg   // opencl.ocl.version named metadata node.
8037330f729Sjoerg   // C++ is backwards compatible with OpenCL v2.0.
8047330f729Sjoerg   // FIXME: We might need to add CXX version at some point too?
8057330f729Sjoerg   auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
8067330f729Sjoerg   llvm::Metadata *OCLVerElts[] = {
8077330f729Sjoerg       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8087330f729Sjoerg           Int32Ty, Version / 100)),
8097330f729Sjoerg       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8107330f729Sjoerg           Int32Ty, (Version % 100) / 10))};
8117330f729Sjoerg   llvm::NamedMDNode *OCLVerMD =
8127330f729Sjoerg       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
8137330f729Sjoerg   llvm::LLVMContext &Ctx = TheModule.getContext();
8147330f729Sjoerg   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8157330f729Sjoerg }
8167330f729Sjoerg 
EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts)817*e038c9c4Sjoerg void CodeGenModule::EmitBackendOptionsMetadata(
818*e038c9c4Sjoerg     const CodeGenOptions CodeGenOpts) {
819*e038c9c4Sjoerg   switch (getTriple().getArch()) {
820*e038c9c4Sjoerg   default:
821*e038c9c4Sjoerg     break;
822*e038c9c4Sjoerg   case llvm::Triple::riscv32:
823*e038c9c4Sjoerg   case llvm::Triple::riscv64:
824*e038c9c4Sjoerg     getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
825*e038c9c4Sjoerg                               CodeGenOpts.SmallDataLimit);
826*e038c9c4Sjoerg     break;
827*e038c9c4Sjoerg   }
828*e038c9c4Sjoerg }
829*e038c9c4Sjoerg 
UpdateCompletedType(const TagDecl * TD)8307330f729Sjoerg void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
8317330f729Sjoerg   // Make sure that this type is translated.
8327330f729Sjoerg   Types.UpdateCompletedType(TD);
8337330f729Sjoerg }
8347330f729Sjoerg 
RefreshTypeCacheForClass(const CXXRecordDecl * RD)8357330f729Sjoerg void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
8367330f729Sjoerg   // Make sure that this type is translated.
8377330f729Sjoerg   Types.RefreshTypeCacheForClass(RD);
8387330f729Sjoerg }
8397330f729Sjoerg 
getTBAATypeInfo(QualType QTy)8407330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
8417330f729Sjoerg   if (!TBAA)
8427330f729Sjoerg     return nullptr;
8437330f729Sjoerg   return TBAA->getTypeInfo(QTy);
8447330f729Sjoerg }
8457330f729Sjoerg 
getTBAAAccessInfo(QualType AccessType)8467330f729Sjoerg TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
8477330f729Sjoerg   if (!TBAA)
8487330f729Sjoerg     return TBAAAccessInfo();
849*e038c9c4Sjoerg   if (getLangOpts().CUDAIsDevice) {
850*e038c9c4Sjoerg     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
851*e038c9c4Sjoerg     // access info.
852*e038c9c4Sjoerg     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
853*e038c9c4Sjoerg       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
854*e038c9c4Sjoerg           nullptr)
855*e038c9c4Sjoerg         return TBAAAccessInfo();
856*e038c9c4Sjoerg     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
857*e038c9c4Sjoerg       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
858*e038c9c4Sjoerg           nullptr)
859*e038c9c4Sjoerg         return TBAAAccessInfo();
860*e038c9c4Sjoerg     }
861*e038c9c4Sjoerg   }
8627330f729Sjoerg   return TBAA->getAccessInfo(AccessType);
8637330f729Sjoerg }
8647330f729Sjoerg 
8657330f729Sjoerg TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type * VTablePtrType)8667330f729Sjoerg CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
8677330f729Sjoerg   if (!TBAA)
8687330f729Sjoerg     return TBAAAccessInfo();
8697330f729Sjoerg   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
8707330f729Sjoerg }
8717330f729Sjoerg 
getTBAAStructInfo(QualType QTy)8727330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
8737330f729Sjoerg   if (!TBAA)
8747330f729Sjoerg     return nullptr;
8757330f729Sjoerg   return TBAA->getTBAAStructInfo(QTy);
8767330f729Sjoerg }
8777330f729Sjoerg 
getTBAABaseTypeInfo(QualType QTy)8787330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
8797330f729Sjoerg   if (!TBAA)
8807330f729Sjoerg     return nullptr;
8817330f729Sjoerg   return TBAA->getBaseTypeInfo(QTy);
8827330f729Sjoerg }
8837330f729Sjoerg 
getTBAAAccessTagInfo(TBAAAccessInfo Info)8847330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
8857330f729Sjoerg   if (!TBAA)
8867330f729Sjoerg     return nullptr;
8877330f729Sjoerg   return TBAA->getAccessTagInfo(Info);
8887330f729Sjoerg }
8897330f729Sjoerg 
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,TBAAAccessInfo TargetInfo)8907330f729Sjoerg TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
8917330f729Sjoerg                                                    TBAAAccessInfo TargetInfo) {
8927330f729Sjoerg   if (!TBAA)
8937330f729Sjoerg     return TBAAAccessInfo();
8947330f729Sjoerg   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
8957330f729Sjoerg }
8967330f729Sjoerg 
8977330f729Sjoerg TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,TBAAAccessInfo InfoB)8987330f729Sjoerg CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
8997330f729Sjoerg                                                    TBAAAccessInfo InfoB) {
9007330f729Sjoerg   if (!TBAA)
9017330f729Sjoerg     return TBAAAccessInfo();
9027330f729Sjoerg   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
9037330f729Sjoerg }
9047330f729Sjoerg 
9057330f729Sjoerg TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,TBAAAccessInfo SrcInfo)9067330f729Sjoerg CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
9077330f729Sjoerg                                               TBAAAccessInfo SrcInfo) {
9087330f729Sjoerg   if (!TBAA)
9097330f729Sjoerg     return TBAAAccessInfo();
9107330f729Sjoerg   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
9117330f729Sjoerg }
9127330f729Sjoerg 
DecorateInstructionWithTBAA(llvm::Instruction * Inst,TBAAAccessInfo TBAAInfo)9137330f729Sjoerg void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
9147330f729Sjoerg                                                 TBAAAccessInfo TBAAInfo) {
9157330f729Sjoerg   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
9167330f729Sjoerg     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
9177330f729Sjoerg }
9187330f729Sjoerg 
DecorateInstructionWithInvariantGroup(llvm::Instruction * I,const CXXRecordDecl * RD)9197330f729Sjoerg void CodeGenModule::DecorateInstructionWithInvariantGroup(
9207330f729Sjoerg     llvm::Instruction *I, const CXXRecordDecl *RD) {
9217330f729Sjoerg   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
9227330f729Sjoerg                  llvm::MDNode::get(getLLVMContext(), {}));
9237330f729Sjoerg }
9247330f729Sjoerg 
Error(SourceLocation loc,StringRef message)9257330f729Sjoerg void CodeGenModule::Error(SourceLocation loc, StringRef message) {
9267330f729Sjoerg   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
9277330f729Sjoerg   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
9287330f729Sjoerg }
9297330f729Sjoerg 
9307330f729Sjoerg /// ErrorUnsupported - Print out an error that codegen doesn't support the
9317330f729Sjoerg /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)9327330f729Sjoerg void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
9337330f729Sjoerg   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
9347330f729Sjoerg                                                "cannot compile this %0 yet");
9357330f729Sjoerg   std::string Msg = Type;
9367330f729Sjoerg   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
9377330f729Sjoerg       << Msg << S->getSourceRange();
9387330f729Sjoerg }
9397330f729Sjoerg 
9407330f729Sjoerg /// ErrorUnsupported - Print out an error that codegen doesn't support the
9417330f729Sjoerg /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)9427330f729Sjoerg void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
9437330f729Sjoerg   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
9447330f729Sjoerg                                                "cannot compile this %0 yet");
9457330f729Sjoerg   std::string Msg = Type;
9467330f729Sjoerg   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
9477330f729Sjoerg }
9487330f729Sjoerg 
getSize(CharUnits size)9497330f729Sjoerg llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
9507330f729Sjoerg   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
9517330f729Sjoerg }
9527330f729Sjoerg 
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const9537330f729Sjoerg void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
9547330f729Sjoerg                                         const NamedDecl *D) const {
9557330f729Sjoerg   if (GV->hasDLLImportStorageClass())
9567330f729Sjoerg     return;
9577330f729Sjoerg   // Internal definitions always have default visibility.
9587330f729Sjoerg   if (GV->hasLocalLinkage()) {
9597330f729Sjoerg     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
9607330f729Sjoerg     return;
9617330f729Sjoerg   }
9627330f729Sjoerg   if (!D)
9637330f729Sjoerg     return;
9647330f729Sjoerg   // Set visibility for definitions, and for declarations if requested globally
9657330f729Sjoerg   // or set explicitly.
9667330f729Sjoerg   LinkageInfo LV = D->getLinkageAndVisibility();
9677330f729Sjoerg   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
9687330f729Sjoerg       !GV->isDeclarationForLinker())
9697330f729Sjoerg     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
9707330f729Sjoerg }
9717330f729Sjoerg 
shouldAssumeDSOLocal(const CodeGenModule & CGM,llvm::GlobalValue * GV)9727330f729Sjoerg static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
9737330f729Sjoerg                                  llvm::GlobalValue *GV) {
9747330f729Sjoerg   if (GV->hasLocalLinkage())
9757330f729Sjoerg     return true;
9767330f729Sjoerg 
9777330f729Sjoerg   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
9787330f729Sjoerg     return true;
9797330f729Sjoerg 
9807330f729Sjoerg   // DLLImport explicitly marks the GV as external.
9817330f729Sjoerg   if (GV->hasDLLImportStorageClass())
9827330f729Sjoerg     return false;
9837330f729Sjoerg 
9847330f729Sjoerg   const llvm::Triple &TT = CGM.getTriple();
9857330f729Sjoerg   if (TT.isWindowsGNUEnvironment()) {
9867330f729Sjoerg     // In MinGW, variables without DLLImport can still be automatically
9877330f729Sjoerg     // imported from a DLL by the linker; don't mark variables that
9887330f729Sjoerg     // potentially could come from another DLL as DSO local.
9897330f729Sjoerg     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
9907330f729Sjoerg         !GV->isThreadLocal())
9917330f729Sjoerg       return false;
9927330f729Sjoerg   }
9937330f729Sjoerg 
9947330f729Sjoerg   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
9957330f729Sjoerg   // remain unresolved in the link, they can be resolved to zero, which is
9967330f729Sjoerg   // outside the current DSO.
9977330f729Sjoerg   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
9987330f729Sjoerg     return false;
9997330f729Sjoerg 
10007330f729Sjoerg   // Every other GV is local on COFF.
10017330f729Sjoerg   // Make an exception for windows OS in the triple: Some firmware builds use
10027330f729Sjoerg   // *-win32-macho triples. This (accidentally?) produced windows relocations
10037330f729Sjoerg   // without GOT tables in older clang versions; Keep this behaviour.
10047330f729Sjoerg   // FIXME: even thread local variables?
10057330f729Sjoerg   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
10067330f729Sjoerg     return true;
10077330f729Sjoerg 
10087330f729Sjoerg   // Only handle COFF and ELF for now.
10097330f729Sjoerg   if (!TT.isOSBinFormatELF())
10107330f729Sjoerg     return false;
10117330f729Sjoerg 
10127330f729Sjoerg   // If this is not an executable, don't assume anything is local.
10137330f729Sjoerg   const auto &CGOpts = CGM.getCodeGenOpts();
10147330f729Sjoerg   llvm::Reloc::Model RM = CGOpts.RelocationModel;
10157330f729Sjoerg   const auto &LOpts = CGM.getLangOpts();
1016*e038c9c4Sjoerg   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
1017*e038c9c4Sjoerg     // On ELF, if -fno-semantic-interposition is specified and the target
1018*e038c9c4Sjoerg     // supports local aliases, there will be neither CC1
1019*e038c9c4Sjoerg     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1020*e038c9c4Sjoerg     // dso_local on the function if using a local alias is preferable (can avoid
1021*e038c9c4Sjoerg     // PLT indirection).
1022*e038c9c4Sjoerg     if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias()))
10237330f729Sjoerg       return false;
1024*e038c9c4Sjoerg     return !(CGM.getLangOpts().SemanticInterposition ||
1025*e038c9c4Sjoerg              CGM.getLangOpts().HalfNoSemanticInterposition);
1026*e038c9c4Sjoerg   }
10277330f729Sjoerg 
10287330f729Sjoerg   // A definition cannot be preempted from an executable.
10297330f729Sjoerg   if (!GV->isDeclarationForLinker())
10307330f729Sjoerg     return true;
10317330f729Sjoerg 
10327330f729Sjoerg   // Most PIC code sequences that assume that a symbol is local cannot produce a
10337330f729Sjoerg   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
10347330f729Sjoerg   // depended, it seems worth it to handle it here.
10357330f729Sjoerg   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
10367330f729Sjoerg     return false;
10377330f729Sjoerg 
1038*e038c9c4Sjoerg   // PowerPC64 prefers TOC indirection to avoid copy relocations.
1039*e038c9c4Sjoerg   if (TT.isPPC64())
10407330f729Sjoerg     return false;
10417330f729Sjoerg 
1042*e038c9c4Sjoerg   if (CGOpts.DirectAccessExternalData) {
1043*e038c9c4Sjoerg     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1044*e038c9c4Sjoerg     // for non-thread-local variables. If the symbol is not defined in the
1045*e038c9c4Sjoerg     // executable, a copy relocation will be needed at link time. dso_local is
1046*e038c9c4Sjoerg     // excluded for thread-local variables because they generally don't support
1047*e038c9c4Sjoerg     // copy relocations.
10487330f729Sjoerg     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1049*e038c9c4Sjoerg       if (!Var->isThreadLocal())
10507330f729Sjoerg         return true;
10517330f729Sjoerg 
1052*e038c9c4Sjoerg     // -fno-pic sets dso_local on a function declaration to allow direct
1053*e038c9c4Sjoerg     // accesses when taking its address (similar to a data symbol). If the
1054*e038c9c4Sjoerg     // function is not defined in the executable, a canonical PLT entry will be
1055*e038c9c4Sjoerg     // needed at link time. -fno-direct-access-external-data can avoid the
1056*e038c9c4Sjoerg     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1057*e038c9c4Sjoerg     // it could just cause trouble without providing perceptible benefits.
10587330f729Sjoerg     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
10597330f729Sjoerg       return true;
1060*e038c9c4Sjoerg   }
10617330f729Sjoerg 
1062*e038c9c4Sjoerg   // If we can use copy relocations we can assume it is local.
1063*e038c9c4Sjoerg 
1064*e038c9c4Sjoerg   // Otherwise don't assume it is local.
10657330f729Sjoerg   return false;
10667330f729Sjoerg }
10677330f729Sjoerg 
setDSOLocal(llvm::GlobalValue * GV) const10687330f729Sjoerg void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
10697330f729Sjoerg   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
10707330f729Sjoerg }
10717330f729Sjoerg 
setDLLImportDLLExport(llvm::GlobalValue * GV,GlobalDecl GD) const10727330f729Sjoerg void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
10737330f729Sjoerg                                           GlobalDecl GD) const {
10747330f729Sjoerg   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
10757330f729Sjoerg   // C++ destructors have a few C++ ABI specific special cases.
10767330f729Sjoerg   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
10777330f729Sjoerg     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
10787330f729Sjoerg     return;
10797330f729Sjoerg   }
10807330f729Sjoerg   setDLLImportDLLExport(GV, D);
10817330f729Sjoerg }
10827330f729Sjoerg 
setDLLImportDLLExport(llvm::GlobalValue * GV,const NamedDecl * D) const10837330f729Sjoerg void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
10847330f729Sjoerg                                           const NamedDecl *D) const {
10857330f729Sjoerg   if (D && D->isExternallyVisible()) {
10867330f729Sjoerg     if (D->hasAttr<DLLImportAttr>())
10877330f729Sjoerg       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
10887330f729Sjoerg     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
10897330f729Sjoerg       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
10907330f729Sjoerg   }
10917330f729Sjoerg }
10927330f729Sjoerg 
setGVProperties(llvm::GlobalValue * GV,GlobalDecl GD) const10937330f729Sjoerg void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
10947330f729Sjoerg                                     GlobalDecl GD) const {
10957330f729Sjoerg   setDLLImportDLLExport(GV, GD);
10967330f729Sjoerg   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
10977330f729Sjoerg }
10987330f729Sjoerg 
setGVProperties(llvm::GlobalValue * GV,const NamedDecl * D) const10997330f729Sjoerg void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
11007330f729Sjoerg                                     const NamedDecl *D) const {
11017330f729Sjoerg   setDLLImportDLLExport(GV, D);
11027330f729Sjoerg   setGVPropertiesAux(GV, D);
11037330f729Sjoerg }
11047330f729Sjoerg 
setGVPropertiesAux(llvm::GlobalValue * GV,const NamedDecl * D) const11057330f729Sjoerg void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
11067330f729Sjoerg                                        const NamedDecl *D) const {
11077330f729Sjoerg   setGlobalVisibility(GV, D);
11087330f729Sjoerg   setDSOLocal(GV);
11097330f729Sjoerg   GV->setPartition(CodeGenOpts.SymbolPartition);
11107330f729Sjoerg }
11117330f729Sjoerg 
GetLLVMTLSModel(StringRef S)11127330f729Sjoerg static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
11137330f729Sjoerg   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
11147330f729Sjoerg       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
11157330f729Sjoerg       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
11167330f729Sjoerg       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
11177330f729Sjoerg       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
11187330f729Sjoerg }
11197330f729Sjoerg 
1120*e038c9c4Sjoerg llvm::GlobalVariable::ThreadLocalMode
GetDefaultLLVMTLSModel() const1121*e038c9c4Sjoerg CodeGenModule::GetDefaultLLVMTLSModel() const {
1122*e038c9c4Sjoerg   switch (CodeGenOpts.getDefaultTLSModel()) {
11237330f729Sjoerg   case CodeGenOptions::GeneralDynamicTLSModel:
11247330f729Sjoerg     return llvm::GlobalVariable::GeneralDynamicTLSModel;
11257330f729Sjoerg   case CodeGenOptions::LocalDynamicTLSModel:
11267330f729Sjoerg     return llvm::GlobalVariable::LocalDynamicTLSModel;
11277330f729Sjoerg   case CodeGenOptions::InitialExecTLSModel:
11287330f729Sjoerg     return llvm::GlobalVariable::InitialExecTLSModel;
11297330f729Sjoerg   case CodeGenOptions::LocalExecTLSModel:
11307330f729Sjoerg     return llvm::GlobalVariable::LocalExecTLSModel;
11317330f729Sjoerg   }
11327330f729Sjoerg   llvm_unreachable("Invalid TLS model!");
11337330f729Sjoerg }
11347330f729Sjoerg 
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const11357330f729Sjoerg void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
11367330f729Sjoerg   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
11377330f729Sjoerg 
11387330f729Sjoerg   llvm::GlobalValue::ThreadLocalMode TLM;
1139*e038c9c4Sjoerg   TLM = GetDefaultLLVMTLSModel();
11407330f729Sjoerg 
11417330f729Sjoerg   // Override the TLS model if it is explicitly specified.
11427330f729Sjoerg   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
11437330f729Sjoerg     TLM = GetLLVMTLSModel(Attr->getModel());
11447330f729Sjoerg   }
11457330f729Sjoerg 
11467330f729Sjoerg   GV->setThreadLocalMode(TLM);
11477330f729Sjoerg }
11487330f729Sjoerg 
getCPUSpecificMangling(const CodeGenModule & CGM,StringRef Name)11497330f729Sjoerg static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
11507330f729Sjoerg                                           StringRef Name) {
11517330f729Sjoerg   const TargetInfo &Target = CGM.getTarget();
11527330f729Sjoerg   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
11537330f729Sjoerg }
11547330f729Sjoerg 
AppendCPUSpecificCPUDispatchMangling(const CodeGenModule & CGM,const CPUSpecificAttr * Attr,unsigned CPUIndex,raw_ostream & Out)11557330f729Sjoerg static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
11567330f729Sjoerg                                                  const CPUSpecificAttr *Attr,
11577330f729Sjoerg                                                  unsigned CPUIndex,
11587330f729Sjoerg                                                  raw_ostream &Out) {
11597330f729Sjoerg   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
11607330f729Sjoerg   // supported.
11617330f729Sjoerg   if (Attr)
11627330f729Sjoerg     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
11637330f729Sjoerg   else if (CGM.getTarget().supportsIFunc())
11647330f729Sjoerg     Out << ".resolver";
11657330f729Sjoerg }
11667330f729Sjoerg 
AppendTargetMangling(const CodeGenModule & CGM,const TargetAttr * Attr,raw_ostream & Out)11677330f729Sjoerg static void AppendTargetMangling(const CodeGenModule &CGM,
11687330f729Sjoerg                                  const TargetAttr *Attr, raw_ostream &Out) {
11697330f729Sjoerg   if (Attr->isDefaultVersion())
11707330f729Sjoerg     return;
11717330f729Sjoerg 
11727330f729Sjoerg   Out << '.';
11737330f729Sjoerg   const TargetInfo &Target = CGM.getTarget();
1174*e038c9c4Sjoerg   ParsedTargetAttr Info =
11757330f729Sjoerg       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
11767330f729Sjoerg         // Multiversioning doesn't allow "no-${feature}", so we can
11777330f729Sjoerg         // only have "+" prefixes here.
11787330f729Sjoerg         assert(LHS.startswith("+") && RHS.startswith("+") &&
11797330f729Sjoerg                "Features should always have a prefix.");
11807330f729Sjoerg         return Target.multiVersionSortPriority(LHS.substr(1)) >
11817330f729Sjoerg                Target.multiVersionSortPriority(RHS.substr(1));
11827330f729Sjoerg       });
11837330f729Sjoerg 
11847330f729Sjoerg   bool IsFirst = true;
11857330f729Sjoerg 
11867330f729Sjoerg   if (!Info.Architecture.empty()) {
11877330f729Sjoerg     IsFirst = false;
11887330f729Sjoerg     Out << "arch_" << Info.Architecture;
11897330f729Sjoerg   }
11907330f729Sjoerg 
11917330f729Sjoerg   for (StringRef Feat : Info.Features) {
11927330f729Sjoerg     if (!IsFirst)
11937330f729Sjoerg       Out << '_';
11947330f729Sjoerg     IsFirst = false;
11957330f729Sjoerg     Out << Feat.substr(1);
11967330f729Sjoerg   }
11977330f729Sjoerg }
11987330f729Sjoerg 
1199*e038c9c4Sjoerg // Returns true if GD is a function decl with internal linkage and
1200*e038c9c4Sjoerg // needs a unique suffix after the mangled name.
isUniqueInternalLinkageDecl(GlobalDecl GD,CodeGenModule & CGM)1201*e038c9c4Sjoerg static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1202*e038c9c4Sjoerg                                         CodeGenModule &CGM) {
1203*e038c9c4Sjoerg   const Decl *D = GD.getDecl();
1204*e038c9c4Sjoerg   return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) &&
1205*e038c9c4Sjoerg          (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage);
1206*e038c9c4Sjoerg }
1207*e038c9c4Sjoerg 
getMangledNameImpl(CodeGenModule & CGM,GlobalDecl GD,const NamedDecl * ND,bool OmitMultiVersionMangling=false)1208*e038c9c4Sjoerg static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
12097330f729Sjoerg                                       const NamedDecl *ND,
12107330f729Sjoerg                                       bool OmitMultiVersionMangling = false) {
12117330f729Sjoerg   SmallString<256> Buffer;
12127330f729Sjoerg   llvm::raw_svector_ostream Out(Buffer);
12137330f729Sjoerg   MangleContext &MC = CGM.getCXXABI().getMangleContext();
1214*e038c9c4Sjoerg   if (!CGM.getModuleNameHash().empty())
1215*e038c9c4Sjoerg     MC.needsUniqueInternalLinkageNames();
1216*e038c9c4Sjoerg   bool ShouldMangle = MC.shouldMangleDeclName(ND);
1217*e038c9c4Sjoerg   if (ShouldMangle)
1218*e038c9c4Sjoerg     MC.mangleName(GD.getWithDecl(ND), Out);
1219*e038c9c4Sjoerg   else {
12207330f729Sjoerg     IdentifierInfo *II = ND->getIdentifier();
12217330f729Sjoerg     assert(II && "Attempt to mangle unnamed decl.");
12227330f729Sjoerg     const auto *FD = dyn_cast<FunctionDecl>(ND);
12237330f729Sjoerg 
12247330f729Sjoerg     if (FD &&
12257330f729Sjoerg         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
12267330f729Sjoerg       Out << "__regcall3__" << II->getName();
1227*e038c9c4Sjoerg     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1228*e038c9c4Sjoerg                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1229*e038c9c4Sjoerg       Out << "__device_stub__" << II->getName();
12307330f729Sjoerg     } else {
12317330f729Sjoerg       Out << II->getName();
12327330f729Sjoerg     }
12337330f729Sjoerg   }
12347330f729Sjoerg 
1235*e038c9c4Sjoerg   // Check if the module name hash should be appended for internal linkage
1236*e038c9c4Sjoerg   // symbols.   This should come before multi-version target suffixes are
1237*e038c9c4Sjoerg   // appended. This is to keep the name and module hash suffix of the
1238*e038c9c4Sjoerg   // internal linkage function together.  The unique suffix should only be
1239*e038c9c4Sjoerg   // added when name mangling is done to make sure that the final name can
1240*e038c9c4Sjoerg   // be properly demangled.  For example, for C functions without prototypes,
1241*e038c9c4Sjoerg   // name mangling is not done and the unique suffix should not be appeneded
1242*e038c9c4Sjoerg   // then.
1243*e038c9c4Sjoerg   if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) {
1244*e038c9c4Sjoerg     assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1245*e038c9c4Sjoerg            "Hash computed when not explicitly requested");
1246*e038c9c4Sjoerg     Out << CGM.getModuleNameHash();
1247*e038c9c4Sjoerg   }
1248*e038c9c4Sjoerg 
12497330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
12507330f729Sjoerg     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
12517330f729Sjoerg       switch (FD->getMultiVersionKind()) {
12527330f729Sjoerg       case MultiVersionKind::CPUDispatch:
12537330f729Sjoerg       case MultiVersionKind::CPUSpecific:
12547330f729Sjoerg         AppendCPUSpecificCPUDispatchMangling(CGM,
12557330f729Sjoerg                                              FD->getAttr<CPUSpecificAttr>(),
12567330f729Sjoerg                                              GD.getMultiVersionIndex(), Out);
12577330f729Sjoerg         break;
12587330f729Sjoerg       case MultiVersionKind::Target:
12597330f729Sjoerg         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
12607330f729Sjoerg         break;
12617330f729Sjoerg       case MultiVersionKind::None:
12627330f729Sjoerg         llvm_unreachable("None multiversion type isn't valid here");
12637330f729Sjoerg       }
12647330f729Sjoerg     }
12657330f729Sjoerg 
1266*e038c9c4Sjoerg   // Make unique name for device side static file-scope variable for HIP.
1267*e038c9c4Sjoerg   if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
1268*e038c9c4Sjoerg       CGM.getLangOpts().GPURelocatableDeviceCode &&
1269*e038c9c4Sjoerg       CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty())
1270*e038c9c4Sjoerg     CGM.printPostfixForExternalizedStaticVar(Out);
1271*e038c9c4Sjoerg   return std::string(Out.str());
12727330f729Sjoerg }
12737330f729Sjoerg 
UpdateMultiVersionNames(GlobalDecl GD,const FunctionDecl * FD)12747330f729Sjoerg void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
12757330f729Sjoerg                                             const FunctionDecl *FD) {
12767330f729Sjoerg   if (!FD->isMultiVersion())
12777330f729Sjoerg     return;
12787330f729Sjoerg 
12797330f729Sjoerg   // Get the name of what this would be without the 'target' attribute.  This
12807330f729Sjoerg   // allows us to lookup the version that was emitted when this wasn't a
12817330f729Sjoerg   // multiversion function.
12827330f729Sjoerg   std::string NonTargetName =
12837330f729Sjoerg       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
12847330f729Sjoerg   GlobalDecl OtherGD;
12857330f729Sjoerg   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
12867330f729Sjoerg     assert(OtherGD.getCanonicalDecl()
12877330f729Sjoerg                .getDecl()
12887330f729Sjoerg                ->getAsFunction()
12897330f729Sjoerg                ->isMultiVersion() &&
12907330f729Sjoerg            "Other GD should now be a multiversioned function");
12917330f729Sjoerg     // OtherFD is the version of this function that was mangled BEFORE
12927330f729Sjoerg     // becoming a MultiVersion function.  It potentially needs to be updated.
12937330f729Sjoerg     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
12947330f729Sjoerg                                       .getDecl()
12957330f729Sjoerg                                       ->getAsFunction()
12967330f729Sjoerg                                       ->getMostRecentDecl();
12977330f729Sjoerg     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
12987330f729Sjoerg     // This is so that if the initial version was already the 'default'
12997330f729Sjoerg     // version, we don't try to update it.
13007330f729Sjoerg     if (OtherName != NonTargetName) {
13017330f729Sjoerg       // Remove instead of erase, since others may have stored the StringRef
13027330f729Sjoerg       // to this.
13037330f729Sjoerg       const auto ExistingRecord = Manglings.find(NonTargetName);
13047330f729Sjoerg       if (ExistingRecord != std::end(Manglings))
13057330f729Sjoerg         Manglings.remove(&(*ExistingRecord));
13067330f729Sjoerg       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
13077330f729Sjoerg       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
13087330f729Sjoerg       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
13097330f729Sjoerg         Entry->setName(OtherName);
13107330f729Sjoerg     }
13117330f729Sjoerg   }
13127330f729Sjoerg }
13137330f729Sjoerg 
getMangledName(GlobalDecl GD)13147330f729Sjoerg StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
13157330f729Sjoerg   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
13167330f729Sjoerg 
13177330f729Sjoerg   // Some ABIs don't have constructor variants.  Make sure that base and
13187330f729Sjoerg   // complete constructors get mangled the same.
13197330f729Sjoerg   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
13207330f729Sjoerg     if (!getTarget().getCXXABI().hasConstructorVariants()) {
13217330f729Sjoerg       CXXCtorType OrigCtorType = GD.getCtorType();
13227330f729Sjoerg       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
13237330f729Sjoerg       if (OrigCtorType == Ctor_Base)
13247330f729Sjoerg         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
13257330f729Sjoerg     }
13267330f729Sjoerg   }
13277330f729Sjoerg 
1328*e038c9c4Sjoerg   // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1329*e038c9c4Sjoerg   // static device variable depends on whether the variable is referenced by
1330*e038c9c4Sjoerg   // a host or device host function. Therefore the mangled name cannot be
1331*e038c9c4Sjoerg   // cached.
1332*e038c9c4Sjoerg   if (!LangOpts.CUDAIsDevice ||
1333*e038c9c4Sjoerg       !getContext().mayExternalizeStaticVar(GD.getDecl())) {
13347330f729Sjoerg     auto FoundName = MangledDeclNames.find(CanonicalGD);
13357330f729Sjoerg     if (FoundName != MangledDeclNames.end())
13367330f729Sjoerg       return FoundName->second;
1337*e038c9c4Sjoerg   }
13387330f729Sjoerg 
13397330f729Sjoerg   // Keep the first result in the case of a mangling collision.
13407330f729Sjoerg   const auto *ND = cast<NamedDecl>(GD.getDecl());
13417330f729Sjoerg   std::string MangledName = getMangledNameImpl(*this, GD, ND);
13427330f729Sjoerg 
1343*e038c9c4Sjoerg   // Ensure either we have different ABIs between host and device compilations,
1344*e038c9c4Sjoerg   // says host compilation following MSVC ABI but device compilation follows
1345*e038c9c4Sjoerg   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1346*e038c9c4Sjoerg   // mangling should be the same after name stubbing. The later checking is
1347*e038c9c4Sjoerg   // very important as the device kernel name being mangled in host-compilation
1348*e038c9c4Sjoerg   // is used to resolve the device binaries to be executed. Inconsistent naming
1349*e038c9c4Sjoerg   // result in undefined behavior. Even though we cannot check that naming
1350*e038c9c4Sjoerg   // directly between host- and device-compilations, the host- and
1351*e038c9c4Sjoerg   // device-mangling in host compilation could help catching certain ones.
1352*e038c9c4Sjoerg   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1353*e038c9c4Sjoerg          getLangOpts().CUDAIsDevice ||
1354*e038c9c4Sjoerg          (getContext().getAuxTargetInfo() &&
1355*e038c9c4Sjoerg           (getContext().getAuxTargetInfo()->getCXXABI() !=
1356*e038c9c4Sjoerg            getContext().getTargetInfo().getCXXABI())) ||
1357*e038c9c4Sjoerg          getCUDARuntime().getDeviceSideName(ND) ==
1358*e038c9c4Sjoerg              getMangledNameImpl(
1359*e038c9c4Sjoerg                  *this,
1360*e038c9c4Sjoerg                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1361*e038c9c4Sjoerg                  ND));
13627330f729Sjoerg 
13637330f729Sjoerg   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
13647330f729Sjoerg   return MangledDeclNames[CanonicalGD] = Result.first->first();
13657330f729Sjoerg }
13667330f729Sjoerg 
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)13677330f729Sjoerg StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
13687330f729Sjoerg                                              const BlockDecl *BD) {
13697330f729Sjoerg   MangleContext &MangleCtx = getCXXABI().getMangleContext();
13707330f729Sjoerg   const Decl *D = GD.getDecl();
13717330f729Sjoerg 
13727330f729Sjoerg   SmallString<256> Buffer;
13737330f729Sjoerg   llvm::raw_svector_ostream Out(Buffer);
13747330f729Sjoerg   if (!D)
13757330f729Sjoerg     MangleCtx.mangleGlobalBlock(BD,
13767330f729Sjoerg       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
13777330f729Sjoerg   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
13787330f729Sjoerg     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
13797330f729Sjoerg   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
13807330f729Sjoerg     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
13817330f729Sjoerg   else
13827330f729Sjoerg     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
13837330f729Sjoerg 
13847330f729Sjoerg   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
13857330f729Sjoerg   return Result.first->first();
13867330f729Sjoerg }
13877330f729Sjoerg 
GetGlobalValue(StringRef Name)13887330f729Sjoerg llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
13897330f729Sjoerg   return getModule().getNamedValue(Name);
13907330f729Sjoerg }
13917330f729Sjoerg 
13927330f729Sjoerg /// AddGlobalCtor - Add a function to the list that will be called before
13937330f729Sjoerg /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,llvm::Constant * AssociatedData)13947330f729Sjoerg void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
13957330f729Sjoerg                                   llvm::Constant *AssociatedData) {
13967330f729Sjoerg   // FIXME: Type coercion of void()* types.
13977330f729Sjoerg   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
13987330f729Sjoerg }
13997330f729Sjoerg 
14007330f729Sjoerg /// AddGlobalDtor - Add a function to the list that will be called
14017330f729Sjoerg /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority,bool IsDtorAttrFunc)1402*e038c9c4Sjoerg void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1403*e038c9c4Sjoerg                                   bool IsDtorAttrFunc) {
1404*e038c9c4Sjoerg   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1405*e038c9c4Sjoerg       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
14067330f729Sjoerg     DtorsUsingAtExit[Priority].push_back(Dtor);
14077330f729Sjoerg     return;
14087330f729Sjoerg   }
14097330f729Sjoerg 
14107330f729Sjoerg   // FIXME: Type coercion of void()* types.
14117330f729Sjoerg   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
14127330f729Sjoerg }
14137330f729Sjoerg 
EmitCtorList(CtorList & Fns,const char * GlobalName)14147330f729Sjoerg void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
14157330f729Sjoerg   if (Fns.empty()) return;
14167330f729Sjoerg 
14177330f729Sjoerg   // Ctor function type is void()*.
14187330f729Sjoerg   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
14197330f729Sjoerg   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
14207330f729Sjoerg       TheModule.getDataLayout().getProgramAddressSpace());
14217330f729Sjoerg 
14227330f729Sjoerg   // Get the type of a ctor entry, { i32, void ()*, i8* }.
14237330f729Sjoerg   llvm::StructType *CtorStructTy = llvm::StructType::get(
14247330f729Sjoerg       Int32Ty, CtorPFTy, VoidPtrTy);
14257330f729Sjoerg 
14267330f729Sjoerg   // Construct the constructor and destructor arrays.
14277330f729Sjoerg   ConstantInitBuilder builder(*this);
14287330f729Sjoerg   auto ctors = builder.beginArray(CtorStructTy);
14297330f729Sjoerg   for (const auto &I : Fns) {
14307330f729Sjoerg     auto ctor = ctors.beginStruct(CtorStructTy);
14317330f729Sjoerg     ctor.addInt(Int32Ty, I.Priority);
14327330f729Sjoerg     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
14337330f729Sjoerg     if (I.AssociatedData)
14347330f729Sjoerg       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
14357330f729Sjoerg     else
14367330f729Sjoerg       ctor.addNullPointer(VoidPtrTy);
14377330f729Sjoerg     ctor.finishAndAddTo(ctors);
14387330f729Sjoerg   }
14397330f729Sjoerg 
14407330f729Sjoerg   auto list =
14417330f729Sjoerg     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
14427330f729Sjoerg                                 /*constant*/ false,
14437330f729Sjoerg                                 llvm::GlobalValue::AppendingLinkage);
14447330f729Sjoerg 
14457330f729Sjoerg   // The LTO linker doesn't seem to like it when we set an alignment
14467330f729Sjoerg   // on appending variables.  Take it off as a workaround.
14477330f729Sjoerg   list->setAlignment(llvm::None);
14487330f729Sjoerg 
14497330f729Sjoerg   Fns.clear();
14507330f729Sjoerg }
14517330f729Sjoerg 
14527330f729Sjoerg llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)14537330f729Sjoerg CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
14547330f729Sjoerg   const auto *D = cast<FunctionDecl>(GD.getDecl());
14557330f729Sjoerg 
14567330f729Sjoerg   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
14577330f729Sjoerg 
14587330f729Sjoerg   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
14597330f729Sjoerg     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
14607330f729Sjoerg 
14617330f729Sjoerg   if (isa<CXXConstructorDecl>(D) &&
14627330f729Sjoerg       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
14637330f729Sjoerg       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14647330f729Sjoerg     // Our approach to inheriting constructors is fundamentally different from
14657330f729Sjoerg     // that used by the MS ABI, so keep our inheriting constructor thunks
14667330f729Sjoerg     // internal rather than trying to pick an unambiguous mangling for them.
14677330f729Sjoerg     return llvm::GlobalValue::InternalLinkage;
14687330f729Sjoerg   }
14697330f729Sjoerg 
14707330f729Sjoerg   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
14717330f729Sjoerg }
14727330f729Sjoerg 
CreateCrossDsoCfiTypeId(llvm::Metadata * MD)14737330f729Sjoerg llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
14747330f729Sjoerg   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
14757330f729Sjoerg   if (!MDS) return nullptr;
14767330f729Sjoerg 
14777330f729Sjoerg   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
14787330f729Sjoerg }
14797330f729Sjoerg 
SetLLVMFunctionAttributes(GlobalDecl GD,const CGFunctionInfo & Info,llvm::Function * F,bool IsThunk)14807330f729Sjoerg void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
14817330f729Sjoerg                                               const CGFunctionInfo &Info,
1482*e038c9c4Sjoerg                                               llvm::Function *F, bool IsThunk) {
14837330f729Sjoerg   unsigned CallingConv;
14847330f729Sjoerg   llvm::AttributeList PAL;
1485*e038c9c4Sjoerg   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
1486*e038c9c4Sjoerg                          /*AttrOnCallSite=*/false, IsThunk);
14877330f729Sjoerg   F->setAttributes(PAL);
14887330f729Sjoerg   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
14897330f729Sjoerg }
14907330f729Sjoerg 
removeImageAccessQualifier(std::string & TyName)14917330f729Sjoerg static void removeImageAccessQualifier(std::string& TyName) {
14927330f729Sjoerg   std::string ReadOnlyQual("__read_only");
14937330f729Sjoerg   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
14947330f729Sjoerg   if (ReadOnlyPos != std::string::npos)
14957330f729Sjoerg     // "+ 1" for the space after access qualifier.
14967330f729Sjoerg     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
14977330f729Sjoerg   else {
14987330f729Sjoerg     std::string WriteOnlyQual("__write_only");
14997330f729Sjoerg     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
15007330f729Sjoerg     if (WriteOnlyPos != std::string::npos)
15017330f729Sjoerg       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
15027330f729Sjoerg     else {
15037330f729Sjoerg       std::string ReadWriteQual("__read_write");
15047330f729Sjoerg       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
15057330f729Sjoerg       if (ReadWritePos != std::string::npos)
15067330f729Sjoerg         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
15077330f729Sjoerg     }
15087330f729Sjoerg   }
15097330f729Sjoerg }
15107330f729Sjoerg 
15117330f729Sjoerg // Returns the address space id that should be produced to the
15127330f729Sjoerg // kernel_arg_addr_space metadata. This is always fixed to the ids
15137330f729Sjoerg // as specified in the SPIR 2.0 specification in order to differentiate
15147330f729Sjoerg // for example in clGetKernelArgInfo() implementation between the address
15157330f729Sjoerg // spaces with targets without unique mapping to the OpenCL address spaces
15167330f729Sjoerg // (basically all single AS CPUs).
ArgInfoAddressSpace(LangAS AS)15177330f729Sjoerg static unsigned ArgInfoAddressSpace(LangAS AS) {
15187330f729Sjoerg   switch (AS) {
1519*e038c9c4Sjoerg   case LangAS::opencl_global:
1520*e038c9c4Sjoerg     return 1;
1521*e038c9c4Sjoerg   case LangAS::opencl_constant:
1522*e038c9c4Sjoerg     return 2;
1523*e038c9c4Sjoerg   case LangAS::opencl_local:
1524*e038c9c4Sjoerg     return 3;
1525*e038c9c4Sjoerg   case LangAS::opencl_generic:
1526*e038c9c4Sjoerg     return 4; // Not in SPIR 2.0 specs.
1527*e038c9c4Sjoerg   case LangAS::opencl_global_device:
1528*e038c9c4Sjoerg     return 5;
1529*e038c9c4Sjoerg   case LangAS::opencl_global_host:
1530*e038c9c4Sjoerg     return 6;
15317330f729Sjoerg   default:
15327330f729Sjoerg     return 0; // Assume private.
15337330f729Sjoerg   }
15347330f729Sjoerg }
15357330f729Sjoerg 
GenOpenCLArgMetadata(llvm::Function * Fn,const FunctionDecl * FD,CodeGenFunction * CGF)15367330f729Sjoerg void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
15377330f729Sjoerg                                          const FunctionDecl *FD,
15387330f729Sjoerg                                          CodeGenFunction *CGF) {
15397330f729Sjoerg   assert(((FD && CGF) || (!FD && !CGF)) &&
15407330f729Sjoerg          "Incorrect use - FD and CGF should either be both null or not!");
15417330f729Sjoerg   // Create MDNodes that represent the kernel arg metadata.
15427330f729Sjoerg   // Each MDNode is a list in the form of "key", N number of values which is
15437330f729Sjoerg   // the same number of values as their are kernel arguments.
15447330f729Sjoerg 
15457330f729Sjoerg   const PrintingPolicy &Policy = Context.getPrintingPolicy();
15467330f729Sjoerg 
15477330f729Sjoerg   // MDNode for the kernel argument address space qualifiers.
15487330f729Sjoerg   SmallVector<llvm::Metadata *, 8> addressQuals;
15497330f729Sjoerg 
15507330f729Sjoerg   // MDNode for the kernel argument access qualifiers (images only).
15517330f729Sjoerg   SmallVector<llvm::Metadata *, 8> accessQuals;
15527330f729Sjoerg 
15537330f729Sjoerg   // MDNode for the kernel argument type names.
15547330f729Sjoerg   SmallVector<llvm::Metadata *, 8> argTypeNames;
15557330f729Sjoerg 
15567330f729Sjoerg   // MDNode for the kernel argument base type names.
15577330f729Sjoerg   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
15587330f729Sjoerg 
15597330f729Sjoerg   // MDNode for the kernel argument type qualifiers.
15607330f729Sjoerg   SmallVector<llvm::Metadata *, 8> argTypeQuals;
15617330f729Sjoerg 
15627330f729Sjoerg   // MDNode for the kernel argument names.
15637330f729Sjoerg   SmallVector<llvm::Metadata *, 8> argNames;
15647330f729Sjoerg 
15657330f729Sjoerg   if (FD && CGF)
15667330f729Sjoerg     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
15677330f729Sjoerg       const ParmVarDecl *parm = FD->getParamDecl(i);
15687330f729Sjoerg       QualType ty = parm->getType();
15697330f729Sjoerg       std::string typeQuals;
15707330f729Sjoerg 
1571*e038c9c4Sjoerg       // Get image and pipe access qualifier:
1572*e038c9c4Sjoerg       if (ty->isImageType() || ty->isPipeType()) {
1573*e038c9c4Sjoerg         const Decl *PDecl = parm;
1574*e038c9c4Sjoerg         if (auto *TD = dyn_cast<TypedefType>(ty))
1575*e038c9c4Sjoerg           PDecl = TD->getDecl();
1576*e038c9c4Sjoerg         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1577*e038c9c4Sjoerg         if (A && A->isWriteOnly())
1578*e038c9c4Sjoerg           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1579*e038c9c4Sjoerg         else if (A && A->isReadWrite())
1580*e038c9c4Sjoerg           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1581*e038c9c4Sjoerg         else
1582*e038c9c4Sjoerg           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1583*e038c9c4Sjoerg       } else
1584*e038c9c4Sjoerg         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1585*e038c9c4Sjoerg 
1586*e038c9c4Sjoerg       // Get argument name.
1587*e038c9c4Sjoerg       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1588*e038c9c4Sjoerg 
1589*e038c9c4Sjoerg       auto getTypeSpelling = [&](QualType Ty) {
1590*e038c9c4Sjoerg         auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
1591*e038c9c4Sjoerg 
1592*e038c9c4Sjoerg         if (Ty.isCanonical()) {
1593*e038c9c4Sjoerg           StringRef typeNameRef = typeName;
1594*e038c9c4Sjoerg           // Turn "unsigned type" to "utype"
1595*e038c9c4Sjoerg           if (typeNameRef.consume_front("unsigned "))
1596*e038c9c4Sjoerg             return std::string("u") + typeNameRef.str();
1597*e038c9c4Sjoerg           if (typeNameRef.consume_front("signed "))
1598*e038c9c4Sjoerg             return typeNameRef.str();
1599*e038c9c4Sjoerg         }
1600*e038c9c4Sjoerg 
1601*e038c9c4Sjoerg         return typeName;
1602*e038c9c4Sjoerg       };
1603*e038c9c4Sjoerg 
16047330f729Sjoerg       if (ty->isPointerType()) {
16057330f729Sjoerg         QualType pointeeTy = ty->getPointeeType();
16067330f729Sjoerg 
16077330f729Sjoerg         // Get address qualifier.
16087330f729Sjoerg         addressQuals.push_back(
16097330f729Sjoerg             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
16107330f729Sjoerg                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
16117330f729Sjoerg 
16127330f729Sjoerg         // Get argument type name.
1613*e038c9c4Sjoerg         std::string typeName = getTypeSpelling(pointeeTy) + "*";
16147330f729Sjoerg         std::string baseTypeName =
1615*e038c9c4Sjoerg             getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
1616*e038c9c4Sjoerg         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
16177330f729Sjoerg         argBaseTypeNames.push_back(
16187330f729Sjoerg             llvm::MDString::get(VMContext, baseTypeName));
16197330f729Sjoerg 
16207330f729Sjoerg         // Get argument type qualifiers:
16217330f729Sjoerg         if (ty.isRestrictQualified())
16227330f729Sjoerg           typeQuals = "restrict";
16237330f729Sjoerg         if (pointeeTy.isConstQualified() ||
16247330f729Sjoerg             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
16257330f729Sjoerg           typeQuals += typeQuals.empty() ? "const" : " const";
16267330f729Sjoerg         if (pointeeTy.isVolatileQualified())
16277330f729Sjoerg           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
16287330f729Sjoerg       } else {
16297330f729Sjoerg         uint32_t AddrSpc = 0;
16307330f729Sjoerg         bool isPipe = ty->isPipeType();
16317330f729Sjoerg         if (ty->isImageType() || isPipe)
16327330f729Sjoerg           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
16337330f729Sjoerg 
16347330f729Sjoerg         addressQuals.push_back(
16357330f729Sjoerg             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
16367330f729Sjoerg 
16377330f729Sjoerg         // Get argument type name.
1638*e038c9c4Sjoerg         ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty;
1639*e038c9c4Sjoerg         std::string typeName = getTypeSpelling(ty);
1640*e038c9c4Sjoerg         std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
16417330f729Sjoerg 
16427330f729Sjoerg         // Remove access qualifiers on images
16437330f729Sjoerg         // (as they are inseparable from type in clang implementation,
16447330f729Sjoerg         // but OpenCL spec provides a special query to get access qualifier
16457330f729Sjoerg         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
16467330f729Sjoerg         if (ty->isImageType()) {
16477330f729Sjoerg           removeImageAccessQualifier(typeName);
16487330f729Sjoerg           removeImageAccessQualifier(baseTypeName);
16497330f729Sjoerg         }
16507330f729Sjoerg 
16517330f729Sjoerg         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
16527330f729Sjoerg         argBaseTypeNames.push_back(
16537330f729Sjoerg             llvm::MDString::get(VMContext, baseTypeName));
16547330f729Sjoerg 
16557330f729Sjoerg         if (isPipe)
16567330f729Sjoerg           typeQuals = "pipe";
16577330f729Sjoerg       }
16587330f729Sjoerg       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
16597330f729Sjoerg     }
16607330f729Sjoerg 
16617330f729Sjoerg   Fn->setMetadata("kernel_arg_addr_space",
16627330f729Sjoerg                   llvm::MDNode::get(VMContext, addressQuals));
16637330f729Sjoerg   Fn->setMetadata("kernel_arg_access_qual",
16647330f729Sjoerg                   llvm::MDNode::get(VMContext, accessQuals));
16657330f729Sjoerg   Fn->setMetadata("kernel_arg_type",
16667330f729Sjoerg                   llvm::MDNode::get(VMContext, argTypeNames));
16677330f729Sjoerg   Fn->setMetadata("kernel_arg_base_type",
16687330f729Sjoerg                   llvm::MDNode::get(VMContext, argBaseTypeNames));
16697330f729Sjoerg   Fn->setMetadata("kernel_arg_type_qual",
16707330f729Sjoerg                   llvm::MDNode::get(VMContext, argTypeQuals));
16717330f729Sjoerg   if (getCodeGenOpts().EmitOpenCLArgMetadata)
16727330f729Sjoerg     Fn->setMetadata("kernel_arg_name",
16737330f729Sjoerg                     llvm::MDNode::get(VMContext, argNames));
16747330f729Sjoerg }
16757330f729Sjoerg 
16767330f729Sjoerg /// Determines whether the language options require us to model
16777330f729Sjoerg /// unwind exceptions.  We treat -fexceptions as mandating this
16787330f729Sjoerg /// except under the fragile ObjC ABI with only ObjC exceptions
16797330f729Sjoerg /// enabled.  This means, for example, that C with -fexceptions
16807330f729Sjoerg /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)16817330f729Sjoerg static bool hasUnwindExceptions(const LangOptions &LangOpts) {
16827330f729Sjoerg   // If exceptions are completely disabled, obviously this is false.
16837330f729Sjoerg   if (!LangOpts.Exceptions) return false;
16847330f729Sjoerg 
16857330f729Sjoerg   // If C++ exceptions are enabled, this is true.
16867330f729Sjoerg   if (LangOpts.CXXExceptions) return true;
16877330f729Sjoerg 
16887330f729Sjoerg   // If ObjC exceptions are enabled, this depends on the ABI.
16897330f729Sjoerg   if (LangOpts.ObjCExceptions) {
16907330f729Sjoerg     return LangOpts.ObjCRuntime.hasUnwindExceptions();
16917330f729Sjoerg   }
16927330f729Sjoerg 
16937330f729Sjoerg   return true;
16947330f729Sjoerg }
16957330f729Sjoerg 
requiresMemberFunctionPointerTypeMetadata(CodeGenModule & CGM,const CXXMethodDecl * MD)16967330f729Sjoerg static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
16977330f729Sjoerg                                                       const CXXMethodDecl *MD) {
16987330f729Sjoerg   // Check that the type metadata can ever actually be used by a call.
16997330f729Sjoerg   if (!CGM.getCodeGenOpts().LTOUnit ||
17007330f729Sjoerg       !CGM.HasHiddenLTOVisibility(MD->getParent()))
17017330f729Sjoerg     return false;
17027330f729Sjoerg 
17037330f729Sjoerg   // Only functions whose address can be taken with a member function pointer
17047330f729Sjoerg   // need this sort of type metadata.
17057330f729Sjoerg   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
17067330f729Sjoerg          !isa<CXXDestructorDecl>(MD);
17077330f729Sjoerg }
17087330f729Sjoerg 
17097330f729Sjoerg std::vector<const CXXRecordDecl *>
getMostBaseClasses(const CXXRecordDecl * RD)17107330f729Sjoerg CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
17117330f729Sjoerg   llvm::SetVector<const CXXRecordDecl *> MostBases;
17127330f729Sjoerg 
17137330f729Sjoerg   std::function<void (const CXXRecordDecl *)> CollectMostBases;
17147330f729Sjoerg   CollectMostBases = [&](const CXXRecordDecl *RD) {
17157330f729Sjoerg     if (RD->getNumBases() == 0)
17167330f729Sjoerg       MostBases.insert(RD);
17177330f729Sjoerg     for (const CXXBaseSpecifier &B : RD->bases())
17187330f729Sjoerg       CollectMostBases(B.getType()->getAsCXXRecordDecl());
17197330f729Sjoerg   };
17207330f729Sjoerg   CollectMostBases(RD);
17217330f729Sjoerg   return MostBases.takeVector();
17227330f729Sjoerg }
17237330f729Sjoerg 
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)17247330f729Sjoerg void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
17257330f729Sjoerg                                                            llvm::Function *F) {
17267330f729Sjoerg   llvm::AttrBuilder B;
17277330f729Sjoerg 
17287330f729Sjoerg   if (CodeGenOpts.UnwindTables)
17297330f729Sjoerg     B.addAttribute(llvm::Attribute::UWTable);
17307330f729Sjoerg 
1731*e038c9c4Sjoerg   if (CodeGenOpts.StackClashProtector)
1732*e038c9c4Sjoerg     B.addAttribute("probe-stack", "inline-asm");
1733*e038c9c4Sjoerg 
17347330f729Sjoerg   if (!hasUnwindExceptions(LangOpts))
17357330f729Sjoerg     B.addAttribute(llvm::Attribute::NoUnwind);
17367330f729Sjoerg 
17377330f729Sjoerg   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
17387330f729Sjoerg     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
17397330f729Sjoerg       B.addAttribute(llvm::Attribute::StackProtect);
17407330f729Sjoerg     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
17417330f729Sjoerg       B.addAttribute(llvm::Attribute::StackProtectStrong);
17427330f729Sjoerg     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
17437330f729Sjoerg       B.addAttribute(llvm::Attribute::StackProtectReq);
17447330f729Sjoerg   }
17457330f729Sjoerg 
17467330f729Sjoerg   if (!D) {
17477330f729Sjoerg     // If we don't have a declaration to control inlining, the function isn't
17487330f729Sjoerg     // explicitly marked as alwaysinline for semantic reasons, and inlining is
17497330f729Sjoerg     // disabled, mark the function as noinline.
17507330f729Sjoerg     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
17517330f729Sjoerg         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
17527330f729Sjoerg       B.addAttribute(llvm::Attribute::NoInline);
17537330f729Sjoerg 
17547330f729Sjoerg     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
17557330f729Sjoerg     return;
17567330f729Sjoerg   }
17577330f729Sjoerg 
17587330f729Sjoerg   // Track whether we need to add the optnone LLVM attribute,
17597330f729Sjoerg   // starting with the default for this optimization level.
17607330f729Sjoerg   bool ShouldAddOptNone =
17617330f729Sjoerg       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
17627330f729Sjoerg   // We can't add optnone in the following cases, it won't pass the verifier.
17637330f729Sjoerg   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
17647330f729Sjoerg   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
17657330f729Sjoerg 
1766*e038c9c4Sjoerg   // Add optnone, but do so only if the function isn't always_inline.
1767*e038c9c4Sjoerg   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1768*e038c9c4Sjoerg       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
17697330f729Sjoerg     B.addAttribute(llvm::Attribute::OptimizeNone);
17707330f729Sjoerg 
17717330f729Sjoerg     // OptimizeNone implies noinline; we should not be inlining such functions.
17727330f729Sjoerg     B.addAttribute(llvm::Attribute::NoInline);
17737330f729Sjoerg 
17747330f729Sjoerg     // We still need to handle naked functions even though optnone subsumes
17757330f729Sjoerg     // much of their semantics.
17767330f729Sjoerg     if (D->hasAttr<NakedAttr>())
17777330f729Sjoerg       B.addAttribute(llvm::Attribute::Naked);
17787330f729Sjoerg 
17797330f729Sjoerg     // OptimizeNone wins over OptimizeForSize and MinSize.
17807330f729Sjoerg     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
17817330f729Sjoerg     F->removeFnAttr(llvm::Attribute::MinSize);
17827330f729Sjoerg   } else if (D->hasAttr<NakedAttr>()) {
17837330f729Sjoerg     // Naked implies noinline: we should not be inlining such functions.
17847330f729Sjoerg     B.addAttribute(llvm::Attribute::Naked);
17857330f729Sjoerg     B.addAttribute(llvm::Attribute::NoInline);
17867330f729Sjoerg   } else if (D->hasAttr<NoDuplicateAttr>()) {
17877330f729Sjoerg     B.addAttribute(llvm::Attribute::NoDuplicate);
1788*e038c9c4Sjoerg   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1789*e038c9c4Sjoerg     // Add noinline if the function isn't always_inline.
17907330f729Sjoerg     B.addAttribute(llvm::Attribute::NoInline);
17917330f729Sjoerg   } else if (D->hasAttr<AlwaysInlineAttr>() &&
17927330f729Sjoerg              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
17937330f729Sjoerg     // (noinline wins over always_inline, and we can't specify both in IR)
17947330f729Sjoerg     B.addAttribute(llvm::Attribute::AlwaysInline);
17957330f729Sjoerg   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
17967330f729Sjoerg     // If we're not inlining, then force everything that isn't always_inline to
17977330f729Sjoerg     // carry an explicit noinline attribute.
17987330f729Sjoerg     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
17997330f729Sjoerg       B.addAttribute(llvm::Attribute::NoInline);
18007330f729Sjoerg   } else {
18017330f729Sjoerg     // Otherwise, propagate the inline hint attribute and potentially use its
18027330f729Sjoerg     // absence to mark things as noinline.
18037330f729Sjoerg     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18047330f729Sjoerg       // Search function and template pattern redeclarations for inline.
18057330f729Sjoerg       auto CheckForInline = [](const FunctionDecl *FD) {
18067330f729Sjoerg         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
18077330f729Sjoerg           return Redecl->isInlineSpecified();
18087330f729Sjoerg         };
18097330f729Sjoerg         if (any_of(FD->redecls(), CheckRedeclForInline))
18107330f729Sjoerg           return true;
18117330f729Sjoerg         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
18127330f729Sjoerg         if (!Pattern)
18137330f729Sjoerg           return false;
18147330f729Sjoerg         return any_of(Pattern->redecls(), CheckRedeclForInline);
18157330f729Sjoerg       };
18167330f729Sjoerg       if (CheckForInline(FD)) {
18177330f729Sjoerg         B.addAttribute(llvm::Attribute::InlineHint);
18187330f729Sjoerg       } else if (CodeGenOpts.getInlining() ==
18197330f729Sjoerg                      CodeGenOptions::OnlyHintInlining &&
18207330f729Sjoerg                  !FD->isInlined() &&
18217330f729Sjoerg                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
18227330f729Sjoerg         B.addAttribute(llvm::Attribute::NoInline);
18237330f729Sjoerg       }
18247330f729Sjoerg     }
18257330f729Sjoerg   }
18267330f729Sjoerg 
18277330f729Sjoerg   // Add other optimization related attributes if we are optimizing this
18287330f729Sjoerg   // function.
18297330f729Sjoerg   if (!D->hasAttr<OptimizeNoneAttr>()) {
18307330f729Sjoerg     if (D->hasAttr<ColdAttr>()) {
18317330f729Sjoerg       if (!ShouldAddOptNone)
18327330f729Sjoerg         B.addAttribute(llvm::Attribute::OptimizeForSize);
18337330f729Sjoerg       B.addAttribute(llvm::Attribute::Cold);
18347330f729Sjoerg     }
1835*e038c9c4Sjoerg     if (D->hasAttr<HotAttr>())
1836*e038c9c4Sjoerg       B.addAttribute(llvm::Attribute::Hot);
18377330f729Sjoerg     if (D->hasAttr<MinSizeAttr>())
18387330f729Sjoerg       B.addAttribute(llvm::Attribute::MinSize);
18397330f729Sjoerg   }
18407330f729Sjoerg 
18417330f729Sjoerg   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
18427330f729Sjoerg 
18437330f729Sjoerg   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
18447330f729Sjoerg   if (alignment)
18457330f729Sjoerg     F->setAlignment(llvm::Align(alignment));
18467330f729Sjoerg 
18477330f729Sjoerg   if (!D->hasAttr<AlignedAttr>())
18487330f729Sjoerg     if (LangOpts.FunctionAlignment)
18497330f729Sjoerg       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
18507330f729Sjoerg 
18517330f729Sjoerg   // Some C++ ABIs require 2-byte alignment for member functions, in order to
18527330f729Sjoerg   // reserve a bit for differentiating between virtual and non-virtual member
18537330f729Sjoerg   // functions. If the current target's C++ ABI requires this and this is a
18547330f729Sjoerg   // member function, set its alignment accordingly.
18557330f729Sjoerg   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
18567330f729Sjoerg     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
18577330f729Sjoerg       F->setAlignment(llvm::Align(2));
18587330f729Sjoerg   }
18597330f729Sjoerg 
18607330f729Sjoerg   // In the cross-dso CFI mode with canonical jump tables, we want !type
18617330f729Sjoerg   // attributes on definitions only.
18627330f729Sjoerg   if (CodeGenOpts.SanitizeCfiCrossDso &&
18637330f729Sjoerg       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
18647330f729Sjoerg     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18657330f729Sjoerg       // Skip available_externally functions. They won't be codegen'ed in the
18667330f729Sjoerg       // current module anyway.
18677330f729Sjoerg       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
18687330f729Sjoerg         CreateFunctionTypeMetadataForIcall(FD, F);
18697330f729Sjoerg     }
18707330f729Sjoerg   }
18717330f729Sjoerg 
18727330f729Sjoerg   // Emit type metadata on member functions for member function pointer checks.
18737330f729Sjoerg   // These are only ever necessary on definitions; we're guaranteed that the
18747330f729Sjoerg   // definition will be present in the LTO unit as a result of LTO visibility.
18757330f729Sjoerg   auto *MD = dyn_cast<CXXMethodDecl>(D);
18767330f729Sjoerg   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
18777330f729Sjoerg     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
18787330f729Sjoerg       llvm::Metadata *Id =
18797330f729Sjoerg           CreateMetadataIdentifierForType(Context.getMemberPointerType(
18807330f729Sjoerg               MD->getType(), Context.getRecordType(Base).getTypePtr()));
18817330f729Sjoerg       F->addTypeMetadata(0, Id);
18827330f729Sjoerg     }
18837330f729Sjoerg   }
18847330f729Sjoerg }
18857330f729Sjoerg 
setLLVMFunctionFEnvAttributes(const FunctionDecl * D,llvm::Function * F)1886*e038c9c4Sjoerg void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
1887*e038c9c4Sjoerg                                                   llvm::Function *F) {
1888*e038c9c4Sjoerg   if (D->hasAttr<StrictFPAttr>()) {
1889*e038c9c4Sjoerg     llvm::AttrBuilder FuncAttrs;
1890*e038c9c4Sjoerg     FuncAttrs.addAttribute("strictfp");
1891*e038c9c4Sjoerg     F->addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1892*e038c9c4Sjoerg   }
1893*e038c9c4Sjoerg }
1894*e038c9c4Sjoerg 
SetCommonAttributes(GlobalDecl GD,llvm::GlobalValue * GV)18957330f729Sjoerg void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
18967330f729Sjoerg   const Decl *D = GD.getDecl();
18977330f729Sjoerg   if (dyn_cast_or_null<NamedDecl>(D))
18987330f729Sjoerg     setGVProperties(GV, GD);
18997330f729Sjoerg   else
19007330f729Sjoerg     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
19017330f729Sjoerg 
19027330f729Sjoerg   if (D && D->hasAttr<UsedAttr>())
1903*e038c9c4Sjoerg     addUsedOrCompilerUsedGlobal(GV);
19047330f729Sjoerg 
19057330f729Sjoerg   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
19067330f729Sjoerg     const auto *VD = cast<VarDecl>(D);
19077330f729Sjoerg     if (VD->getType().isConstQualified() &&
19087330f729Sjoerg         VD->getStorageDuration() == SD_Static)
1909*e038c9c4Sjoerg       addUsedOrCompilerUsedGlobal(GV);
19107330f729Sjoerg   }
19117330f729Sjoerg }
19127330f729Sjoerg 
GetCPUAndFeaturesAttributes(GlobalDecl GD,llvm::AttrBuilder & Attrs)19137330f729Sjoerg bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
19147330f729Sjoerg                                                 llvm::AttrBuilder &Attrs) {
19157330f729Sjoerg   // Add target-cpu and target-features attributes to functions. If
19167330f729Sjoerg   // we have a decl for the function and it has a target attribute then
19177330f729Sjoerg   // parse that and add it to the feature set.
19187330f729Sjoerg   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1919*e038c9c4Sjoerg   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
19207330f729Sjoerg   std::vector<std::string> Features;
19217330f729Sjoerg   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
19227330f729Sjoerg   FD = FD ? FD->getMostRecentDecl() : FD;
19237330f729Sjoerg   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
19247330f729Sjoerg   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
19257330f729Sjoerg   bool AddedAttr = false;
19267330f729Sjoerg   if (TD || SD) {
19277330f729Sjoerg     llvm::StringMap<bool> FeatureMap;
1928*e038c9c4Sjoerg     getContext().getFunctionFeatureMap(FeatureMap, GD);
19297330f729Sjoerg 
19307330f729Sjoerg     // Produce the canonical string for this set of features.
19317330f729Sjoerg     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
19327330f729Sjoerg       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
19337330f729Sjoerg 
19347330f729Sjoerg     // Now add the target-cpu and target-features to the function.
19357330f729Sjoerg     // While we populated the feature map above, we still need to
19367330f729Sjoerg     // get and parse the target attribute so we can get the cpu for
19377330f729Sjoerg     // the function.
19387330f729Sjoerg     if (TD) {
1939*e038c9c4Sjoerg       ParsedTargetAttr ParsedAttr = TD->parse();
1940*e038c9c4Sjoerg       if (!ParsedAttr.Architecture.empty() &&
1941*e038c9c4Sjoerg           getTarget().isValidCPUName(ParsedAttr.Architecture)) {
19427330f729Sjoerg         TargetCPU = ParsedAttr.Architecture;
1943*e038c9c4Sjoerg         TuneCPU = ""; // Clear the tune CPU.
1944*e038c9c4Sjoerg       }
1945*e038c9c4Sjoerg       if (!ParsedAttr.Tune.empty() &&
1946*e038c9c4Sjoerg           getTarget().isValidCPUName(ParsedAttr.Tune))
1947*e038c9c4Sjoerg         TuneCPU = ParsedAttr.Tune;
19487330f729Sjoerg     }
19497330f729Sjoerg   } else {
19507330f729Sjoerg     // Otherwise just add the existing target cpu and target features to the
19517330f729Sjoerg     // function.
19527330f729Sjoerg     Features = getTarget().getTargetOpts().Features;
19537330f729Sjoerg   }
19547330f729Sjoerg 
1955*e038c9c4Sjoerg   if (!TargetCPU.empty()) {
19567330f729Sjoerg     Attrs.addAttribute("target-cpu", TargetCPU);
19577330f729Sjoerg     AddedAttr = true;
19587330f729Sjoerg   }
1959*e038c9c4Sjoerg   if (!TuneCPU.empty()) {
1960*e038c9c4Sjoerg     Attrs.addAttribute("tune-cpu", TuneCPU);
1961*e038c9c4Sjoerg     AddedAttr = true;
1962*e038c9c4Sjoerg   }
19637330f729Sjoerg   if (!Features.empty()) {
19647330f729Sjoerg     llvm::sort(Features);
19657330f729Sjoerg     Attrs.addAttribute("target-features", llvm::join(Features, ","));
19667330f729Sjoerg     AddedAttr = true;
19677330f729Sjoerg   }
19687330f729Sjoerg 
19697330f729Sjoerg   return AddedAttr;
19707330f729Sjoerg }
19717330f729Sjoerg 
setNonAliasAttributes(GlobalDecl GD,llvm::GlobalObject * GO)19727330f729Sjoerg void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
19737330f729Sjoerg                                           llvm::GlobalObject *GO) {
19747330f729Sjoerg   const Decl *D = GD.getDecl();
19757330f729Sjoerg   SetCommonAttributes(GD, GO);
19767330f729Sjoerg 
19777330f729Sjoerg   if (D) {
19787330f729Sjoerg     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1979*e038c9c4Sjoerg       if (D->hasAttr<RetainAttr>())
1980*e038c9c4Sjoerg         addUsedGlobal(GV);
19817330f729Sjoerg       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
19827330f729Sjoerg         GV->addAttribute("bss-section", SA->getName());
19837330f729Sjoerg       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
19847330f729Sjoerg         GV->addAttribute("data-section", SA->getName());
19857330f729Sjoerg       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
19867330f729Sjoerg         GV->addAttribute("rodata-section", SA->getName());
19877330f729Sjoerg       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
19887330f729Sjoerg         GV->addAttribute("relro-section", SA->getName());
19897330f729Sjoerg     }
19907330f729Sjoerg 
19917330f729Sjoerg     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1992*e038c9c4Sjoerg       if (D->hasAttr<RetainAttr>())
1993*e038c9c4Sjoerg         addUsedGlobal(F);
19947330f729Sjoerg       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
19957330f729Sjoerg         if (!D->getAttr<SectionAttr>())
19967330f729Sjoerg           F->addFnAttr("implicit-section-name", SA->getName());
19977330f729Sjoerg 
19987330f729Sjoerg       llvm::AttrBuilder Attrs;
19997330f729Sjoerg       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
20007330f729Sjoerg         // We know that GetCPUAndFeaturesAttributes will always have the
20017330f729Sjoerg         // newest set, since it has the newest possible FunctionDecl, so the
20027330f729Sjoerg         // new ones should replace the old.
2003*e038c9c4Sjoerg         llvm::AttrBuilder RemoveAttrs;
2004*e038c9c4Sjoerg         RemoveAttrs.addAttribute("target-cpu");
2005*e038c9c4Sjoerg         RemoveAttrs.addAttribute("target-features");
2006*e038c9c4Sjoerg         RemoveAttrs.addAttribute("tune-cpu");
2007*e038c9c4Sjoerg         F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs);
20087330f729Sjoerg         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
20097330f729Sjoerg       }
20107330f729Sjoerg     }
20117330f729Sjoerg 
20127330f729Sjoerg     if (const auto *CSA = D->getAttr<CodeSegAttr>())
20137330f729Sjoerg       GO->setSection(CSA->getName());
20147330f729Sjoerg     else if (const auto *SA = D->getAttr<SectionAttr>())
20157330f729Sjoerg       GO->setSection(SA->getName());
20167330f729Sjoerg   }
20177330f729Sjoerg 
20187330f729Sjoerg   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
20197330f729Sjoerg }
20207330f729Sjoerg 
SetInternalFunctionAttributes(GlobalDecl GD,llvm::Function * F,const CGFunctionInfo & FI)20217330f729Sjoerg void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
20227330f729Sjoerg                                                   llvm::Function *F,
20237330f729Sjoerg                                                   const CGFunctionInfo &FI) {
20247330f729Sjoerg   const Decl *D = GD.getDecl();
2025*e038c9c4Sjoerg   SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
20267330f729Sjoerg   SetLLVMFunctionAttributesForDefinition(D, F);
20277330f729Sjoerg 
20287330f729Sjoerg   F->setLinkage(llvm::Function::InternalLinkage);
20297330f729Sjoerg 
20307330f729Sjoerg   setNonAliasAttributes(GD, F);
20317330f729Sjoerg }
20327330f729Sjoerg 
setLinkageForGV(llvm::GlobalValue * GV,const NamedDecl * ND)20337330f729Sjoerg static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
20347330f729Sjoerg   // Set linkage and visibility in case we never see a definition.
20357330f729Sjoerg   LinkageInfo LV = ND->getLinkageAndVisibility();
20367330f729Sjoerg   // Don't set internal linkage on declarations.
20377330f729Sjoerg   // "extern_weak" is overloaded in LLVM; we probably should have
20387330f729Sjoerg   // separate linkage types for this.
20397330f729Sjoerg   if (isExternallyVisible(LV.getLinkage()) &&
20407330f729Sjoerg       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
20417330f729Sjoerg     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
20427330f729Sjoerg }
20437330f729Sjoerg 
CreateFunctionTypeMetadataForIcall(const FunctionDecl * FD,llvm::Function * F)20447330f729Sjoerg void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
20457330f729Sjoerg                                                        llvm::Function *F) {
20467330f729Sjoerg   // Only if we are checking indirect calls.
20477330f729Sjoerg   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
20487330f729Sjoerg     return;
20497330f729Sjoerg 
20507330f729Sjoerg   // Non-static class methods are handled via vtable or member function pointer
20517330f729Sjoerg   // checks elsewhere.
20527330f729Sjoerg   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
20537330f729Sjoerg     return;
20547330f729Sjoerg 
20557330f729Sjoerg   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
20567330f729Sjoerg   F->addTypeMetadata(0, MD);
20577330f729Sjoerg   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
20587330f729Sjoerg 
20597330f729Sjoerg   // Emit a hash-based bit set entry for cross-DSO calls.
20607330f729Sjoerg   if (CodeGenOpts.SanitizeCfiCrossDso)
20617330f729Sjoerg     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
20627330f729Sjoerg       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
20637330f729Sjoerg }
20647330f729Sjoerg 
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)20657330f729Sjoerg void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
20667330f729Sjoerg                                           bool IsIncompleteFunction,
20677330f729Sjoerg                                           bool IsThunk) {
20687330f729Sjoerg 
20697330f729Sjoerg   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
20707330f729Sjoerg     // If this is an intrinsic function, set the function's attributes
20717330f729Sjoerg     // to the intrinsic's attributes.
20727330f729Sjoerg     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
20737330f729Sjoerg     return;
20747330f729Sjoerg   }
20757330f729Sjoerg 
20767330f729Sjoerg   const auto *FD = cast<FunctionDecl>(GD.getDecl());
20777330f729Sjoerg 
20787330f729Sjoerg   if (!IsIncompleteFunction)
2079*e038c9c4Sjoerg     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2080*e038c9c4Sjoerg                               IsThunk);
20817330f729Sjoerg 
20827330f729Sjoerg   // Add the Returned attribute for "this", except for iOS 5 and earlier
20837330f729Sjoerg   // where substantial code, including the libstdc++ dylib, was compiled with
20847330f729Sjoerg   // GCC and does not actually return "this".
20857330f729Sjoerg   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
20867330f729Sjoerg       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
20877330f729Sjoerg     assert(!F->arg_empty() &&
20887330f729Sjoerg            F->arg_begin()->getType()
20897330f729Sjoerg              ->canLosslesslyBitCastTo(F->getReturnType()) &&
20907330f729Sjoerg            "unexpected this return");
20917330f729Sjoerg     F->addAttribute(1, llvm::Attribute::Returned);
20927330f729Sjoerg   }
20937330f729Sjoerg 
20947330f729Sjoerg   // Only a few attributes are set on declarations; these may later be
20957330f729Sjoerg   // overridden by a definition.
20967330f729Sjoerg 
20977330f729Sjoerg   setLinkageForGV(F, FD);
20987330f729Sjoerg   setGVProperties(F, FD);
20997330f729Sjoerg 
21007330f729Sjoerg   // Setup target-specific attributes.
21017330f729Sjoerg   if (!IsIncompleteFunction && F->isDeclaration())
21027330f729Sjoerg     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
21037330f729Sjoerg 
21047330f729Sjoerg   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
21057330f729Sjoerg     F->setSection(CSA->getName());
21067330f729Sjoerg   else if (const auto *SA = FD->getAttr<SectionAttr>())
21077330f729Sjoerg      F->setSection(SA->getName());
21087330f729Sjoerg 
2109*e038c9c4Sjoerg   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2110*e038c9c4Sjoerg   if (FD->isInlineBuiltinDeclaration()) {
2111*e038c9c4Sjoerg     const FunctionDecl *FDBody;
2112*e038c9c4Sjoerg     bool HasBody = FD->hasBody(FDBody);
2113*e038c9c4Sjoerg     (void)HasBody;
2114*e038c9c4Sjoerg     assert(HasBody && "Inline builtin declarations should always have an "
2115*e038c9c4Sjoerg                       "available body!");
2116*e038c9c4Sjoerg     if (shouldEmitFunction(FDBody))
2117*e038c9c4Sjoerg       F->addAttribute(llvm::AttributeList::FunctionIndex,
2118*e038c9c4Sjoerg                       llvm::Attribute::NoBuiltin);
2119*e038c9c4Sjoerg   }
2120*e038c9c4Sjoerg 
21217330f729Sjoerg   if (FD->isReplaceableGlobalAllocationFunction()) {
21227330f729Sjoerg     // A replaceable global allocation function does not act like a builtin by
21237330f729Sjoerg     // default, only if it is invoked by a new-expression or delete-expression.
21247330f729Sjoerg     F->addAttribute(llvm::AttributeList::FunctionIndex,
21257330f729Sjoerg                     llvm::Attribute::NoBuiltin);
21267330f729Sjoerg   }
21277330f729Sjoerg 
21287330f729Sjoerg   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
21297330f729Sjoerg     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
21307330f729Sjoerg   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
21317330f729Sjoerg     if (MD->isVirtual())
21327330f729Sjoerg       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
21337330f729Sjoerg 
21347330f729Sjoerg   // Don't emit entries for function declarations in the cross-DSO mode. This
21357330f729Sjoerg   // is handled with better precision by the receiving DSO. But if jump tables
21367330f729Sjoerg   // are non-canonical then we need type metadata in order to produce the local
21377330f729Sjoerg   // jump table.
21387330f729Sjoerg   if (!CodeGenOpts.SanitizeCfiCrossDso ||
21397330f729Sjoerg       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
21407330f729Sjoerg     CreateFunctionTypeMetadataForIcall(FD, F);
21417330f729Sjoerg 
21427330f729Sjoerg   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
21437330f729Sjoerg     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
21447330f729Sjoerg 
21457330f729Sjoerg   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
21467330f729Sjoerg     // Annotate the callback behavior as metadata:
21477330f729Sjoerg     //  - The callback callee (as argument number).
21487330f729Sjoerg     //  - The callback payloads (as argument numbers).
21497330f729Sjoerg     llvm::LLVMContext &Ctx = F->getContext();
21507330f729Sjoerg     llvm::MDBuilder MDB(Ctx);
21517330f729Sjoerg 
21527330f729Sjoerg     // The payload indices are all but the first one in the encoding. The first
21537330f729Sjoerg     // identifies the callback callee.
21547330f729Sjoerg     int CalleeIdx = *CB->encoding_begin();
21557330f729Sjoerg     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
21567330f729Sjoerg     F->addMetadata(llvm::LLVMContext::MD_callback,
21577330f729Sjoerg                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
21587330f729Sjoerg                                                CalleeIdx, PayloadIndices,
21597330f729Sjoerg                                                /* VarArgsArePassed */ false)}));
21607330f729Sjoerg   }
21617330f729Sjoerg }
21627330f729Sjoerg 
addUsedGlobal(llvm::GlobalValue * GV)21637330f729Sjoerg void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2164*e038c9c4Sjoerg   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
21657330f729Sjoerg          "Only globals with definition can force usage.");
21667330f729Sjoerg   LLVMUsed.emplace_back(GV);
21677330f729Sjoerg }
21687330f729Sjoerg 
addCompilerUsedGlobal(llvm::GlobalValue * GV)21697330f729Sjoerg void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
21707330f729Sjoerg   assert(!GV->isDeclaration() &&
21717330f729Sjoerg          "Only globals with definition can force usage.");
21727330f729Sjoerg   LLVMCompilerUsed.emplace_back(GV);
21737330f729Sjoerg }
21747330f729Sjoerg 
addUsedOrCompilerUsedGlobal(llvm::GlobalValue * GV)2175*e038c9c4Sjoerg void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2176*e038c9c4Sjoerg   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2177*e038c9c4Sjoerg          "Only globals with definition can force usage.");
2178*e038c9c4Sjoerg   if (getTriple().isOSBinFormatELF())
2179*e038c9c4Sjoerg     LLVMCompilerUsed.emplace_back(GV);
2180*e038c9c4Sjoerg   else
2181*e038c9c4Sjoerg     LLVMUsed.emplace_back(GV);
2182*e038c9c4Sjoerg }
2183*e038c9c4Sjoerg 
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakTrackingVH> & List)21847330f729Sjoerg static void emitUsed(CodeGenModule &CGM, StringRef Name,
21857330f729Sjoerg                      std::vector<llvm::WeakTrackingVH> &List) {
21867330f729Sjoerg   // Don't create llvm.used if there is no need.
21877330f729Sjoerg   if (List.empty())
21887330f729Sjoerg     return;
21897330f729Sjoerg 
21907330f729Sjoerg   // Convert List to what ConstantArray needs.
21917330f729Sjoerg   SmallVector<llvm::Constant*, 8> UsedArray;
21927330f729Sjoerg   UsedArray.resize(List.size());
21937330f729Sjoerg   for (unsigned i = 0, e = List.size(); i != e; ++i) {
21947330f729Sjoerg     UsedArray[i] =
21957330f729Sjoerg         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
21967330f729Sjoerg             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
21977330f729Sjoerg   }
21987330f729Sjoerg 
21997330f729Sjoerg   if (UsedArray.empty())
22007330f729Sjoerg     return;
22017330f729Sjoerg   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
22027330f729Sjoerg 
22037330f729Sjoerg   auto *GV = new llvm::GlobalVariable(
22047330f729Sjoerg       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
22057330f729Sjoerg       llvm::ConstantArray::get(ATy, UsedArray), Name);
22067330f729Sjoerg 
22077330f729Sjoerg   GV->setSection("llvm.metadata");
22087330f729Sjoerg }
22097330f729Sjoerg 
emitLLVMUsed()22107330f729Sjoerg void CodeGenModule::emitLLVMUsed() {
22117330f729Sjoerg   emitUsed(*this, "llvm.used", LLVMUsed);
22127330f729Sjoerg   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
22137330f729Sjoerg }
22147330f729Sjoerg 
AppendLinkerOptions(StringRef Opts)22157330f729Sjoerg void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
22167330f729Sjoerg   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
22177330f729Sjoerg   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
22187330f729Sjoerg }
22197330f729Sjoerg 
AddDetectMismatch(StringRef Name,StringRef Value)22207330f729Sjoerg void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
22217330f729Sjoerg   llvm::SmallString<32> Opt;
22227330f729Sjoerg   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2223*e038c9c4Sjoerg   if (Opt.empty())
2224*e038c9c4Sjoerg     return;
22257330f729Sjoerg   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
22267330f729Sjoerg   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
22277330f729Sjoerg }
22287330f729Sjoerg 
AddDependentLib(StringRef Lib)22297330f729Sjoerg void CodeGenModule::AddDependentLib(StringRef Lib) {
22307330f729Sjoerg   auto &C = getLLVMContext();
22317330f729Sjoerg   if (getTarget().getTriple().isOSBinFormatELF()) {
22327330f729Sjoerg       ELFDependentLibraries.push_back(
22337330f729Sjoerg         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
22347330f729Sjoerg     return;
22357330f729Sjoerg   }
22367330f729Sjoerg 
22377330f729Sjoerg   llvm::SmallString<24> Opt;
22387330f729Sjoerg   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
22397330f729Sjoerg   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
22407330f729Sjoerg   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
22417330f729Sjoerg }
22427330f729Sjoerg 
22437330f729Sjoerg /// Add link options implied by the given module, including modules
22447330f729Sjoerg /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::MDNode * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)22457330f729Sjoerg static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
22467330f729Sjoerg                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
22477330f729Sjoerg                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
22487330f729Sjoerg   // Import this module's parent.
22497330f729Sjoerg   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
22507330f729Sjoerg     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
22517330f729Sjoerg   }
22527330f729Sjoerg 
22537330f729Sjoerg   // Import this module's dependencies.
22547330f729Sjoerg   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
22557330f729Sjoerg     if (Visited.insert(Mod->Imports[I - 1]).second)
22567330f729Sjoerg       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
22577330f729Sjoerg   }
22587330f729Sjoerg 
22597330f729Sjoerg   // Add linker options to link against the libraries/frameworks
22607330f729Sjoerg   // described by this module.
22617330f729Sjoerg   llvm::LLVMContext &Context = CGM.getLLVMContext();
22627330f729Sjoerg   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
22637330f729Sjoerg 
22647330f729Sjoerg   // For modules that use export_as for linking, use that module
22657330f729Sjoerg   // name instead.
22667330f729Sjoerg   if (Mod->UseExportAsModuleLinkName)
22677330f729Sjoerg     return;
22687330f729Sjoerg 
22697330f729Sjoerg   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
22707330f729Sjoerg     // Link against a framework.  Frameworks are currently Darwin only, so we
22717330f729Sjoerg     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
22727330f729Sjoerg     if (Mod->LinkLibraries[I-1].IsFramework) {
22737330f729Sjoerg       llvm::Metadata *Args[2] = {
22747330f729Sjoerg           llvm::MDString::get(Context, "-framework"),
22757330f729Sjoerg           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
22767330f729Sjoerg 
22777330f729Sjoerg       Metadata.push_back(llvm::MDNode::get(Context, Args));
22787330f729Sjoerg       continue;
22797330f729Sjoerg     }
22807330f729Sjoerg 
22817330f729Sjoerg     // Link against a library.
22827330f729Sjoerg     if (IsELF) {
22837330f729Sjoerg       llvm::Metadata *Args[2] = {
22847330f729Sjoerg           llvm::MDString::get(Context, "lib"),
22857330f729Sjoerg           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
22867330f729Sjoerg       };
22877330f729Sjoerg       Metadata.push_back(llvm::MDNode::get(Context, Args));
22887330f729Sjoerg     } else {
22897330f729Sjoerg       llvm::SmallString<24> Opt;
22907330f729Sjoerg       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
22917330f729Sjoerg           Mod->LinkLibraries[I - 1].Library, Opt);
22927330f729Sjoerg       auto *OptString = llvm::MDString::get(Context, Opt);
22937330f729Sjoerg       Metadata.push_back(llvm::MDNode::get(Context, OptString));
22947330f729Sjoerg     }
22957330f729Sjoerg   }
22967330f729Sjoerg }
22977330f729Sjoerg 
EmitModuleLinkOptions()22987330f729Sjoerg void CodeGenModule::EmitModuleLinkOptions() {
22997330f729Sjoerg   // Collect the set of all of the modules we want to visit to emit link
23007330f729Sjoerg   // options, which is essentially the imported modules and all of their
23017330f729Sjoerg   // non-explicit child modules.
23027330f729Sjoerg   llvm::SetVector<clang::Module *> LinkModules;
23037330f729Sjoerg   llvm::SmallPtrSet<clang::Module *, 16> Visited;
23047330f729Sjoerg   SmallVector<clang::Module *, 16> Stack;
23057330f729Sjoerg 
23067330f729Sjoerg   // Seed the stack with imported modules.
23077330f729Sjoerg   for (Module *M : ImportedModules) {
23087330f729Sjoerg     // Do not add any link flags when an implementation TU of a module imports
23097330f729Sjoerg     // a header of that same module.
23107330f729Sjoerg     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
23117330f729Sjoerg         !getLangOpts().isCompilingModule())
23127330f729Sjoerg       continue;
23137330f729Sjoerg     if (Visited.insert(M).second)
23147330f729Sjoerg       Stack.push_back(M);
23157330f729Sjoerg   }
23167330f729Sjoerg 
23177330f729Sjoerg   // Find all of the modules to import, making a little effort to prune
23187330f729Sjoerg   // non-leaf modules.
23197330f729Sjoerg   while (!Stack.empty()) {
23207330f729Sjoerg     clang::Module *Mod = Stack.pop_back_val();
23217330f729Sjoerg 
23227330f729Sjoerg     bool AnyChildren = false;
23237330f729Sjoerg 
23247330f729Sjoerg     // Visit the submodules of this module.
23257330f729Sjoerg     for (const auto &SM : Mod->submodules()) {
23267330f729Sjoerg       // Skip explicit children; they need to be explicitly imported to be
23277330f729Sjoerg       // linked against.
23287330f729Sjoerg       if (SM->IsExplicit)
23297330f729Sjoerg         continue;
23307330f729Sjoerg 
23317330f729Sjoerg       if (Visited.insert(SM).second) {
23327330f729Sjoerg         Stack.push_back(SM);
23337330f729Sjoerg         AnyChildren = true;
23347330f729Sjoerg       }
23357330f729Sjoerg     }
23367330f729Sjoerg 
23377330f729Sjoerg     // We didn't find any children, so add this module to the list of
23387330f729Sjoerg     // modules to link against.
23397330f729Sjoerg     if (!AnyChildren) {
23407330f729Sjoerg       LinkModules.insert(Mod);
23417330f729Sjoerg     }
23427330f729Sjoerg   }
23437330f729Sjoerg 
23447330f729Sjoerg   // Add link options for all of the imported modules in reverse topological
23457330f729Sjoerg   // order.  We don't do anything to try to order import link flags with respect
23467330f729Sjoerg   // to linker options inserted by things like #pragma comment().
23477330f729Sjoerg   SmallVector<llvm::MDNode *, 16> MetadataArgs;
23487330f729Sjoerg   Visited.clear();
23497330f729Sjoerg   for (Module *M : LinkModules)
23507330f729Sjoerg     if (Visited.insert(M).second)
23517330f729Sjoerg       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
23527330f729Sjoerg   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
23537330f729Sjoerg   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
23547330f729Sjoerg 
23557330f729Sjoerg   // Add the linker options metadata flag.
23567330f729Sjoerg   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
23577330f729Sjoerg   for (auto *MD : LinkerOptionsMetadata)
23587330f729Sjoerg     NMD->addOperand(MD);
23597330f729Sjoerg }
23607330f729Sjoerg 
EmitDeferred()23617330f729Sjoerg void CodeGenModule::EmitDeferred() {
23627330f729Sjoerg   // Emit deferred declare target declarations.
23637330f729Sjoerg   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
23647330f729Sjoerg     getOpenMPRuntime().emitDeferredTargetDecls();
23657330f729Sjoerg 
23667330f729Sjoerg   // Emit code for any potentially referenced deferred decls.  Since a
23677330f729Sjoerg   // previously unused static decl may become used during the generation of code
23687330f729Sjoerg   // for a static function, iterate until no changes are made.
23697330f729Sjoerg 
23707330f729Sjoerg   if (!DeferredVTables.empty()) {
23717330f729Sjoerg     EmitDeferredVTables();
23727330f729Sjoerg 
23737330f729Sjoerg     // Emitting a vtable doesn't directly cause more vtables to
23747330f729Sjoerg     // become deferred, although it can cause functions to be
23757330f729Sjoerg     // emitted that then need those vtables.
23767330f729Sjoerg     assert(DeferredVTables.empty());
23777330f729Sjoerg   }
23787330f729Sjoerg 
2379*e038c9c4Sjoerg   // Emit CUDA/HIP static device variables referenced by host code only.
2380*e038c9c4Sjoerg   // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2381*e038c9c4Sjoerg   // needed for further handling.
2382*e038c9c4Sjoerg   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2383*e038c9c4Sjoerg     for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
2384*e038c9c4Sjoerg       DeferredDeclsToEmit.push_back(V);
2385*e038c9c4Sjoerg 
23867330f729Sjoerg   // Stop if we're out of both deferred vtables and deferred declarations.
23877330f729Sjoerg   if (DeferredDeclsToEmit.empty())
23887330f729Sjoerg     return;
23897330f729Sjoerg 
23907330f729Sjoerg   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
23917330f729Sjoerg   // work, it will not interfere with this.
23927330f729Sjoerg   std::vector<GlobalDecl> CurDeclsToEmit;
23937330f729Sjoerg   CurDeclsToEmit.swap(DeferredDeclsToEmit);
23947330f729Sjoerg 
23957330f729Sjoerg   for (GlobalDecl &D : CurDeclsToEmit) {
23967330f729Sjoerg     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
23977330f729Sjoerg     // to get GlobalValue with exactly the type we need, not something that
23987330f729Sjoerg     // might had been created for another decl with the same mangled name but
23997330f729Sjoerg     // different type.
24007330f729Sjoerg     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
24017330f729Sjoerg         GetAddrOfGlobal(D, ForDefinition));
24027330f729Sjoerg 
24037330f729Sjoerg     // In case of different address spaces, we may still get a cast, even with
24047330f729Sjoerg     // IsForDefinition equal to true. Query mangled names table to get
24057330f729Sjoerg     // GlobalValue.
24067330f729Sjoerg     if (!GV)
24077330f729Sjoerg       GV = GetGlobalValue(getMangledName(D));
24087330f729Sjoerg 
24097330f729Sjoerg     // Make sure GetGlobalValue returned non-null.
24107330f729Sjoerg     assert(GV);
24117330f729Sjoerg 
24127330f729Sjoerg     // Check to see if we've already emitted this.  This is necessary
24137330f729Sjoerg     // for a couple of reasons: first, decls can end up in the
24147330f729Sjoerg     // deferred-decls queue multiple times, and second, decls can end
24157330f729Sjoerg     // up with definitions in unusual ways (e.g. by an extern inline
24167330f729Sjoerg     // function acquiring a strong function redefinition).  Just
24177330f729Sjoerg     // ignore these cases.
24187330f729Sjoerg     if (!GV->isDeclaration())
24197330f729Sjoerg       continue;
24207330f729Sjoerg 
24217330f729Sjoerg     // If this is OpenMP, check if it is legal to emit this global normally.
24227330f729Sjoerg     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
24237330f729Sjoerg       continue;
24247330f729Sjoerg 
24257330f729Sjoerg     // Otherwise, emit the definition and move on to the next one.
24267330f729Sjoerg     EmitGlobalDefinition(D, GV);
24277330f729Sjoerg 
24287330f729Sjoerg     // If we found out that we need to emit more decls, do that recursively.
24297330f729Sjoerg     // This has the advantage that the decls are emitted in a DFS and related
24307330f729Sjoerg     // ones are close together, which is convenient for testing.
24317330f729Sjoerg     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
24327330f729Sjoerg       EmitDeferred();
24337330f729Sjoerg       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
24347330f729Sjoerg     }
24357330f729Sjoerg   }
24367330f729Sjoerg }
24377330f729Sjoerg 
EmitVTablesOpportunistically()24387330f729Sjoerg void CodeGenModule::EmitVTablesOpportunistically() {
24397330f729Sjoerg   // Try to emit external vtables as available_externally if they have emitted
24407330f729Sjoerg   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
24417330f729Sjoerg   // is not allowed to create new references to things that need to be emitted
24427330f729Sjoerg   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
24437330f729Sjoerg 
24447330f729Sjoerg   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
24457330f729Sjoerg          && "Only emit opportunistic vtables with optimizations");
24467330f729Sjoerg 
24477330f729Sjoerg   for (const CXXRecordDecl *RD : OpportunisticVTables) {
24487330f729Sjoerg     assert(getVTables().isVTableExternal(RD) &&
24497330f729Sjoerg            "This queue should only contain external vtables");
24507330f729Sjoerg     if (getCXXABI().canSpeculativelyEmitVTable(RD))
24517330f729Sjoerg       VTables.GenerateClassData(RD);
24527330f729Sjoerg   }
24537330f729Sjoerg   OpportunisticVTables.clear();
24547330f729Sjoerg }
24557330f729Sjoerg 
EmitGlobalAnnotations()24567330f729Sjoerg void CodeGenModule::EmitGlobalAnnotations() {
24577330f729Sjoerg   if (Annotations.empty())
24587330f729Sjoerg     return;
24597330f729Sjoerg 
24607330f729Sjoerg   // Create a new global variable for the ConstantStruct in the Module.
24617330f729Sjoerg   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
24627330f729Sjoerg     Annotations[0]->getType(), Annotations.size()), Annotations);
24637330f729Sjoerg   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
24647330f729Sjoerg                                       llvm::GlobalValue::AppendingLinkage,
24657330f729Sjoerg                                       Array, "llvm.global.annotations");
24667330f729Sjoerg   gv->setSection(AnnotationSection);
24677330f729Sjoerg }
24687330f729Sjoerg 
EmitAnnotationString(StringRef Str)24697330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
24707330f729Sjoerg   llvm::Constant *&AStr = AnnotationStrings[Str];
24717330f729Sjoerg   if (AStr)
24727330f729Sjoerg     return AStr;
24737330f729Sjoerg 
24747330f729Sjoerg   // Not found yet, create a new global.
24757330f729Sjoerg   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
24767330f729Sjoerg   auto *gv =
24777330f729Sjoerg       new llvm::GlobalVariable(getModule(), s->getType(), true,
24787330f729Sjoerg                                llvm::GlobalValue::PrivateLinkage, s, ".str");
24797330f729Sjoerg   gv->setSection(AnnotationSection);
24807330f729Sjoerg   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
24817330f729Sjoerg   AStr = gv;
24827330f729Sjoerg   return gv;
24837330f729Sjoerg }
24847330f729Sjoerg 
EmitAnnotationUnit(SourceLocation Loc)24857330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
24867330f729Sjoerg   SourceManager &SM = getContext().getSourceManager();
24877330f729Sjoerg   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
24887330f729Sjoerg   if (PLoc.isValid())
24897330f729Sjoerg     return EmitAnnotationString(PLoc.getFilename());
24907330f729Sjoerg   return EmitAnnotationString(SM.getBufferName(Loc));
24917330f729Sjoerg }
24927330f729Sjoerg 
EmitAnnotationLineNo(SourceLocation L)24937330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
24947330f729Sjoerg   SourceManager &SM = getContext().getSourceManager();
24957330f729Sjoerg   PresumedLoc PLoc = SM.getPresumedLoc(L);
24967330f729Sjoerg   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
24977330f729Sjoerg     SM.getExpansionLineNumber(L);
24987330f729Sjoerg   return llvm::ConstantInt::get(Int32Ty, LineNo);
24997330f729Sjoerg }
25007330f729Sjoerg 
EmitAnnotationArgs(const AnnotateAttr * Attr)2501*e038c9c4Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2502*e038c9c4Sjoerg   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2503*e038c9c4Sjoerg   if (Exprs.empty())
2504*e038c9c4Sjoerg     return llvm::ConstantPointerNull::get(Int8PtrTy);
2505*e038c9c4Sjoerg 
2506*e038c9c4Sjoerg   llvm::FoldingSetNodeID ID;
2507*e038c9c4Sjoerg   for (Expr *E : Exprs) {
2508*e038c9c4Sjoerg     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2509*e038c9c4Sjoerg   }
2510*e038c9c4Sjoerg   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2511*e038c9c4Sjoerg   if (Lookup)
2512*e038c9c4Sjoerg     return Lookup;
2513*e038c9c4Sjoerg 
2514*e038c9c4Sjoerg   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2515*e038c9c4Sjoerg   LLVMArgs.reserve(Exprs.size());
2516*e038c9c4Sjoerg   ConstantEmitter ConstEmiter(*this);
2517*e038c9c4Sjoerg   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2518*e038c9c4Sjoerg     const auto *CE = cast<clang::ConstantExpr>(E);
2519*e038c9c4Sjoerg     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2520*e038c9c4Sjoerg                                     CE->getType());
2521*e038c9c4Sjoerg   });
2522*e038c9c4Sjoerg   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2523*e038c9c4Sjoerg   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2524*e038c9c4Sjoerg                                       llvm::GlobalValue::PrivateLinkage, Struct,
2525*e038c9c4Sjoerg                                       ".args");
2526*e038c9c4Sjoerg   GV->setSection(AnnotationSection);
2527*e038c9c4Sjoerg   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2528*e038c9c4Sjoerg   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
2529*e038c9c4Sjoerg 
2530*e038c9c4Sjoerg   Lookup = Bitcasted;
2531*e038c9c4Sjoerg   return Bitcasted;
2532*e038c9c4Sjoerg }
2533*e038c9c4Sjoerg 
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)25347330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
25357330f729Sjoerg                                                 const AnnotateAttr *AA,
25367330f729Sjoerg                                                 SourceLocation L) {
25377330f729Sjoerg   // Get the globals for file name, annotation, and the line number.
25387330f729Sjoerg   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
25397330f729Sjoerg                  *UnitGV = EmitAnnotationUnit(L),
2540*e038c9c4Sjoerg                  *LineNoCst = EmitAnnotationLineNo(L),
2541*e038c9c4Sjoerg                  *Args = EmitAnnotationArgs(AA);
2542*e038c9c4Sjoerg 
2543*e038c9c4Sjoerg   llvm::Constant *ASZeroGV = GV;
2544*e038c9c4Sjoerg   if (GV->getAddressSpace() != 0) {
2545*e038c9c4Sjoerg     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2546*e038c9c4Sjoerg                    GV, GV->getValueType()->getPointerTo(0));
2547*e038c9c4Sjoerg   }
25487330f729Sjoerg 
25497330f729Sjoerg   // Create the ConstantStruct for the global annotation.
2550*e038c9c4Sjoerg   llvm::Constant *Fields[] = {
2551*e038c9c4Sjoerg       llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
25527330f729Sjoerg       llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
25537330f729Sjoerg       llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2554*e038c9c4Sjoerg       LineNoCst,
2555*e038c9c4Sjoerg       Args,
25567330f729Sjoerg   };
25577330f729Sjoerg   return llvm::ConstantStruct::getAnon(Fields);
25587330f729Sjoerg }
25597330f729Sjoerg 
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)25607330f729Sjoerg void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
25617330f729Sjoerg                                          llvm::GlobalValue *GV) {
25627330f729Sjoerg   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
25637330f729Sjoerg   // Get the struct elements for these annotations.
25647330f729Sjoerg   for (const auto *I : D->specific_attrs<AnnotateAttr>())
25657330f729Sjoerg     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
25667330f729Sjoerg }
25677330f729Sjoerg 
isInNoSanitizeList(SanitizerMask Kind,llvm::Function * Fn,SourceLocation Loc) const2568*e038c9c4Sjoerg bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
25697330f729Sjoerg                                        SourceLocation Loc) const {
2570*e038c9c4Sjoerg   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2571*e038c9c4Sjoerg   // NoSanitize by function name.
2572*e038c9c4Sjoerg   if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
25737330f729Sjoerg     return true;
2574*e038c9c4Sjoerg   // NoSanitize by location.
25757330f729Sjoerg   if (Loc.isValid())
2576*e038c9c4Sjoerg     return NoSanitizeL.containsLocation(Kind, Loc);
25777330f729Sjoerg   // If location is unknown, this may be a compiler-generated function. Assume
25787330f729Sjoerg   // it's located in the main file.
25797330f729Sjoerg   auto &SM = Context.getSourceManager();
25807330f729Sjoerg   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2581*e038c9c4Sjoerg     return NoSanitizeL.containsFile(Kind, MainFile->getName());
25827330f729Sjoerg   }
25837330f729Sjoerg   return false;
25847330f729Sjoerg }
25857330f729Sjoerg 
isInNoSanitizeList(llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const2586*e038c9c4Sjoerg bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
25877330f729Sjoerg                                        SourceLocation Loc, QualType Ty,
25887330f729Sjoerg                                        StringRef Category) const {
2589*e038c9c4Sjoerg   // For now globals can be ignored only in ASan and KASan.
25907330f729Sjoerg   const SanitizerMask EnabledAsanMask =
25917330f729Sjoerg       LangOpts.Sanitize.Mask &
25927330f729Sjoerg       (SanitizerKind::Address | SanitizerKind::KernelAddress |
25937330f729Sjoerg        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
25947330f729Sjoerg        SanitizerKind::MemTag);
25957330f729Sjoerg   if (!EnabledAsanMask)
25967330f729Sjoerg     return false;
2597*e038c9c4Sjoerg   const auto &NoSanitizeL = getContext().getNoSanitizeList();
2598*e038c9c4Sjoerg   if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
25997330f729Sjoerg     return true;
2600*e038c9c4Sjoerg   if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
26017330f729Sjoerg     return true;
26027330f729Sjoerg   // Check global type.
26037330f729Sjoerg   if (!Ty.isNull()) {
26047330f729Sjoerg     // Drill down the array types: if global variable of a fixed type is
2605*e038c9c4Sjoerg     // not sanitized, we also don't instrument arrays of them.
26067330f729Sjoerg     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
26077330f729Sjoerg       Ty = AT->getElementType();
26087330f729Sjoerg     Ty = Ty.getCanonicalType().getUnqualifiedType();
2609*e038c9c4Sjoerg     // Only record types (classes, structs etc.) are ignored.
26107330f729Sjoerg     if (Ty->isRecordType()) {
26117330f729Sjoerg       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2612*e038c9c4Sjoerg       if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
26137330f729Sjoerg         return true;
26147330f729Sjoerg     }
26157330f729Sjoerg   }
26167330f729Sjoerg   return false;
26177330f729Sjoerg }
26187330f729Sjoerg 
imbueXRayAttrs(llvm::Function * Fn,SourceLocation Loc,StringRef Category) const26197330f729Sjoerg bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
26207330f729Sjoerg                                    StringRef Category) const {
26217330f729Sjoerg   const auto &XRayFilter = getContext().getXRayFilter();
26227330f729Sjoerg   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
26237330f729Sjoerg   auto Attr = ImbueAttr::NONE;
26247330f729Sjoerg   if (Loc.isValid())
26257330f729Sjoerg     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
26267330f729Sjoerg   if (Attr == ImbueAttr::NONE)
26277330f729Sjoerg     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
26287330f729Sjoerg   switch (Attr) {
26297330f729Sjoerg   case ImbueAttr::NONE:
26307330f729Sjoerg     return false;
26317330f729Sjoerg   case ImbueAttr::ALWAYS:
26327330f729Sjoerg     Fn->addFnAttr("function-instrument", "xray-always");
26337330f729Sjoerg     break;
26347330f729Sjoerg   case ImbueAttr::ALWAYS_ARG1:
26357330f729Sjoerg     Fn->addFnAttr("function-instrument", "xray-always");
26367330f729Sjoerg     Fn->addFnAttr("xray-log-args", "1");
26377330f729Sjoerg     break;
26387330f729Sjoerg   case ImbueAttr::NEVER:
26397330f729Sjoerg     Fn->addFnAttr("function-instrument", "xray-never");
26407330f729Sjoerg     break;
26417330f729Sjoerg   }
26427330f729Sjoerg   return true;
26437330f729Sjoerg }
26447330f729Sjoerg 
isProfileInstrExcluded(llvm::Function * Fn,SourceLocation Loc) const2645*e038c9c4Sjoerg bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2646*e038c9c4Sjoerg                                            SourceLocation Loc) const {
2647*e038c9c4Sjoerg   const auto &ProfileList = getContext().getProfileList();
2648*e038c9c4Sjoerg   // If the profile list is empty, then instrument everything.
2649*e038c9c4Sjoerg   if (ProfileList.isEmpty())
2650*e038c9c4Sjoerg     return false;
2651*e038c9c4Sjoerg   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2652*e038c9c4Sjoerg   // First, check the function name.
2653*e038c9c4Sjoerg   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2654*e038c9c4Sjoerg   if (V.hasValue())
2655*e038c9c4Sjoerg     return *V;
2656*e038c9c4Sjoerg   // Next, check the source location.
2657*e038c9c4Sjoerg   if (Loc.isValid()) {
2658*e038c9c4Sjoerg     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2659*e038c9c4Sjoerg     if (V.hasValue())
2660*e038c9c4Sjoerg       return *V;
2661*e038c9c4Sjoerg   }
2662*e038c9c4Sjoerg   // If location is unknown, this may be a compiler-generated function. Assume
2663*e038c9c4Sjoerg   // it's located in the main file.
2664*e038c9c4Sjoerg   auto &SM = Context.getSourceManager();
2665*e038c9c4Sjoerg   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2666*e038c9c4Sjoerg     Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2667*e038c9c4Sjoerg     if (V.hasValue())
2668*e038c9c4Sjoerg       return *V;
2669*e038c9c4Sjoerg   }
2670*e038c9c4Sjoerg   return ProfileList.getDefault();
2671*e038c9c4Sjoerg }
2672*e038c9c4Sjoerg 
MustBeEmitted(const ValueDecl * Global)26737330f729Sjoerg bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
26747330f729Sjoerg   // Never defer when EmitAllDecls is specified.
26757330f729Sjoerg   if (LangOpts.EmitAllDecls)
26767330f729Sjoerg     return true;
26777330f729Sjoerg 
26787330f729Sjoerg   if (CodeGenOpts.KeepStaticConsts) {
26797330f729Sjoerg     const auto *VD = dyn_cast<VarDecl>(Global);
26807330f729Sjoerg     if (VD && VD->getType().isConstQualified() &&
26817330f729Sjoerg         VD->getStorageDuration() == SD_Static)
26827330f729Sjoerg       return true;
26837330f729Sjoerg   }
26847330f729Sjoerg 
26857330f729Sjoerg   return getContext().DeclMustBeEmitted(Global);
26867330f729Sjoerg }
26877330f729Sjoerg 
MayBeEmittedEagerly(const ValueDecl * Global)26887330f729Sjoerg bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2689*e038c9c4Sjoerg   // In OpenMP 5.0 variables and function may be marked as
2690*e038c9c4Sjoerg   // device_type(host/nohost) and we should not emit them eagerly unless we sure
2691*e038c9c4Sjoerg   // that they must be emitted on the host/device. To be sure we need to have
2692*e038c9c4Sjoerg   // seen a declare target with an explicit mentioning of the function, we know
2693*e038c9c4Sjoerg   // we have if the level of the declare target attribute is -1. Note that we
2694*e038c9c4Sjoerg   // check somewhere else if we should emit this at all.
2695*e038c9c4Sjoerg   if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) {
2696*e038c9c4Sjoerg     llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
2697*e038c9c4Sjoerg         OMPDeclareTargetDeclAttr::getActiveAttr(Global);
2698*e038c9c4Sjoerg     if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1)
2699*e038c9c4Sjoerg       return false;
2700*e038c9c4Sjoerg   }
2701*e038c9c4Sjoerg 
27027330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
27037330f729Sjoerg     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
27047330f729Sjoerg       // Implicit template instantiations may change linkage if they are later
27057330f729Sjoerg       // explicitly instantiated, so they should not be emitted eagerly.
27067330f729Sjoerg       return false;
27077330f729Sjoerg   }
27087330f729Sjoerg   if (const auto *VD = dyn_cast<VarDecl>(Global))
27097330f729Sjoerg     if (Context.getInlineVariableDefinitionKind(VD) ==
27107330f729Sjoerg         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
27117330f729Sjoerg       // A definition of an inline constexpr static data member may change
27127330f729Sjoerg       // linkage later if it's redeclared outside the class.
27137330f729Sjoerg       return false;
27147330f729Sjoerg   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
27157330f729Sjoerg   // codegen for global variables, because they may be marked as threadprivate.
27167330f729Sjoerg   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
27177330f729Sjoerg       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
27187330f729Sjoerg       !isTypeConstant(Global->getType(), false) &&
27197330f729Sjoerg       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
27207330f729Sjoerg     return false;
27217330f729Sjoerg 
27227330f729Sjoerg   return true;
27237330f729Sjoerg }
27247330f729Sjoerg 
GetAddrOfMSGuidDecl(const MSGuidDecl * GD)2725*e038c9c4Sjoerg ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2726*e038c9c4Sjoerg   StringRef Name = getMangledName(GD);
27277330f729Sjoerg 
27287330f729Sjoerg   // The UUID descriptor should be pointer aligned.
27297330f729Sjoerg   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
27307330f729Sjoerg 
27317330f729Sjoerg   // Look for an existing global.
27327330f729Sjoerg   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
27337330f729Sjoerg     return ConstantAddress(GV, Alignment);
27347330f729Sjoerg 
2735*e038c9c4Sjoerg   ConstantEmitter Emitter(*this);
2736*e038c9c4Sjoerg   llvm::Constant *Init;
2737*e038c9c4Sjoerg 
2738*e038c9c4Sjoerg   APValue &V = GD->getAsAPValue();
2739*e038c9c4Sjoerg   if (!V.isAbsent()) {
2740*e038c9c4Sjoerg     // If possible, emit the APValue version of the initializer. In particular,
2741*e038c9c4Sjoerg     // this gets the type of the constant right.
2742*e038c9c4Sjoerg     Init = Emitter.emitForInitializer(
2743*e038c9c4Sjoerg         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2744*e038c9c4Sjoerg   } else {
2745*e038c9c4Sjoerg     // As a fallback, directly construct the constant.
2746*e038c9c4Sjoerg     // FIXME: This may get padding wrong under esoteric struct layout rules.
2747*e038c9c4Sjoerg     // MSVC appears to create a complete type 'struct __s_GUID' that it
2748*e038c9c4Sjoerg     // presumably uses to represent these constants.
2749*e038c9c4Sjoerg     MSGuidDecl::Parts Parts = GD->getParts();
2750*e038c9c4Sjoerg     llvm::Constant *Fields[4] = {
2751*e038c9c4Sjoerg         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2752*e038c9c4Sjoerg         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2753*e038c9c4Sjoerg         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2754*e038c9c4Sjoerg         llvm::ConstantDataArray::getRaw(
2755*e038c9c4Sjoerg             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2756*e038c9c4Sjoerg             Int8Ty)};
2757*e038c9c4Sjoerg     Init = llvm::ConstantStruct::getAnon(Fields);
2758*e038c9c4Sjoerg   }
27597330f729Sjoerg 
27607330f729Sjoerg   auto *GV = new llvm::GlobalVariable(
27617330f729Sjoerg       getModule(), Init->getType(),
27627330f729Sjoerg       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
27637330f729Sjoerg   if (supportsCOMDAT())
27647330f729Sjoerg     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
27657330f729Sjoerg   setDSOLocal(GV);
2766*e038c9c4Sjoerg 
2767*e038c9c4Sjoerg   llvm::Constant *Addr = GV;
2768*e038c9c4Sjoerg   if (!V.isAbsent()) {
2769*e038c9c4Sjoerg     Emitter.finalize(GV);
2770*e038c9c4Sjoerg   } else {
2771*e038c9c4Sjoerg     llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2772*e038c9c4Sjoerg     Addr = llvm::ConstantExpr::getBitCast(
2773*e038c9c4Sjoerg         GV, Ty->getPointerTo(GV->getAddressSpace()));
2774*e038c9c4Sjoerg   }
2775*e038c9c4Sjoerg   return ConstantAddress(Addr, Alignment);
2776*e038c9c4Sjoerg }
2777*e038c9c4Sjoerg 
GetAddrOfTemplateParamObject(const TemplateParamObjectDecl * TPO)2778*e038c9c4Sjoerg ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2779*e038c9c4Sjoerg     const TemplateParamObjectDecl *TPO) {
2780*e038c9c4Sjoerg   StringRef Name = getMangledName(TPO);
2781*e038c9c4Sjoerg   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2782*e038c9c4Sjoerg 
2783*e038c9c4Sjoerg   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2784*e038c9c4Sjoerg     return ConstantAddress(GV, Alignment);
2785*e038c9c4Sjoerg 
2786*e038c9c4Sjoerg   ConstantEmitter Emitter(*this);
2787*e038c9c4Sjoerg   llvm::Constant *Init = Emitter.emitForInitializer(
2788*e038c9c4Sjoerg         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2789*e038c9c4Sjoerg 
2790*e038c9c4Sjoerg   if (!Init) {
2791*e038c9c4Sjoerg     ErrorUnsupported(TPO, "template parameter object");
2792*e038c9c4Sjoerg     return ConstantAddress::invalid();
2793*e038c9c4Sjoerg   }
2794*e038c9c4Sjoerg 
2795*e038c9c4Sjoerg   auto *GV = new llvm::GlobalVariable(
2796*e038c9c4Sjoerg       getModule(), Init->getType(),
2797*e038c9c4Sjoerg       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2798*e038c9c4Sjoerg   if (supportsCOMDAT())
2799*e038c9c4Sjoerg     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2800*e038c9c4Sjoerg   Emitter.finalize(GV);
2801*e038c9c4Sjoerg 
28027330f729Sjoerg   return ConstantAddress(GV, Alignment);
28037330f729Sjoerg }
28047330f729Sjoerg 
GetWeakRefReference(const ValueDecl * VD)28057330f729Sjoerg ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
28067330f729Sjoerg   const AliasAttr *AA = VD->getAttr<AliasAttr>();
28077330f729Sjoerg   assert(AA && "No alias?");
28087330f729Sjoerg 
28097330f729Sjoerg   CharUnits Alignment = getContext().getDeclAlign(VD);
28107330f729Sjoerg   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
28117330f729Sjoerg 
28127330f729Sjoerg   // See if there is already something with the target's name in the module.
28137330f729Sjoerg   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
28147330f729Sjoerg   if (Entry) {
28157330f729Sjoerg     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
28167330f729Sjoerg     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
28177330f729Sjoerg     return ConstantAddress(Ptr, Alignment);
28187330f729Sjoerg   }
28197330f729Sjoerg 
28207330f729Sjoerg   llvm::Constant *Aliasee;
28217330f729Sjoerg   if (isa<llvm::FunctionType>(DeclTy))
28227330f729Sjoerg     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
28237330f729Sjoerg                                       GlobalDecl(cast<FunctionDecl>(VD)),
28247330f729Sjoerg                                       /*ForVTable=*/false);
28257330f729Sjoerg   else
2826*e038c9c4Sjoerg     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0, nullptr);
28277330f729Sjoerg 
28287330f729Sjoerg   auto *F = cast<llvm::GlobalValue>(Aliasee);
28297330f729Sjoerg   F->setLinkage(llvm::Function::ExternalWeakLinkage);
28307330f729Sjoerg   WeakRefReferences.insert(F);
28317330f729Sjoerg 
28327330f729Sjoerg   return ConstantAddress(Aliasee, Alignment);
28337330f729Sjoerg }
28347330f729Sjoerg 
EmitGlobal(GlobalDecl GD)28357330f729Sjoerg void CodeGenModule::EmitGlobal(GlobalDecl GD) {
28367330f729Sjoerg   const auto *Global = cast<ValueDecl>(GD.getDecl());
28377330f729Sjoerg 
28387330f729Sjoerg   // Weak references don't produce any output by themselves.
28397330f729Sjoerg   if (Global->hasAttr<WeakRefAttr>())
28407330f729Sjoerg     return;
28417330f729Sjoerg 
28427330f729Sjoerg   // If this is an alias definition (which otherwise looks like a declaration)
28437330f729Sjoerg   // emit it now.
28447330f729Sjoerg   if (Global->hasAttr<AliasAttr>())
28457330f729Sjoerg     return EmitAliasDefinition(GD);
28467330f729Sjoerg 
28477330f729Sjoerg   // IFunc like an alias whose value is resolved at runtime by calling resolver.
28487330f729Sjoerg   if (Global->hasAttr<IFuncAttr>())
28497330f729Sjoerg     return emitIFuncDefinition(GD);
28507330f729Sjoerg 
28517330f729Sjoerg   // If this is a cpu_dispatch multiversion function, emit the resolver.
28527330f729Sjoerg   if (Global->hasAttr<CPUDispatchAttr>())
28537330f729Sjoerg     return emitCPUDispatchDefinition(GD);
28547330f729Sjoerg 
28557330f729Sjoerg   // If this is CUDA, be selective about which declarations we emit.
28567330f729Sjoerg   if (LangOpts.CUDA) {
28577330f729Sjoerg     if (LangOpts.CUDAIsDevice) {
28587330f729Sjoerg       if (!Global->hasAttr<CUDADeviceAttr>() &&
28597330f729Sjoerg           !Global->hasAttr<CUDAGlobalAttr>() &&
28607330f729Sjoerg           !Global->hasAttr<CUDAConstantAttr>() &&
28617330f729Sjoerg           !Global->hasAttr<CUDASharedAttr>() &&
2862*e038c9c4Sjoerg           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2863*e038c9c4Sjoerg           !Global->getType()->isCUDADeviceBuiltinTextureType())
28647330f729Sjoerg         return;
28657330f729Sjoerg     } else {
28667330f729Sjoerg       // We need to emit host-side 'shadows' for all global
28677330f729Sjoerg       // device-side variables because the CUDA runtime needs their
28687330f729Sjoerg       // size and host-side address in order to provide access to
28697330f729Sjoerg       // their device-side incarnations.
28707330f729Sjoerg 
28717330f729Sjoerg       // So device-only functions are the only things we skip.
28727330f729Sjoerg       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
28737330f729Sjoerg           Global->hasAttr<CUDADeviceAttr>())
28747330f729Sjoerg         return;
28757330f729Sjoerg 
28767330f729Sjoerg       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
28777330f729Sjoerg              "Expected Variable or Function");
28787330f729Sjoerg     }
28797330f729Sjoerg   }
28807330f729Sjoerg 
28817330f729Sjoerg   if (LangOpts.OpenMP) {
28827330f729Sjoerg     // If this is OpenMP, check if it is legal to emit this global normally.
28837330f729Sjoerg     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
28847330f729Sjoerg       return;
28857330f729Sjoerg     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
28867330f729Sjoerg       if (MustBeEmitted(Global))
28877330f729Sjoerg         EmitOMPDeclareReduction(DRD);
28887330f729Sjoerg       return;
28897330f729Sjoerg     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
28907330f729Sjoerg       if (MustBeEmitted(Global))
28917330f729Sjoerg         EmitOMPDeclareMapper(DMD);
28927330f729Sjoerg       return;
28937330f729Sjoerg     }
28947330f729Sjoerg   }
28957330f729Sjoerg 
28967330f729Sjoerg   // Ignore declarations, they will be emitted on their first use.
28977330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
28987330f729Sjoerg     // Forward declarations are emitted lazily on first use.
28997330f729Sjoerg     if (!FD->doesThisDeclarationHaveABody()) {
29007330f729Sjoerg       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
29017330f729Sjoerg         return;
29027330f729Sjoerg 
29037330f729Sjoerg       StringRef MangledName = getMangledName(GD);
29047330f729Sjoerg 
29057330f729Sjoerg       // Compute the function info and LLVM type.
29067330f729Sjoerg       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
29077330f729Sjoerg       llvm::Type *Ty = getTypes().GetFunctionType(FI);
29087330f729Sjoerg 
29097330f729Sjoerg       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
29107330f729Sjoerg                               /*DontDefer=*/false);
29117330f729Sjoerg       return;
29127330f729Sjoerg     }
29137330f729Sjoerg   } else {
29147330f729Sjoerg     const auto *VD = cast<VarDecl>(Global);
29157330f729Sjoerg     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
29167330f729Sjoerg     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
29177330f729Sjoerg         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
29187330f729Sjoerg       if (LangOpts.OpenMP) {
29197330f729Sjoerg         // Emit declaration of the must-be-emitted declare target variable.
29207330f729Sjoerg         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
29217330f729Sjoerg                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
29227330f729Sjoerg           bool UnifiedMemoryEnabled =
29237330f729Sjoerg               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
29247330f729Sjoerg           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
29257330f729Sjoerg               !UnifiedMemoryEnabled) {
29267330f729Sjoerg             (void)GetAddrOfGlobalVar(VD);
29277330f729Sjoerg           } else {
29287330f729Sjoerg             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
29297330f729Sjoerg                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
29307330f729Sjoerg                      UnifiedMemoryEnabled)) &&
29317330f729Sjoerg                    "Link clause or to clause with unified memory expected.");
29327330f729Sjoerg             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
29337330f729Sjoerg           }
29347330f729Sjoerg 
29357330f729Sjoerg           return;
29367330f729Sjoerg         }
29377330f729Sjoerg       }
29387330f729Sjoerg       // If this declaration may have caused an inline variable definition to
29397330f729Sjoerg       // change linkage, make sure that it's emitted.
29407330f729Sjoerg       if (Context.getInlineVariableDefinitionKind(VD) ==
29417330f729Sjoerg           ASTContext::InlineVariableDefinitionKind::Strong)
29427330f729Sjoerg         GetAddrOfGlobalVar(VD);
29437330f729Sjoerg       return;
29447330f729Sjoerg     }
29457330f729Sjoerg   }
29467330f729Sjoerg 
29477330f729Sjoerg   // Defer code generation to first use when possible, e.g. if this is an inline
29487330f729Sjoerg   // function. If the global must always be emitted, do it eagerly if possible
29497330f729Sjoerg   // to benefit from cache locality.
29507330f729Sjoerg   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
29517330f729Sjoerg     // Emit the definition if it can't be deferred.
29527330f729Sjoerg     EmitGlobalDefinition(GD);
29537330f729Sjoerg     return;
29547330f729Sjoerg   }
29557330f729Sjoerg 
29567330f729Sjoerg   // If we're deferring emission of a C++ variable with an
29577330f729Sjoerg   // initializer, remember the order in which it appeared in the file.
29587330f729Sjoerg   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
29597330f729Sjoerg       cast<VarDecl>(Global)->hasInit()) {
29607330f729Sjoerg     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
29617330f729Sjoerg     CXXGlobalInits.push_back(nullptr);
29627330f729Sjoerg   }
29637330f729Sjoerg 
29647330f729Sjoerg   StringRef MangledName = getMangledName(GD);
29657330f729Sjoerg   if (GetGlobalValue(MangledName) != nullptr) {
29667330f729Sjoerg     // The value has already been used and should therefore be emitted.
29677330f729Sjoerg     addDeferredDeclToEmit(GD);
29687330f729Sjoerg   } else if (MustBeEmitted(Global)) {
29697330f729Sjoerg     // The value must be emitted, but cannot be emitted eagerly.
29707330f729Sjoerg     assert(!MayBeEmittedEagerly(Global));
29717330f729Sjoerg     addDeferredDeclToEmit(GD);
29727330f729Sjoerg   } else {
29737330f729Sjoerg     // Otherwise, remember that we saw a deferred decl with this name.  The
29747330f729Sjoerg     // first use of the mangled name will cause it to move into
29757330f729Sjoerg     // DeferredDeclsToEmit.
29767330f729Sjoerg     DeferredDecls[MangledName] = GD;
29777330f729Sjoerg   }
29787330f729Sjoerg }
29797330f729Sjoerg 
29807330f729Sjoerg // Check if T is a class type with a destructor that's not dllimport.
HasNonDllImportDtor(QualType T)29817330f729Sjoerg static bool HasNonDllImportDtor(QualType T) {
29827330f729Sjoerg   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
29837330f729Sjoerg     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
29847330f729Sjoerg       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
29857330f729Sjoerg         return true;
29867330f729Sjoerg 
29877330f729Sjoerg   return false;
29887330f729Sjoerg }
29897330f729Sjoerg 
29907330f729Sjoerg namespace {
29917330f729Sjoerg   struct FunctionIsDirectlyRecursive
29927330f729Sjoerg       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
29937330f729Sjoerg     const StringRef Name;
29947330f729Sjoerg     const Builtin::Context &BI;
FunctionIsDirectlyRecursive__anon06bf6b040811::FunctionIsDirectlyRecursive29957330f729Sjoerg     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
29967330f729Sjoerg         : Name(N), BI(C) {}
29977330f729Sjoerg 
VisitCallExpr__anon06bf6b040811::FunctionIsDirectlyRecursive29987330f729Sjoerg     bool VisitCallExpr(const CallExpr *E) {
29997330f729Sjoerg       const FunctionDecl *FD = E->getDirectCallee();
30007330f729Sjoerg       if (!FD)
30017330f729Sjoerg         return false;
30027330f729Sjoerg       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
30037330f729Sjoerg       if (Attr && Name == Attr->getLabel())
30047330f729Sjoerg         return true;
30057330f729Sjoerg       unsigned BuiltinID = FD->getBuiltinID();
30067330f729Sjoerg       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
30077330f729Sjoerg         return false;
30087330f729Sjoerg       StringRef BuiltinName = BI.getName(BuiltinID);
30097330f729Sjoerg       if (BuiltinName.startswith("__builtin_") &&
30107330f729Sjoerg           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
30117330f729Sjoerg         return true;
30127330f729Sjoerg       }
30137330f729Sjoerg       return false;
30147330f729Sjoerg     }
30157330f729Sjoerg 
VisitStmt__anon06bf6b040811::FunctionIsDirectlyRecursive30167330f729Sjoerg     bool VisitStmt(const Stmt *S) {
30177330f729Sjoerg       for (const Stmt *Child : S->children())
30187330f729Sjoerg         if (Child && this->Visit(Child))
30197330f729Sjoerg           return true;
30207330f729Sjoerg       return false;
30217330f729Sjoerg     }
30227330f729Sjoerg   };
30237330f729Sjoerg 
30247330f729Sjoerg   // Make sure we're not referencing non-imported vars or functions.
30257330f729Sjoerg   struct DLLImportFunctionVisitor
30267330f729Sjoerg       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
30277330f729Sjoerg     bool SafeToInline = true;
30287330f729Sjoerg 
shouldVisitImplicitCode__anon06bf6b040811::DLLImportFunctionVisitor30297330f729Sjoerg     bool shouldVisitImplicitCode() const { return true; }
30307330f729Sjoerg 
VisitVarDecl__anon06bf6b040811::DLLImportFunctionVisitor30317330f729Sjoerg     bool VisitVarDecl(VarDecl *VD) {
30327330f729Sjoerg       if (VD->getTLSKind()) {
30337330f729Sjoerg         // A thread-local variable cannot be imported.
30347330f729Sjoerg         SafeToInline = false;
30357330f729Sjoerg         return SafeToInline;
30367330f729Sjoerg       }
30377330f729Sjoerg 
30387330f729Sjoerg       // A variable definition might imply a destructor call.
30397330f729Sjoerg       if (VD->isThisDeclarationADefinition())
30407330f729Sjoerg         SafeToInline = !HasNonDllImportDtor(VD->getType());
30417330f729Sjoerg 
30427330f729Sjoerg       return SafeToInline;
30437330f729Sjoerg     }
30447330f729Sjoerg 
VisitCXXBindTemporaryExpr__anon06bf6b040811::DLLImportFunctionVisitor30457330f729Sjoerg     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
30467330f729Sjoerg       if (const auto *D = E->getTemporary()->getDestructor())
30477330f729Sjoerg         SafeToInline = D->hasAttr<DLLImportAttr>();
30487330f729Sjoerg       return SafeToInline;
30497330f729Sjoerg     }
30507330f729Sjoerg 
VisitDeclRefExpr__anon06bf6b040811::DLLImportFunctionVisitor30517330f729Sjoerg     bool VisitDeclRefExpr(DeclRefExpr *E) {
30527330f729Sjoerg       ValueDecl *VD = E->getDecl();
30537330f729Sjoerg       if (isa<FunctionDecl>(VD))
30547330f729Sjoerg         SafeToInline = VD->hasAttr<DLLImportAttr>();
30557330f729Sjoerg       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
30567330f729Sjoerg         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
30577330f729Sjoerg       return SafeToInline;
30587330f729Sjoerg     }
30597330f729Sjoerg 
VisitCXXConstructExpr__anon06bf6b040811::DLLImportFunctionVisitor30607330f729Sjoerg     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
30617330f729Sjoerg       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
30627330f729Sjoerg       return SafeToInline;
30637330f729Sjoerg     }
30647330f729Sjoerg 
VisitCXXMemberCallExpr__anon06bf6b040811::DLLImportFunctionVisitor30657330f729Sjoerg     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
30667330f729Sjoerg       CXXMethodDecl *M = E->getMethodDecl();
30677330f729Sjoerg       if (!M) {
30687330f729Sjoerg         // Call through a pointer to member function. This is safe to inline.
30697330f729Sjoerg         SafeToInline = true;
30707330f729Sjoerg       } else {
30717330f729Sjoerg         SafeToInline = M->hasAttr<DLLImportAttr>();
30727330f729Sjoerg       }
30737330f729Sjoerg       return SafeToInline;
30747330f729Sjoerg     }
30757330f729Sjoerg 
VisitCXXDeleteExpr__anon06bf6b040811::DLLImportFunctionVisitor30767330f729Sjoerg     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
30777330f729Sjoerg       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
30787330f729Sjoerg       return SafeToInline;
30797330f729Sjoerg     }
30807330f729Sjoerg 
VisitCXXNewExpr__anon06bf6b040811::DLLImportFunctionVisitor30817330f729Sjoerg     bool VisitCXXNewExpr(CXXNewExpr *E) {
30827330f729Sjoerg       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
30837330f729Sjoerg       return SafeToInline;
30847330f729Sjoerg     }
30857330f729Sjoerg   };
30867330f729Sjoerg }
30877330f729Sjoerg 
30887330f729Sjoerg // isTriviallyRecursive - Check if this function calls another
30897330f729Sjoerg // decl that, because of the asm attribute or the other decl being a builtin,
30907330f729Sjoerg // ends up pointing to itself.
30917330f729Sjoerg bool
isTriviallyRecursive(const FunctionDecl * FD)30927330f729Sjoerg CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
30937330f729Sjoerg   StringRef Name;
30947330f729Sjoerg   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
30957330f729Sjoerg     // asm labels are a special kind of mangling we have to support.
30967330f729Sjoerg     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
30977330f729Sjoerg     if (!Attr)
30987330f729Sjoerg       return false;
30997330f729Sjoerg     Name = Attr->getLabel();
31007330f729Sjoerg   } else {
31017330f729Sjoerg     Name = FD->getName();
31027330f729Sjoerg   }
31037330f729Sjoerg 
31047330f729Sjoerg   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
31057330f729Sjoerg   const Stmt *Body = FD->getBody();
31067330f729Sjoerg   return Body ? Walker.Visit(Body) : false;
31077330f729Sjoerg }
31087330f729Sjoerg 
shouldEmitFunction(GlobalDecl GD)31097330f729Sjoerg bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
31107330f729Sjoerg   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
31117330f729Sjoerg     return true;
31127330f729Sjoerg   const auto *F = cast<FunctionDecl>(GD.getDecl());
31137330f729Sjoerg   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
31147330f729Sjoerg     return false;
31157330f729Sjoerg 
3116*e038c9c4Sjoerg   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
31177330f729Sjoerg     // Check whether it would be safe to inline this dllimport function.
31187330f729Sjoerg     DLLImportFunctionVisitor Visitor;
31197330f729Sjoerg     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
31207330f729Sjoerg     if (!Visitor.SafeToInline)
31217330f729Sjoerg       return false;
31227330f729Sjoerg 
31237330f729Sjoerg     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
31247330f729Sjoerg       // Implicit destructor invocations aren't captured in the AST, so the
31257330f729Sjoerg       // check above can't see them. Check for them manually here.
31267330f729Sjoerg       for (const Decl *Member : Dtor->getParent()->decls())
31277330f729Sjoerg         if (isa<FieldDecl>(Member))
31287330f729Sjoerg           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
31297330f729Sjoerg             return false;
31307330f729Sjoerg       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
31317330f729Sjoerg         if (HasNonDllImportDtor(B.getType()))
31327330f729Sjoerg           return false;
31337330f729Sjoerg     }
31347330f729Sjoerg   }
31357330f729Sjoerg 
31367330f729Sjoerg   // PR9614. Avoid cases where the source code is lying to us. An available
31377330f729Sjoerg   // externally function should have an equivalent function somewhere else,
3138*e038c9c4Sjoerg   // but a function that calls itself through asm label/`__builtin_` trickery is
3139*e038c9c4Sjoerg   // clearly not equivalent to the real implementation.
31407330f729Sjoerg   // This happens in glibc's btowc and in some configure checks.
31417330f729Sjoerg   return !isTriviallyRecursive(F);
31427330f729Sjoerg }
31437330f729Sjoerg 
shouldOpportunisticallyEmitVTables()31447330f729Sjoerg bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
31457330f729Sjoerg   return CodeGenOpts.OptimizationLevel > 0;
31467330f729Sjoerg }
31477330f729Sjoerg 
EmitMultiVersionFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)31487330f729Sjoerg void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
31497330f729Sjoerg                                                        llvm::GlobalValue *GV) {
31507330f729Sjoerg   const auto *FD = cast<FunctionDecl>(GD.getDecl());
31517330f729Sjoerg 
31527330f729Sjoerg   if (FD->isCPUSpecificMultiVersion()) {
31537330f729Sjoerg     auto *Spec = FD->getAttr<CPUSpecificAttr>();
31547330f729Sjoerg     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
31557330f729Sjoerg       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
31567330f729Sjoerg     // Requires multiple emits.
31577330f729Sjoerg   } else
31587330f729Sjoerg     EmitGlobalFunctionDefinition(GD, GV);
31597330f729Sjoerg }
31607330f729Sjoerg 
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)31617330f729Sjoerg void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
31627330f729Sjoerg   const auto *D = cast<ValueDecl>(GD.getDecl());
31637330f729Sjoerg 
31647330f729Sjoerg   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
31657330f729Sjoerg                                  Context.getSourceManager(),
31667330f729Sjoerg                                  "Generating code for declaration");
31677330f729Sjoerg 
31687330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
31697330f729Sjoerg     // At -O0, don't generate IR for functions with available_externally
31707330f729Sjoerg     // linkage.
31717330f729Sjoerg     if (!shouldEmitFunction(GD))
31727330f729Sjoerg       return;
31737330f729Sjoerg 
31747330f729Sjoerg     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
31757330f729Sjoerg       std::string Name;
31767330f729Sjoerg       llvm::raw_string_ostream OS(Name);
31777330f729Sjoerg       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
31787330f729Sjoerg                                /*Qualified=*/true);
31797330f729Sjoerg       return Name;
31807330f729Sjoerg     });
31817330f729Sjoerg 
31827330f729Sjoerg     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
31837330f729Sjoerg       // Make sure to emit the definition(s) before we emit the thunks.
31847330f729Sjoerg       // This is necessary for the generation of certain thunks.
31857330f729Sjoerg       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
31867330f729Sjoerg         ABI->emitCXXStructor(GD);
31877330f729Sjoerg       else if (FD->isMultiVersion())
31887330f729Sjoerg         EmitMultiVersionFunctionDefinition(GD, GV);
31897330f729Sjoerg       else
31907330f729Sjoerg         EmitGlobalFunctionDefinition(GD, GV);
31917330f729Sjoerg 
31927330f729Sjoerg       if (Method->isVirtual())
31937330f729Sjoerg         getVTables().EmitThunks(GD);
31947330f729Sjoerg 
31957330f729Sjoerg       return;
31967330f729Sjoerg     }
31977330f729Sjoerg 
31987330f729Sjoerg     if (FD->isMultiVersion())
31997330f729Sjoerg       return EmitMultiVersionFunctionDefinition(GD, GV);
32007330f729Sjoerg     return EmitGlobalFunctionDefinition(GD, GV);
32017330f729Sjoerg   }
32027330f729Sjoerg 
32037330f729Sjoerg   if (const auto *VD = dyn_cast<VarDecl>(D))
32047330f729Sjoerg     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
32057330f729Sjoerg 
32067330f729Sjoerg   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
32077330f729Sjoerg }
32087330f729Sjoerg 
32097330f729Sjoerg static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
32107330f729Sjoerg                                                       llvm::Function *NewFn);
32117330f729Sjoerg 
32127330f729Sjoerg static unsigned
TargetMVPriority(const TargetInfo & TI,const CodeGenFunction::MultiVersionResolverOption & RO)32137330f729Sjoerg TargetMVPriority(const TargetInfo &TI,
32147330f729Sjoerg                  const CodeGenFunction::MultiVersionResolverOption &RO) {
32157330f729Sjoerg   unsigned Priority = 0;
32167330f729Sjoerg   for (StringRef Feat : RO.Conditions.Features)
32177330f729Sjoerg     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
32187330f729Sjoerg 
32197330f729Sjoerg   if (!RO.Conditions.Architecture.empty())
32207330f729Sjoerg     Priority = std::max(
32217330f729Sjoerg         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
32227330f729Sjoerg   return Priority;
32237330f729Sjoerg }
32247330f729Sjoerg 
emitMultiVersionFunctions()32257330f729Sjoerg void CodeGenModule::emitMultiVersionFunctions() {
3226*e038c9c4Sjoerg   std::vector<GlobalDecl> MVFuncsToEmit;
3227*e038c9c4Sjoerg   MultiVersionFuncs.swap(MVFuncsToEmit);
3228*e038c9c4Sjoerg   for (GlobalDecl GD : MVFuncsToEmit) {
32297330f729Sjoerg     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
32307330f729Sjoerg     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
32317330f729Sjoerg     getContext().forEachMultiversionedFunctionVersion(
32327330f729Sjoerg         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
32337330f729Sjoerg           GlobalDecl CurGD{
32347330f729Sjoerg               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
32357330f729Sjoerg           StringRef MangledName = getMangledName(CurGD);
32367330f729Sjoerg           llvm::Constant *Func = GetGlobalValue(MangledName);
32377330f729Sjoerg           if (!Func) {
32387330f729Sjoerg             if (CurFD->isDefined()) {
32397330f729Sjoerg               EmitGlobalFunctionDefinition(CurGD, nullptr);
32407330f729Sjoerg               Func = GetGlobalValue(MangledName);
32417330f729Sjoerg             } else {
32427330f729Sjoerg               const CGFunctionInfo &FI =
32437330f729Sjoerg                   getTypes().arrangeGlobalDeclaration(GD);
32447330f729Sjoerg               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
32457330f729Sjoerg               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
32467330f729Sjoerg                                        /*DontDefer=*/false, ForDefinition);
32477330f729Sjoerg             }
32487330f729Sjoerg             assert(Func && "This should have just been created");
32497330f729Sjoerg           }
32507330f729Sjoerg 
32517330f729Sjoerg           const auto *TA = CurFD->getAttr<TargetAttr>();
32527330f729Sjoerg           llvm::SmallVector<StringRef, 8> Feats;
32537330f729Sjoerg           TA->getAddedFeatures(Feats);
32547330f729Sjoerg 
32557330f729Sjoerg           Options.emplace_back(cast<llvm::Function>(Func),
32567330f729Sjoerg                                TA->getArchitecture(), Feats);
32577330f729Sjoerg         });
32587330f729Sjoerg 
32597330f729Sjoerg     llvm::Function *ResolverFunc;
32607330f729Sjoerg     const TargetInfo &TI = getTarget();
32617330f729Sjoerg 
32627330f729Sjoerg     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
32637330f729Sjoerg       ResolverFunc = cast<llvm::Function>(
32647330f729Sjoerg           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
32657330f729Sjoerg       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
32667330f729Sjoerg     } else {
32677330f729Sjoerg       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
32687330f729Sjoerg     }
32697330f729Sjoerg 
32707330f729Sjoerg     if (supportsCOMDAT())
32717330f729Sjoerg       ResolverFunc->setComdat(
32727330f729Sjoerg           getModule().getOrInsertComdat(ResolverFunc->getName()));
32737330f729Sjoerg 
32747330f729Sjoerg     llvm::stable_sort(
32757330f729Sjoerg         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
32767330f729Sjoerg                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
32777330f729Sjoerg           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
32787330f729Sjoerg         });
32797330f729Sjoerg     CodeGenFunction CGF(*this);
32807330f729Sjoerg     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
32817330f729Sjoerg   }
3282*e038c9c4Sjoerg 
3283*e038c9c4Sjoerg   // Ensure that any additions to the deferred decls list caused by emitting a
3284*e038c9c4Sjoerg   // variant are emitted.  This can happen when the variant itself is inline and
3285*e038c9c4Sjoerg   // calls a function without linkage.
3286*e038c9c4Sjoerg   if (!MVFuncsToEmit.empty())
3287*e038c9c4Sjoerg     EmitDeferred();
3288*e038c9c4Sjoerg 
3289*e038c9c4Sjoerg   // Ensure that any additions to the multiversion funcs list from either the
3290*e038c9c4Sjoerg   // deferred decls or the multiversion functions themselves are emitted.
3291*e038c9c4Sjoerg   if (!MultiVersionFuncs.empty())
3292*e038c9c4Sjoerg     emitMultiVersionFunctions();
32937330f729Sjoerg }
32947330f729Sjoerg 
emitCPUDispatchDefinition(GlobalDecl GD)32957330f729Sjoerg void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
32967330f729Sjoerg   const auto *FD = cast<FunctionDecl>(GD.getDecl());
32977330f729Sjoerg   assert(FD && "Not a FunctionDecl?");
32987330f729Sjoerg   const auto *DD = FD->getAttr<CPUDispatchAttr>();
32997330f729Sjoerg   assert(DD && "Not a cpu_dispatch Function?");
33007330f729Sjoerg   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
33017330f729Sjoerg 
33027330f729Sjoerg   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
33037330f729Sjoerg     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
33047330f729Sjoerg     DeclTy = getTypes().GetFunctionType(FInfo);
33057330f729Sjoerg   }
33067330f729Sjoerg 
33077330f729Sjoerg   StringRef ResolverName = getMangledName(GD);
33087330f729Sjoerg 
33097330f729Sjoerg   llvm::Type *ResolverType;
33107330f729Sjoerg   GlobalDecl ResolverGD;
33117330f729Sjoerg   if (getTarget().supportsIFunc())
33127330f729Sjoerg     ResolverType = llvm::FunctionType::get(
33137330f729Sjoerg         llvm::PointerType::get(DeclTy,
33147330f729Sjoerg                                Context.getTargetAddressSpace(FD->getType())),
33157330f729Sjoerg         false);
33167330f729Sjoerg   else {
33177330f729Sjoerg     ResolverType = DeclTy;
33187330f729Sjoerg     ResolverGD = GD;
33197330f729Sjoerg   }
33207330f729Sjoerg 
33217330f729Sjoerg   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
33227330f729Sjoerg       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
33237330f729Sjoerg   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
33247330f729Sjoerg   if (supportsCOMDAT())
33257330f729Sjoerg     ResolverFunc->setComdat(
33267330f729Sjoerg         getModule().getOrInsertComdat(ResolverFunc->getName()));
33277330f729Sjoerg 
33287330f729Sjoerg   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
33297330f729Sjoerg   const TargetInfo &Target = getTarget();
33307330f729Sjoerg   unsigned Index = 0;
33317330f729Sjoerg   for (const IdentifierInfo *II : DD->cpus()) {
33327330f729Sjoerg     // Get the name of the target function so we can look it up/create it.
33337330f729Sjoerg     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
33347330f729Sjoerg                               getCPUSpecificMangling(*this, II->getName());
33357330f729Sjoerg 
33367330f729Sjoerg     llvm::Constant *Func = GetGlobalValue(MangledName);
33377330f729Sjoerg 
33387330f729Sjoerg     if (!Func) {
33397330f729Sjoerg       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
33407330f729Sjoerg       if (ExistingDecl.getDecl() &&
33417330f729Sjoerg           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
33427330f729Sjoerg         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
33437330f729Sjoerg         Func = GetGlobalValue(MangledName);
33447330f729Sjoerg       } else {
33457330f729Sjoerg         if (!ExistingDecl.getDecl())
33467330f729Sjoerg           ExistingDecl = GD.getWithMultiVersionIndex(Index);
33477330f729Sjoerg 
33487330f729Sjoerg       Func = GetOrCreateLLVMFunction(
33497330f729Sjoerg           MangledName, DeclTy, ExistingDecl,
33507330f729Sjoerg           /*ForVTable=*/false, /*DontDefer=*/true,
33517330f729Sjoerg           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
33527330f729Sjoerg       }
33537330f729Sjoerg     }
33547330f729Sjoerg 
33557330f729Sjoerg     llvm::SmallVector<StringRef, 32> Features;
33567330f729Sjoerg     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
33577330f729Sjoerg     llvm::transform(Features, Features.begin(),
33587330f729Sjoerg                     [](StringRef Str) { return Str.substr(1); });
33597330f729Sjoerg     Features.erase(std::remove_if(
33607330f729Sjoerg         Features.begin(), Features.end(), [&Target](StringRef Feat) {
33617330f729Sjoerg           return !Target.validateCpuSupports(Feat);
33627330f729Sjoerg         }), Features.end());
33637330f729Sjoerg     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
33647330f729Sjoerg     ++Index;
33657330f729Sjoerg   }
33667330f729Sjoerg 
3367*e038c9c4Sjoerg   llvm::stable_sort(
33687330f729Sjoerg       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
33697330f729Sjoerg                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
33707330f729Sjoerg         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
33717330f729Sjoerg                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
33727330f729Sjoerg       });
33737330f729Sjoerg 
33747330f729Sjoerg   // If the list contains multiple 'default' versions, such as when it contains
33757330f729Sjoerg   // 'pentium' and 'generic', don't emit the call to the generic one (since we
33767330f729Sjoerg   // always run on at least a 'pentium'). We do this by deleting the 'least
33777330f729Sjoerg   // advanced' (read, lowest mangling letter).
33787330f729Sjoerg   while (Options.size() > 1 &&
33797330f729Sjoerg          CodeGenFunction::GetX86CpuSupportsMask(
33807330f729Sjoerg              (Options.end() - 2)->Conditions.Features) == 0) {
33817330f729Sjoerg     StringRef LHSName = (Options.end() - 2)->Function->getName();
33827330f729Sjoerg     StringRef RHSName = (Options.end() - 1)->Function->getName();
33837330f729Sjoerg     if (LHSName.compare(RHSName) < 0)
33847330f729Sjoerg       Options.erase(Options.end() - 2);
33857330f729Sjoerg     else
33867330f729Sjoerg       Options.erase(Options.end() - 1);
33877330f729Sjoerg   }
33887330f729Sjoerg 
33897330f729Sjoerg   CodeGenFunction CGF(*this);
33907330f729Sjoerg   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
33917330f729Sjoerg 
33927330f729Sjoerg   if (getTarget().supportsIFunc()) {
33937330f729Sjoerg     std::string AliasName = getMangledNameImpl(
33947330f729Sjoerg         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
33957330f729Sjoerg     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
33967330f729Sjoerg     if (!AliasFunc) {
33977330f729Sjoerg       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
33987330f729Sjoerg           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
33997330f729Sjoerg           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
34007330f729Sjoerg       auto *GA = llvm::GlobalAlias::create(
34017330f729Sjoerg          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
34027330f729Sjoerg       GA->setLinkage(llvm::Function::WeakODRLinkage);
34037330f729Sjoerg       SetCommonAttributes(GD, GA);
34047330f729Sjoerg     }
34057330f729Sjoerg   }
34067330f729Sjoerg }
34077330f729Sjoerg 
34087330f729Sjoerg /// If a dispatcher for the specified mangled name is not in the module, create
34097330f729Sjoerg /// and return an llvm Function with the specified type.
GetOrCreateMultiVersionResolver(GlobalDecl GD,llvm::Type * DeclTy,const FunctionDecl * FD)34107330f729Sjoerg llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
34117330f729Sjoerg     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
34127330f729Sjoerg   std::string MangledName =
34137330f729Sjoerg       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
34147330f729Sjoerg 
34157330f729Sjoerg   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
34167330f729Sjoerg   // a separate resolver).
34177330f729Sjoerg   std::string ResolverName = MangledName;
34187330f729Sjoerg   if (getTarget().supportsIFunc())
34197330f729Sjoerg     ResolverName += ".ifunc";
34207330f729Sjoerg   else if (FD->isTargetMultiVersion())
34217330f729Sjoerg     ResolverName += ".resolver";
34227330f729Sjoerg 
34237330f729Sjoerg   // If this already exists, just return that one.
34247330f729Sjoerg   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
34257330f729Sjoerg     return ResolverGV;
34267330f729Sjoerg 
34277330f729Sjoerg   // Since this is the first time we've created this IFunc, make sure
34287330f729Sjoerg   // that we put this multiversioned function into the list to be
34297330f729Sjoerg   // replaced later if necessary (target multiversioning only).
34307330f729Sjoerg   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
34317330f729Sjoerg     MultiVersionFuncs.push_back(GD);
34327330f729Sjoerg 
34337330f729Sjoerg   if (getTarget().supportsIFunc()) {
34347330f729Sjoerg     llvm::Type *ResolverType = llvm::FunctionType::get(
34357330f729Sjoerg         llvm::PointerType::get(
34367330f729Sjoerg             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
34377330f729Sjoerg         false);
34387330f729Sjoerg     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
34397330f729Sjoerg         MangledName + ".resolver", ResolverType, GlobalDecl{},
34407330f729Sjoerg         /*ForVTable=*/false);
34417330f729Sjoerg     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
34427330f729Sjoerg         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
34437330f729Sjoerg     GIF->setName(ResolverName);
34447330f729Sjoerg     SetCommonAttributes(FD, GIF);
34457330f729Sjoerg 
34467330f729Sjoerg     return GIF;
34477330f729Sjoerg   }
34487330f729Sjoerg 
34497330f729Sjoerg   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
34507330f729Sjoerg       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
34517330f729Sjoerg   assert(isa<llvm::GlobalValue>(Resolver) &&
34527330f729Sjoerg          "Resolver should be created for the first time");
34537330f729Sjoerg   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
34547330f729Sjoerg   return Resolver;
34557330f729Sjoerg }
34567330f729Sjoerg 
34577330f729Sjoerg /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
34587330f729Sjoerg /// module, create and return an llvm Function with the specified type. If there
34597330f729Sjoerg /// is something in the module with the specified name, return it potentially
34607330f729Sjoerg /// bitcasted to the right type.
34617330f729Sjoerg ///
34627330f729Sjoerg /// If D is non-null, it specifies a decl that correspond to this.  This is used
34637330f729Sjoerg /// to set the attributes on the function when it is first created.
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeList ExtraAttrs,ForDefinition_t IsForDefinition)34647330f729Sjoerg llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
34657330f729Sjoerg     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
34667330f729Sjoerg     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
34677330f729Sjoerg     ForDefinition_t IsForDefinition) {
34687330f729Sjoerg   const Decl *D = GD.getDecl();
34697330f729Sjoerg 
34707330f729Sjoerg   // Any attempts to use a MultiVersion function should result in retrieving
34717330f729Sjoerg   // the iFunc instead. Name Mangling will handle the rest of the changes.
34727330f729Sjoerg   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
34737330f729Sjoerg     // For the device mark the function as one that should be emitted.
34747330f729Sjoerg     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
34757330f729Sjoerg         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
34767330f729Sjoerg         !DontDefer && !IsForDefinition) {
34777330f729Sjoerg       if (const FunctionDecl *FDDef = FD->getDefinition()) {
34787330f729Sjoerg         GlobalDecl GDDef;
34797330f729Sjoerg         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
34807330f729Sjoerg           GDDef = GlobalDecl(CD, GD.getCtorType());
34817330f729Sjoerg         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
34827330f729Sjoerg           GDDef = GlobalDecl(DD, GD.getDtorType());
34837330f729Sjoerg         else
34847330f729Sjoerg           GDDef = GlobalDecl(FDDef);
34857330f729Sjoerg         EmitGlobal(GDDef);
34867330f729Sjoerg       }
34877330f729Sjoerg     }
34887330f729Sjoerg 
34897330f729Sjoerg     if (FD->isMultiVersion()) {
3490*e038c9c4Sjoerg       if (FD->hasAttr<TargetAttr>())
34917330f729Sjoerg         UpdateMultiVersionNames(GD, FD);
34927330f729Sjoerg       if (!IsForDefinition)
34937330f729Sjoerg         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
34947330f729Sjoerg     }
34957330f729Sjoerg   }
34967330f729Sjoerg 
34977330f729Sjoerg   // Lookup the entry, lazily creating it if necessary.
34987330f729Sjoerg   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
34997330f729Sjoerg   if (Entry) {
35007330f729Sjoerg     if (WeakRefReferences.erase(Entry)) {
35017330f729Sjoerg       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
35027330f729Sjoerg       if (FD && !FD->hasAttr<WeakAttr>())
35037330f729Sjoerg         Entry->setLinkage(llvm::Function::ExternalLinkage);
35047330f729Sjoerg     }
35057330f729Sjoerg 
35067330f729Sjoerg     // Handle dropped DLL attributes.
35077330f729Sjoerg     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
35087330f729Sjoerg       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
35097330f729Sjoerg       setDSOLocal(Entry);
35107330f729Sjoerg     }
35117330f729Sjoerg 
35127330f729Sjoerg     // If there are two attempts to define the same mangled name, issue an
35137330f729Sjoerg     // error.
35147330f729Sjoerg     if (IsForDefinition && !Entry->isDeclaration()) {
35157330f729Sjoerg       GlobalDecl OtherGD;
35167330f729Sjoerg       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
35177330f729Sjoerg       // to make sure that we issue an error only once.
35187330f729Sjoerg       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
35197330f729Sjoerg           (GD.getCanonicalDecl().getDecl() !=
35207330f729Sjoerg            OtherGD.getCanonicalDecl().getDecl()) &&
35217330f729Sjoerg           DiagnosedConflictingDefinitions.insert(GD).second) {
35227330f729Sjoerg         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
35237330f729Sjoerg             << MangledName;
35247330f729Sjoerg         getDiags().Report(OtherGD.getDecl()->getLocation(),
35257330f729Sjoerg                           diag::note_previous_definition);
35267330f729Sjoerg       }
35277330f729Sjoerg     }
35287330f729Sjoerg 
35297330f729Sjoerg     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3530*e038c9c4Sjoerg         (Entry->getValueType() == Ty)) {
35317330f729Sjoerg       return Entry;
35327330f729Sjoerg     }
35337330f729Sjoerg 
35347330f729Sjoerg     // Make sure the result is of the correct type.
35357330f729Sjoerg     // (If function is requested for a definition, we always need to create a new
35367330f729Sjoerg     // function, not just return a bitcast.)
35377330f729Sjoerg     if (!IsForDefinition)
35387330f729Sjoerg       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
35397330f729Sjoerg   }
35407330f729Sjoerg 
35417330f729Sjoerg   // This function doesn't have a complete type (for example, the return
35427330f729Sjoerg   // type is an incomplete struct). Use a fake type instead, and make
35437330f729Sjoerg   // sure not to try to set attributes.
35447330f729Sjoerg   bool IsIncompleteFunction = false;
35457330f729Sjoerg 
35467330f729Sjoerg   llvm::FunctionType *FTy;
35477330f729Sjoerg   if (isa<llvm::FunctionType>(Ty)) {
35487330f729Sjoerg     FTy = cast<llvm::FunctionType>(Ty);
35497330f729Sjoerg   } else {
35507330f729Sjoerg     FTy = llvm::FunctionType::get(VoidTy, false);
35517330f729Sjoerg     IsIncompleteFunction = true;
35527330f729Sjoerg   }
35537330f729Sjoerg 
35547330f729Sjoerg   llvm::Function *F =
35557330f729Sjoerg       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
35567330f729Sjoerg                              Entry ? StringRef() : MangledName, &getModule());
35577330f729Sjoerg 
35587330f729Sjoerg   // If we already created a function with the same mangled name (but different
35597330f729Sjoerg   // type) before, take its name and add it to the list of functions to be
35607330f729Sjoerg   // replaced with F at the end of CodeGen.
35617330f729Sjoerg   //
35627330f729Sjoerg   // This happens if there is a prototype for a function (e.g. "int f()") and
35637330f729Sjoerg   // then a definition of a different type (e.g. "int f(int x)").
35647330f729Sjoerg   if (Entry) {
35657330f729Sjoerg     F->takeName(Entry);
35667330f729Sjoerg 
35677330f729Sjoerg     // This might be an implementation of a function without a prototype, in
35687330f729Sjoerg     // which case, try to do special replacement of calls which match the new
35697330f729Sjoerg     // prototype.  The really key thing here is that we also potentially drop
35707330f729Sjoerg     // arguments from the call site so as to make a direct call, which makes the
35717330f729Sjoerg     // inliner happier and suppresses a number of optimizer warnings (!) about
35727330f729Sjoerg     // dropping arguments.
35737330f729Sjoerg     if (!Entry->use_empty()) {
35747330f729Sjoerg       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
35757330f729Sjoerg       Entry->removeDeadConstantUsers();
35767330f729Sjoerg     }
35777330f729Sjoerg 
35787330f729Sjoerg     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3579*e038c9c4Sjoerg         F, Entry->getValueType()->getPointerTo());
35807330f729Sjoerg     addGlobalValReplacement(Entry, BC);
35817330f729Sjoerg   }
35827330f729Sjoerg 
35837330f729Sjoerg   assert(F->getName() == MangledName && "name was uniqued!");
35847330f729Sjoerg   if (D)
35857330f729Sjoerg     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
35867330f729Sjoerg   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
35877330f729Sjoerg     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
35887330f729Sjoerg     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
35897330f729Sjoerg   }
35907330f729Sjoerg 
35917330f729Sjoerg   if (!DontDefer) {
35927330f729Sjoerg     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
35937330f729Sjoerg     // each other bottoming out with the base dtor.  Therefore we emit non-base
35947330f729Sjoerg     // dtors on usage, even if there is no dtor definition in the TU.
35957330f729Sjoerg     if (D && isa<CXXDestructorDecl>(D) &&
35967330f729Sjoerg         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
35977330f729Sjoerg                                            GD.getDtorType()))
35987330f729Sjoerg       addDeferredDeclToEmit(GD);
35997330f729Sjoerg 
36007330f729Sjoerg     // This is the first use or definition of a mangled name.  If there is a
36017330f729Sjoerg     // deferred decl with this name, remember that we need to emit it at the end
36027330f729Sjoerg     // of the file.
36037330f729Sjoerg     auto DDI = DeferredDecls.find(MangledName);
36047330f729Sjoerg     if (DDI != DeferredDecls.end()) {
36057330f729Sjoerg       // Move the potentially referenced deferred decl to the
36067330f729Sjoerg       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
36077330f729Sjoerg       // don't need it anymore).
36087330f729Sjoerg       addDeferredDeclToEmit(DDI->second);
36097330f729Sjoerg       DeferredDecls.erase(DDI);
36107330f729Sjoerg 
36117330f729Sjoerg       // Otherwise, there are cases we have to worry about where we're
36127330f729Sjoerg       // using a declaration for which we must emit a definition but where
36137330f729Sjoerg       // we might not find a top-level definition:
36147330f729Sjoerg       //   - member functions defined inline in their classes
36157330f729Sjoerg       //   - friend functions defined inline in some class
36167330f729Sjoerg       //   - special member functions with implicit definitions
36177330f729Sjoerg       // If we ever change our AST traversal to walk into class methods,
36187330f729Sjoerg       // this will be unnecessary.
36197330f729Sjoerg       //
36207330f729Sjoerg       // We also don't emit a definition for a function if it's going to be an
36217330f729Sjoerg       // entry in a vtable, unless it's already marked as used.
36227330f729Sjoerg     } else if (getLangOpts().CPlusPlus && D) {
36237330f729Sjoerg       // Look for a declaration that's lexically in a record.
36247330f729Sjoerg       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
36257330f729Sjoerg            FD = FD->getPreviousDecl()) {
36267330f729Sjoerg         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
36277330f729Sjoerg           if (FD->doesThisDeclarationHaveABody()) {
36287330f729Sjoerg             addDeferredDeclToEmit(GD.getWithDecl(FD));
36297330f729Sjoerg             break;
36307330f729Sjoerg           }
36317330f729Sjoerg         }
36327330f729Sjoerg       }
36337330f729Sjoerg     }
36347330f729Sjoerg   }
36357330f729Sjoerg 
36367330f729Sjoerg   // Make sure the result is of the requested type.
36377330f729Sjoerg   if (!IsIncompleteFunction) {
3638*e038c9c4Sjoerg     assert(F->getFunctionType() == Ty);
36397330f729Sjoerg     return F;
36407330f729Sjoerg   }
36417330f729Sjoerg 
36427330f729Sjoerg   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
36437330f729Sjoerg   return llvm::ConstantExpr::getBitCast(F, PTy);
36447330f729Sjoerg }
36457330f729Sjoerg 
36467330f729Sjoerg /// GetAddrOfFunction - Return the address of the given function.  If Ty is
36477330f729Sjoerg /// non-null, then this function will use the specified type if it has to
36487330f729Sjoerg /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer,ForDefinition_t IsForDefinition)36497330f729Sjoerg llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
36507330f729Sjoerg                                                  llvm::Type *Ty,
36517330f729Sjoerg                                                  bool ForVTable,
36527330f729Sjoerg                                                  bool DontDefer,
36537330f729Sjoerg                                               ForDefinition_t IsForDefinition) {
3654*e038c9c4Sjoerg   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3655*e038c9c4Sjoerg          "consteval function should never be emitted");
36567330f729Sjoerg   // If there was no specific requested type, just convert it now.
36577330f729Sjoerg   if (!Ty) {
36587330f729Sjoerg     const auto *FD = cast<FunctionDecl>(GD.getDecl());
36597330f729Sjoerg     Ty = getTypes().ConvertType(FD->getType());
36607330f729Sjoerg   }
36617330f729Sjoerg 
36627330f729Sjoerg   // Devirtualized destructor calls may come through here instead of via
36637330f729Sjoerg   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
36647330f729Sjoerg   // of the complete destructor when necessary.
36657330f729Sjoerg   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
36667330f729Sjoerg     if (getTarget().getCXXABI().isMicrosoft() &&
36677330f729Sjoerg         GD.getDtorType() == Dtor_Complete &&
36687330f729Sjoerg         DD->getParent()->getNumVBases() == 0)
36697330f729Sjoerg       GD = GlobalDecl(DD, Dtor_Base);
36707330f729Sjoerg   }
36717330f729Sjoerg 
36727330f729Sjoerg   StringRef MangledName = getMangledName(GD);
3673*e038c9c4Sjoerg   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
36747330f729Sjoerg                                     /*IsThunk=*/false, llvm::AttributeList(),
36757330f729Sjoerg                                     IsForDefinition);
3676*e038c9c4Sjoerg   // Returns kernel handle for HIP kernel stub function.
3677*e038c9c4Sjoerg   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
3678*e038c9c4Sjoerg       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
3679*e038c9c4Sjoerg     auto *Handle = getCUDARuntime().getKernelHandle(
3680*e038c9c4Sjoerg         cast<llvm::Function>(F->stripPointerCasts()), GD);
3681*e038c9c4Sjoerg     if (IsForDefinition)
3682*e038c9c4Sjoerg       return F;
3683*e038c9c4Sjoerg     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3684*e038c9c4Sjoerg   }
3685*e038c9c4Sjoerg   return F;
36867330f729Sjoerg }
36877330f729Sjoerg 
36887330f729Sjoerg static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext & C,StringRef Name)36897330f729Sjoerg GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
36907330f729Sjoerg   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
36917330f729Sjoerg   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
36927330f729Sjoerg 
36937330f729Sjoerg   IdentifierInfo &CII = C.Idents.get(Name);
3694*e038c9c4Sjoerg   for (const auto *Result : DC->lookup(&CII))
3695*e038c9c4Sjoerg     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
36967330f729Sjoerg       return FD;
36977330f729Sjoerg 
36987330f729Sjoerg   if (!C.getLangOpts().CPlusPlus)
36997330f729Sjoerg     return nullptr;
37007330f729Sjoerg 
37017330f729Sjoerg   // Demangle the premangled name from getTerminateFn()
37027330f729Sjoerg   IdentifierInfo &CXXII =
37037330f729Sjoerg       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
37047330f729Sjoerg           ? C.Idents.get("terminate")
37057330f729Sjoerg           : C.Idents.get(Name);
37067330f729Sjoerg 
37077330f729Sjoerg   for (const auto &N : {"__cxxabiv1", "std"}) {
37087330f729Sjoerg     IdentifierInfo &NS = C.Idents.get(N);
3709*e038c9c4Sjoerg     for (const auto *Result : DC->lookup(&NS)) {
3710*e038c9c4Sjoerg       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3711*e038c9c4Sjoerg       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3712*e038c9c4Sjoerg         for (const auto *Result : LSD->lookup(&NS))
37137330f729Sjoerg           if ((ND = dyn_cast<NamespaceDecl>(Result)))
37147330f729Sjoerg             break;
37157330f729Sjoerg 
37167330f729Sjoerg       if (ND)
3717*e038c9c4Sjoerg         for (const auto *Result : ND->lookup(&CXXII))
37187330f729Sjoerg           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
37197330f729Sjoerg             return FD;
37207330f729Sjoerg     }
37217330f729Sjoerg   }
37227330f729Sjoerg 
37237330f729Sjoerg   return nullptr;
37247330f729Sjoerg }
37257330f729Sjoerg 
37267330f729Sjoerg /// CreateRuntimeFunction - Create a new runtime function with the specified
37277330f729Sjoerg /// type and name.
37287330f729Sjoerg llvm::FunctionCallee
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeList ExtraAttrs,bool Local,bool AssumeConvergent)37297330f729Sjoerg CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
37307330f729Sjoerg                                      llvm::AttributeList ExtraAttrs, bool Local,
37317330f729Sjoerg                                      bool AssumeConvergent) {
37327330f729Sjoerg   if (AssumeConvergent) {
37337330f729Sjoerg     ExtraAttrs =
37347330f729Sjoerg         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
37357330f729Sjoerg                                 llvm::Attribute::Convergent);
37367330f729Sjoerg   }
37377330f729Sjoerg 
37387330f729Sjoerg   llvm::Constant *C =
37397330f729Sjoerg       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
37407330f729Sjoerg                               /*DontDefer=*/false, /*IsThunk=*/false,
37417330f729Sjoerg                               ExtraAttrs);
37427330f729Sjoerg 
37437330f729Sjoerg   if (auto *F = dyn_cast<llvm::Function>(C)) {
37447330f729Sjoerg     if (F->empty()) {
37457330f729Sjoerg       F->setCallingConv(getRuntimeCC());
37467330f729Sjoerg 
37477330f729Sjoerg       // In Windows Itanium environments, try to mark runtime functions
37487330f729Sjoerg       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
37497330f729Sjoerg       // will link their standard library statically or dynamically. Marking
37507330f729Sjoerg       // functions imported when they are not imported can cause linker errors
37517330f729Sjoerg       // and warnings.
37527330f729Sjoerg       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
37537330f729Sjoerg           !getCodeGenOpts().LTOVisibilityPublicStd) {
37547330f729Sjoerg         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
37557330f729Sjoerg         if (!FD || FD->hasAttr<DLLImportAttr>()) {
37567330f729Sjoerg           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
37577330f729Sjoerg           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
37587330f729Sjoerg         }
37597330f729Sjoerg       }
37607330f729Sjoerg       setDSOLocal(F);
37617330f729Sjoerg     }
37627330f729Sjoerg   }
37637330f729Sjoerg 
37647330f729Sjoerg   return {FTy, C};
37657330f729Sjoerg }
37667330f729Sjoerg 
37677330f729Sjoerg /// isTypeConstant - Determine whether an object of this type can be emitted
37687330f729Sjoerg /// as a constant.
37697330f729Sjoerg ///
37707330f729Sjoerg /// If ExcludeCtor is true, the duration when the object's constructor runs
37717330f729Sjoerg /// will not be considered. The caller will need to verify that the object is
37727330f729Sjoerg /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)37737330f729Sjoerg bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
37747330f729Sjoerg   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
37757330f729Sjoerg     return false;
37767330f729Sjoerg 
37777330f729Sjoerg   if (Context.getLangOpts().CPlusPlus) {
37787330f729Sjoerg     if (const CXXRecordDecl *Record
37797330f729Sjoerg           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
37807330f729Sjoerg       return ExcludeCtor && !Record->hasMutableFields() &&
37817330f729Sjoerg              Record->hasTrivialDestructor();
37827330f729Sjoerg   }
37837330f729Sjoerg 
37847330f729Sjoerg   return true;
37857330f729Sjoerg }
37867330f729Sjoerg 
37877330f729Sjoerg /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3788*e038c9c4Sjoerg /// create and return an llvm GlobalVariable with the specified type and address
3789*e038c9c4Sjoerg /// space. If there is something in the module with the specified name, return
3790*e038c9c4Sjoerg /// it potentially bitcasted to the right type.
37917330f729Sjoerg ///
37927330f729Sjoerg /// If D is non-null, it specifies a decl that correspond to this.  This is used
37937330f729Sjoerg /// to set the attributes on the global when it is first created.
37947330f729Sjoerg ///
37957330f729Sjoerg /// If IsForDefinition is true, it is guaranteed that an actual global with
37967330f729Sjoerg /// type Ty will be returned, not conversion of a variable with the same
37977330f729Sjoerg /// mangled name but some other type.
37987330f729Sjoerg llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::Type * Ty,unsigned AddrSpace,const VarDecl * D,ForDefinition_t IsForDefinition)3799*e038c9c4Sjoerg CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
3800*e038c9c4Sjoerg                                      unsigned AddrSpace, const VarDecl *D,
38017330f729Sjoerg                                      ForDefinition_t IsForDefinition) {
38027330f729Sjoerg   // Lookup the entry, lazily creating it if necessary.
38037330f729Sjoerg   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
38047330f729Sjoerg   if (Entry) {
38057330f729Sjoerg     if (WeakRefReferences.erase(Entry)) {
38067330f729Sjoerg       if (D && !D->hasAttr<WeakAttr>())
38077330f729Sjoerg         Entry->setLinkage(llvm::Function::ExternalLinkage);
38087330f729Sjoerg     }
38097330f729Sjoerg 
38107330f729Sjoerg     // Handle dropped DLL attributes.
38117330f729Sjoerg     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
38127330f729Sjoerg       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
38137330f729Sjoerg 
38147330f729Sjoerg     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
38157330f729Sjoerg       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
38167330f729Sjoerg 
3817*e038c9c4Sjoerg     if (Entry->getValueType() == Ty && Entry->getAddressSpace() == AddrSpace)
38187330f729Sjoerg       return Entry;
38197330f729Sjoerg 
38207330f729Sjoerg     // If there are two attempts to define the same mangled name, issue an
38217330f729Sjoerg     // error.
38227330f729Sjoerg     if (IsForDefinition && !Entry->isDeclaration()) {
38237330f729Sjoerg       GlobalDecl OtherGD;
38247330f729Sjoerg       const VarDecl *OtherD;
38257330f729Sjoerg 
38267330f729Sjoerg       // Check that D is not yet in DiagnosedConflictingDefinitions is required
38277330f729Sjoerg       // to make sure that we issue an error only once.
38287330f729Sjoerg       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
38297330f729Sjoerg           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
38307330f729Sjoerg           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
38317330f729Sjoerg           OtherD->hasInit() &&
38327330f729Sjoerg           DiagnosedConflictingDefinitions.insert(D).second) {
38337330f729Sjoerg         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
38347330f729Sjoerg             << MangledName;
38357330f729Sjoerg         getDiags().Report(OtherGD.getDecl()->getLocation(),
38367330f729Sjoerg                           diag::note_previous_definition);
38377330f729Sjoerg       }
38387330f729Sjoerg     }
38397330f729Sjoerg 
38407330f729Sjoerg     // Make sure the result is of the correct type.
3841*e038c9c4Sjoerg     if (Entry->getType()->getAddressSpace() != AddrSpace) {
3842*e038c9c4Sjoerg       return llvm::ConstantExpr::getAddrSpaceCast(Entry,
3843*e038c9c4Sjoerg                                                   Ty->getPointerTo(AddrSpace));
3844*e038c9c4Sjoerg     }
38457330f729Sjoerg 
38467330f729Sjoerg     // (If global is requested for a definition, we always need to create a new
38477330f729Sjoerg     // global, not just return a bitcast.)
38487330f729Sjoerg     if (!IsForDefinition)
3849*e038c9c4Sjoerg       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(AddrSpace));
38507330f729Sjoerg   }
38517330f729Sjoerg 
3852*e038c9c4Sjoerg   auto DAddrSpace = GetGlobalVarAddressSpace(D);
3853*e038c9c4Sjoerg   auto TargetAddrSpace = getContext().getTargetAddressSpace(DAddrSpace);
38547330f729Sjoerg 
38557330f729Sjoerg   auto *GV = new llvm::GlobalVariable(
3856*e038c9c4Sjoerg       getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
3857*e038c9c4Sjoerg       MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
3858*e038c9c4Sjoerg       TargetAddrSpace);
38597330f729Sjoerg 
38607330f729Sjoerg   // If we already created a global with the same mangled name (but different
38617330f729Sjoerg   // type) before, take its name and remove it from its parent.
38627330f729Sjoerg   if (Entry) {
38637330f729Sjoerg     GV->takeName(Entry);
38647330f729Sjoerg 
38657330f729Sjoerg     if (!Entry->use_empty()) {
38667330f729Sjoerg       llvm::Constant *NewPtrForOldDecl =
38677330f729Sjoerg           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
38687330f729Sjoerg       Entry->replaceAllUsesWith(NewPtrForOldDecl);
38697330f729Sjoerg     }
38707330f729Sjoerg 
38717330f729Sjoerg     Entry->eraseFromParent();
38727330f729Sjoerg   }
38737330f729Sjoerg 
38747330f729Sjoerg   // This is the first use or definition of a mangled name.  If there is a
38757330f729Sjoerg   // deferred decl with this name, remember that we need to emit it at the end
38767330f729Sjoerg   // of the file.
38777330f729Sjoerg   auto DDI = DeferredDecls.find(MangledName);
38787330f729Sjoerg   if (DDI != DeferredDecls.end()) {
38797330f729Sjoerg     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
38807330f729Sjoerg     // list, and remove it from DeferredDecls (since we don't need it anymore).
38817330f729Sjoerg     addDeferredDeclToEmit(DDI->second);
38827330f729Sjoerg     DeferredDecls.erase(DDI);
38837330f729Sjoerg   }
38847330f729Sjoerg 
38857330f729Sjoerg   // Handle things which are present even on external declarations.
38867330f729Sjoerg   if (D) {
38877330f729Sjoerg     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
38887330f729Sjoerg       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
38897330f729Sjoerg 
38907330f729Sjoerg     // FIXME: This code is overly simple and should be merged with other global
38917330f729Sjoerg     // handling.
38927330f729Sjoerg     GV->setConstant(isTypeConstant(D->getType(), false));
38937330f729Sjoerg 
38947330f729Sjoerg     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
38957330f729Sjoerg 
38967330f729Sjoerg     setLinkageForGV(GV, D);
38977330f729Sjoerg 
38987330f729Sjoerg     if (D->getTLSKind()) {
38997330f729Sjoerg       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
39007330f729Sjoerg         CXXThreadLocals.push_back(D);
39017330f729Sjoerg       setTLSMode(GV, *D);
39027330f729Sjoerg     }
39037330f729Sjoerg 
39047330f729Sjoerg     setGVProperties(GV, D);
39057330f729Sjoerg 
39067330f729Sjoerg     // If required by the ABI, treat declarations of static data members with
39077330f729Sjoerg     // inline initializers as definitions.
39087330f729Sjoerg     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
39097330f729Sjoerg       EmitGlobalVarDefinition(D);
39107330f729Sjoerg     }
39117330f729Sjoerg 
39127330f729Sjoerg     // Emit section information for extern variables.
39137330f729Sjoerg     if (D->hasExternalStorage()) {
39147330f729Sjoerg       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
39157330f729Sjoerg         GV->setSection(SA->getName());
39167330f729Sjoerg     }
39177330f729Sjoerg 
39187330f729Sjoerg     // Handle XCore specific ABI requirements.
39197330f729Sjoerg     if (getTriple().getArch() == llvm::Triple::xcore &&
39207330f729Sjoerg         D->getLanguageLinkage() == CLanguageLinkage &&
39217330f729Sjoerg         D->getType().isConstant(Context) &&
39227330f729Sjoerg         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
39237330f729Sjoerg       GV->setSection(".cp.rodata");
39247330f729Sjoerg 
39257330f729Sjoerg     // Check if we a have a const declaration with an initializer, we may be
39267330f729Sjoerg     // able to emit it as available_externally to expose it's value to the
39277330f729Sjoerg     // optimizer.
39287330f729Sjoerg     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
39297330f729Sjoerg         D->getType().isConstQualified() && !GV->hasInitializer() &&
39307330f729Sjoerg         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
39317330f729Sjoerg       const auto *Record =
39327330f729Sjoerg           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
39337330f729Sjoerg       bool HasMutableFields = Record && Record->hasMutableFields();
39347330f729Sjoerg       if (!HasMutableFields) {
39357330f729Sjoerg         const VarDecl *InitDecl;
39367330f729Sjoerg         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
39377330f729Sjoerg         if (InitExpr) {
39387330f729Sjoerg           ConstantEmitter emitter(*this);
39397330f729Sjoerg           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
39407330f729Sjoerg           if (Init) {
39417330f729Sjoerg             auto *InitType = Init->getType();
3942*e038c9c4Sjoerg             if (GV->getValueType() != InitType) {
39437330f729Sjoerg               // The type of the initializer does not match the definition.
39447330f729Sjoerg               // This happens when an initializer has a different type from
39457330f729Sjoerg               // the type of the global (because of padding at the end of a
39467330f729Sjoerg               // structure for instance).
39477330f729Sjoerg               GV->setName(StringRef());
39487330f729Sjoerg               // Make a new global with the correct type, this is now guaranteed
39497330f729Sjoerg               // to work.
39507330f729Sjoerg               auto *NewGV = cast<llvm::GlobalVariable>(
39517330f729Sjoerg                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
39527330f729Sjoerg                       ->stripPointerCasts());
39537330f729Sjoerg 
39547330f729Sjoerg               // Erase the old global, since it is no longer used.
39557330f729Sjoerg               GV->eraseFromParent();
39567330f729Sjoerg               GV = NewGV;
39577330f729Sjoerg             } else {
39587330f729Sjoerg               GV->setInitializer(Init);
39597330f729Sjoerg               GV->setConstant(true);
39607330f729Sjoerg               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
39617330f729Sjoerg             }
39627330f729Sjoerg             emitter.finalize(GV);
39637330f729Sjoerg           }
39647330f729Sjoerg         }
39657330f729Sjoerg       }
39667330f729Sjoerg     }
39677330f729Sjoerg   }
39687330f729Sjoerg 
3969*e038c9c4Sjoerg   if (GV->isDeclaration()) {
3970*e038c9c4Sjoerg     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3971*e038c9c4Sjoerg     // External HIP managed variables needed to be recorded for transformation
3972*e038c9c4Sjoerg     // in both device and host compilations.
3973*e038c9c4Sjoerg     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
3974*e038c9c4Sjoerg         D->hasExternalStorage())
3975*e038c9c4Sjoerg       getCUDARuntime().handleVarRegistration(D, *GV);
3976*e038c9c4Sjoerg   }
3977*e038c9c4Sjoerg 
39787330f729Sjoerg   LangAS ExpectedAS =
39797330f729Sjoerg       D ? D->getType().getAddressSpace()
39807330f729Sjoerg         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3981*e038c9c4Sjoerg   assert(getContext().getTargetAddressSpace(ExpectedAS) == AddrSpace);
3982*e038c9c4Sjoerg   if (DAddrSpace != ExpectedAS) {
3983*e038c9c4Sjoerg     return getTargetCodeGenInfo().performAddrSpaceCast(
3984*e038c9c4Sjoerg         *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(AddrSpace));
3985*e038c9c4Sjoerg   }
39867330f729Sjoerg 
39877330f729Sjoerg   return GV;
39887330f729Sjoerg }
39897330f729Sjoerg 
39907330f729Sjoerg llvm::Constant *
GetAddrOfGlobal(GlobalDecl GD,ForDefinition_t IsForDefinition)3991*e038c9c4Sjoerg CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
39927330f729Sjoerg   const Decl *D = GD.getDecl();
3993*e038c9c4Sjoerg 
39947330f729Sjoerg   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
39957330f729Sjoerg     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
39967330f729Sjoerg                                 /*DontDefer=*/false, IsForDefinition);
3997*e038c9c4Sjoerg 
3998*e038c9c4Sjoerg   if (isa<CXXMethodDecl>(D)) {
3999*e038c9c4Sjoerg     auto FInfo =
4000*e038c9c4Sjoerg         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
40017330f729Sjoerg     auto Ty = getTypes().GetFunctionType(*FInfo);
40027330f729Sjoerg     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
40037330f729Sjoerg                              IsForDefinition);
4004*e038c9c4Sjoerg   }
4005*e038c9c4Sjoerg 
4006*e038c9c4Sjoerg   if (isa<FunctionDecl>(D)) {
40077330f729Sjoerg     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
40087330f729Sjoerg     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
40097330f729Sjoerg     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
40107330f729Sjoerg                              IsForDefinition);
4011*e038c9c4Sjoerg   }
4012*e038c9c4Sjoerg 
4013*e038c9c4Sjoerg   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
40147330f729Sjoerg }
40157330f729Sjoerg 
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage,unsigned Alignment)40167330f729Sjoerg llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
40177330f729Sjoerg     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
40187330f729Sjoerg     unsigned Alignment) {
40197330f729Sjoerg   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
40207330f729Sjoerg   llvm::GlobalVariable *OldGV = nullptr;
40217330f729Sjoerg 
40227330f729Sjoerg   if (GV) {
40237330f729Sjoerg     // Check if the variable has the right type.
4024*e038c9c4Sjoerg     if (GV->getValueType() == Ty)
40257330f729Sjoerg       return GV;
40267330f729Sjoerg 
40277330f729Sjoerg     // Because C++ name mangling, the only way we can end up with an already
40287330f729Sjoerg     // existing global with the same name is if it has been declared extern "C".
40297330f729Sjoerg     assert(GV->isDeclaration() && "Declaration has wrong type!");
40307330f729Sjoerg     OldGV = GV;
40317330f729Sjoerg   }
40327330f729Sjoerg 
40337330f729Sjoerg   // Create a new variable.
40347330f729Sjoerg   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
40357330f729Sjoerg                                 Linkage, nullptr, Name);
40367330f729Sjoerg 
40377330f729Sjoerg   if (OldGV) {
40387330f729Sjoerg     // Replace occurrences of the old variable if needed.
40397330f729Sjoerg     GV->takeName(OldGV);
40407330f729Sjoerg 
40417330f729Sjoerg     if (!OldGV->use_empty()) {
40427330f729Sjoerg       llvm::Constant *NewPtrForOldDecl =
40437330f729Sjoerg       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
40447330f729Sjoerg       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
40457330f729Sjoerg     }
40467330f729Sjoerg 
40477330f729Sjoerg     OldGV->eraseFromParent();
40487330f729Sjoerg   }
40497330f729Sjoerg 
40507330f729Sjoerg   if (supportsCOMDAT() && GV->isWeakForLinker() &&
40517330f729Sjoerg       !GV->hasAvailableExternallyLinkage())
40527330f729Sjoerg     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
40537330f729Sjoerg 
40547330f729Sjoerg   GV->setAlignment(llvm::MaybeAlign(Alignment));
40557330f729Sjoerg 
40567330f729Sjoerg   return GV;
40577330f729Sjoerg }
40587330f729Sjoerg 
40597330f729Sjoerg /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
40607330f729Sjoerg /// given global variable.  If Ty is non-null and if the global doesn't exist,
40617330f729Sjoerg /// then it will be created with the specified type instead of whatever the
40627330f729Sjoerg /// normal requested type would be. If IsForDefinition is true, it is guaranteed
40637330f729Sjoerg /// that an actual global with type Ty will be returned, not conversion of a
40647330f729Sjoerg /// variable with the same mangled name but some other type.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty,ForDefinition_t IsForDefinition)40657330f729Sjoerg llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
40667330f729Sjoerg                                                   llvm::Type *Ty,
40677330f729Sjoerg                                            ForDefinition_t IsForDefinition) {
40687330f729Sjoerg   assert(D->hasGlobalStorage() && "Not a global variable");
40697330f729Sjoerg   QualType ASTTy = D->getType();
40707330f729Sjoerg   if (!Ty)
40717330f729Sjoerg     Ty = getTypes().ConvertTypeForMem(ASTTy);
40727330f729Sjoerg 
40737330f729Sjoerg   StringRef MangledName = getMangledName(D);
4074*e038c9c4Sjoerg   return GetOrCreateLLVMGlobal(MangledName, Ty,
4075*e038c9c4Sjoerg                                getContext().getTargetAddressSpace(ASTTy), D,
4076*e038c9c4Sjoerg                                IsForDefinition);
40777330f729Sjoerg }
40787330f729Sjoerg 
40797330f729Sjoerg /// CreateRuntimeVariable - Create a new runtime global variable with the
40807330f729Sjoerg /// specified type and name.
40817330f729Sjoerg llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name)40827330f729Sjoerg CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
40837330f729Sjoerg                                      StringRef Name) {
4084*e038c9c4Sjoerg   auto AddrSpace =
40857330f729Sjoerg       getContext().getLangOpts().OpenCL
4086*e038c9c4Sjoerg           ? getContext().getTargetAddressSpace(LangAS::opencl_global)
4087*e038c9c4Sjoerg           : 0;
4088*e038c9c4Sjoerg   auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
40897330f729Sjoerg   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
40907330f729Sjoerg   return Ret;
40917330f729Sjoerg }
40927330f729Sjoerg 
EmitTentativeDefinition(const VarDecl * D)40937330f729Sjoerg void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
40947330f729Sjoerg   assert(!D->getInit() && "Cannot emit definite definitions here!");
40957330f729Sjoerg 
40967330f729Sjoerg   StringRef MangledName = getMangledName(D);
40977330f729Sjoerg   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
40987330f729Sjoerg 
40997330f729Sjoerg   // We already have a definition, not declaration, with the same mangled name.
41007330f729Sjoerg   // Emitting of declaration is not required (and actually overwrites emitted
41017330f729Sjoerg   // definition).
41027330f729Sjoerg   if (GV && !GV->isDeclaration())
41037330f729Sjoerg     return;
41047330f729Sjoerg 
41057330f729Sjoerg   // If we have not seen a reference to this variable yet, place it into the
41067330f729Sjoerg   // deferred declarations table to be emitted if needed later.
41077330f729Sjoerg   if (!MustBeEmitted(D) && !GV) {
41087330f729Sjoerg       DeferredDecls[MangledName] = D;
41097330f729Sjoerg       return;
41107330f729Sjoerg   }
41117330f729Sjoerg 
41127330f729Sjoerg   // The tentative definition is the only definition.
41137330f729Sjoerg   EmitGlobalVarDefinition(D);
41147330f729Sjoerg }
41157330f729Sjoerg 
EmitExternalDeclaration(const VarDecl * D)4116*e038c9c4Sjoerg void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4117*e038c9c4Sjoerg   EmitExternalVarDeclaration(D);
4118*e038c9c4Sjoerg }
4119*e038c9c4Sjoerg 
GetTargetTypeStoreSize(llvm::Type * Ty) const41207330f729Sjoerg CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
41217330f729Sjoerg   return Context.toCharUnitsFromBits(
41227330f729Sjoerg       getDataLayout().getTypeStoreSizeInBits(Ty));
41237330f729Sjoerg }
41247330f729Sjoerg 
GetGlobalVarAddressSpace(const VarDecl * D)41257330f729Sjoerg LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
41267330f729Sjoerg   LangAS AddrSpace = LangAS::Default;
41277330f729Sjoerg   if (LangOpts.OpenCL) {
41287330f729Sjoerg     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
41297330f729Sjoerg     assert(AddrSpace == LangAS::opencl_global ||
4130*e038c9c4Sjoerg            AddrSpace == LangAS::opencl_global_device ||
4131*e038c9c4Sjoerg            AddrSpace == LangAS::opencl_global_host ||
41327330f729Sjoerg            AddrSpace == LangAS::opencl_constant ||
41337330f729Sjoerg            AddrSpace == LangAS::opencl_local ||
41347330f729Sjoerg            AddrSpace >= LangAS::FirstTargetAddressSpace);
41357330f729Sjoerg     return AddrSpace;
41367330f729Sjoerg   }
41377330f729Sjoerg 
4138*e038c9c4Sjoerg   if (LangOpts.SYCLIsDevice &&
4139*e038c9c4Sjoerg       (!D || D->getType().getAddressSpace() == LangAS::Default))
4140*e038c9c4Sjoerg     return LangAS::sycl_global;
4141*e038c9c4Sjoerg 
41427330f729Sjoerg   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
41437330f729Sjoerg     if (D && D->hasAttr<CUDAConstantAttr>())
41447330f729Sjoerg       return LangAS::cuda_constant;
41457330f729Sjoerg     else if (D && D->hasAttr<CUDASharedAttr>())
41467330f729Sjoerg       return LangAS::cuda_shared;
41477330f729Sjoerg     else if (D && D->hasAttr<CUDADeviceAttr>())
41487330f729Sjoerg       return LangAS::cuda_device;
41497330f729Sjoerg     else if (D && D->getType().isConstQualified())
41507330f729Sjoerg       return LangAS::cuda_constant;
41517330f729Sjoerg     else
41527330f729Sjoerg       return LangAS::cuda_device;
41537330f729Sjoerg   }
41547330f729Sjoerg 
41557330f729Sjoerg   if (LangOpts.OpenMP) {
41567330f729Sjoerg     LangAS AS;
41577330f729Sjoerg     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
41587330f729Sjoerg       return AS;
41597330f729Sjoerg   }
41607330f729Sjoerg   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
41617330f729Sjoerg }
41627330f729Sjoerg 
GetGlobalConstantAddressSpace() const4163*e038c9c4Sjoerg LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
41647330f729Sjoerg   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
41657330f729Sjoerg   if (LangOpts.OpenCL)
41667330f729Sjoerg     return LangAS::opencl_constant;
4167*e038c9c4Sjoerg   if (LangOpts.SYCLIsDevice)
4168*e038c9c4Sjoerg     return LangAS::sycl_global;
41697330f729Sjoerg   if (auto AS = getTarget().getConstantAddressSpace())
41707330f729Sjoerg     return AS.getValue();
41717330f729Sjoerg   return LangAS::Default;
41727330f729Sjoerg }
41737330f729Sjoerg 
41747330f729Sjoerg // In address space agnostic languages, string literals are in default address
41757330f729Sjoerg // space in AST. However, certain targets (e.g. amdgcn) request them to be
41767330f729Sjoerg // emitted in constant address space in LLVM IR. To be consistent with other
41777330f729Sjoerg // parts of AST, string literal global variables in constant address space
41787330f729Sjoerg // need to be casted to default address space before being put into address
41797330f729Sjoerg // map and referenced by other part of CodeGen.
41807330f729Sjoerg // In OpenCL, string literals are in constant address space in AST, therefore
41817330f729Sjoerg // they should not be casted to default address space.
41827330f729Sjoerg static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule & CGM,llvm::GlobalVariable * GV)41837330f729Sjoerg castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
41847330f729Sjoerg                                        llvm::GlobalVariable *GV) {
41857330f729Sjoerg   llvm::Constant *Cast = GV;
41867330f729Sjoerg   if (!CGM.getLangOpts().OpenCL) {
4187*e038c9c4Sjoerg     auto AS = CGM.GetGlobalConstantAddressSpace();
41887330f729Sjoerg     if (AS != LangAS::Default)
41897330f729Sjoerg       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4190*e038c9c4Sjoerg           CGM, GV, AS, LangAS::Default,
41917330f729Sjoerg           GV->getValueType()->getPointerTo(
41927330f729Sjoerg               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
41937330f729Sjoerg   }
41947330f729Sjoerg   return Cast;
41957330f729Sjoerg }
41967330f729Sjoerg 
41977330f729Sjoerg template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)41987330f729Sjoerg void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
41997330f729Sjoerg                                                llvm::GlobalValue *GV) {
42007330f729Sjoerg   if (!getLangOpts().CPlusPlus)
42017330f729Sjoerg     return;
42027330f729Sjoerg 
42037330f729Sjoerg   // Must have 'used' attribute, or else inline assembly can't rely on
42047330f729Sjoerg   // the name existing.
42057330f729Sjoerg   if (!D->template hasAttr<UsedAttr>())
42067330f729Sjoerg     return;
42077330f729Sjoerg 
42087330f729Sjoerg   // Must have internal linkage and an ordinary name.
42097330f729Sjoerg   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
42107330f729Sjoerg     return;
42117330f729Sjoerg 
42127330f729Sjoerg   // Must be in an extern "C" context. Entities declared directly within
42137330f729Sjoerg   // a record are not extern "C" even if the record is in such a context.
42147330f729Sjoerg   const SomeDecl *First = D->getFirstDecl();
42157330f729Sjoerg   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
42167330f729Sjoerg     return;
42177330f729Sjoerg 
42187330f729Sjoerg   // OK, this is an internal linkage entity inside an extern "C" linkage
42197330f729Sjoerg   // specification. Make a note of that so we can give it the "expected"
42207330f729Sjoerg   // mangled name if nothing else is using that name.
42217330f729Sjoerg   std::pair<StaticExternCMap::iterator, bool> R =
42227330f729Sjoerg       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
42237330f729Sjoerg 
42247330f729Sjoerg   // If we have multiple internal linkage entities with the same name
42257330f729Sjoerg   // in extern "C" regions, none of them gets that name.
42267330f729Sjoerg   if (!R.second)
42277330f729Sjoerg     R.first->second = nullptr;
42287330f729Sjoerg }
42297330f729Sjoerg 
shouldBeInCOMDAT(CodeGenModule & CGM,const Decl & D)42307330f729Sjoerg static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
42317330f729Sjoerg   if (!CGM.supportsCOMDAT())
42327330f729Sjoerg     return false;
42337330f729Sjoerg 
42347330f729Sjoerg   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
42357330f729Sjoerg   // them being "merged" by the COMDAT Folding linker optimization.
42367330f729Sjoerg   if (D.hasAttr<CUDAGlobalAttr>())
42377330f729Sjoerg     return false;
42387330f729Sjoerg 
42397330f729Sjoerg   if (D.hasAttr<SelectAnyAttr>())
42407330f729Sjoerg     return true;
42417330f729Sjoerg 
42427330f729Sjoerg   GVALinkage Linkage;
42437330f729Sjoerg   if (auto *VD = dyn_cast<VarDecl>(&D))
42447330f729Sjoerg     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
42457330f729Sjoerg   else
42467330f729Sjoerg     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
42477330f729Sjoerg 
42487330f729Sjoerg   switch (Linkage) {
42497330f729Sjoerg   case GVA_Internal:
42507330f729Sjoerg   case GVA_AvailableExternally:
42517330f729Sjoerg   case GVA_StrongExternal:
42527330f729Sjoerg     return false;
42537330f729Sjoerg   case GVA_DiscardableODR:
42547330f729Sjoerg   case GVA_StrongODR:
42557330f729Sjoerg     return true;
42567330f729Sjoerg   }
42577330f729Sjoerg   llvm_unreachable("No such linkage");
42587330f729Sjoerg }
42597330f729Sjoerg 
maybeSetTrivialComdat(const Decl & D,llvm::GlobalObject & GO)42607330f729Sjoerg void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
42617330f729Sjoerg                                           llvm::GlobalObject &GO) {
42627330f729Sjoerg   if (!shouldBeInCOMDAT(*this, D))
42637330f729Sjoerg     return;
42647330f729Sjoerg   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
42657330f729Sjoerg }
42667330f729Sjoerg 
42677330f729Sjoerg /// Pass IsTentative as true if you want to create a tentative definition.
EmitGlobalVarDefinition(const VarDecl * D,bool IsTentative)42687330f729Sjoerg void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
42697330f729Sjoerg                                             bool IsTentative) {
42707330f729Sjoerg   // OpenCL global variables of sampler type are translated to function calls,
42717330f729Sjoerg   // therefore no need to be translated.
42727330f729Sjoerg   QualType ASTTy = D->getType();
42737330f729Sjoerg   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
42747330f729Sjoerg     return;
42757330f729Sjoerg 
42767330f729Sjoerg   // If this is OpenMP device, check if it is legal to emit this global
42777330f729Sjoerg   // normally.
42787330f729Sjoerg   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
42797330f729Sjoerg       OpenMPRuntime->emitTargetGlobalVariable(D))
42807330f729Sjoerg     return;
42817330f729Sjoerg 
42827330f729Sjoerg   llvm::Constant *Init = nullptr;
42837330f729Sjoerg   bool NeedsGlobalCtor = false;
42847330f729Sjoerg   bool NeedsGlobalDtor =
42857330f729Sjoerg       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
42867330f729Sjoerg 
42877330f729Sjoerg   const VarDecl *InitDecl;
42887330f729Sjoerg   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
42897330f729Sjoerg 
42907330f729Sjoerg   Optional<ConstantEmitter> emitter;
42917330f729Sjoerg 
42927330f729Sjoerg   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
42937330f729Sjoerg   // as part of their declaration."  Sema has already checked for
42947330f729Sjoerg   // error cases, so we just need to set Init to UndefValue.
42957330f729Sjoerg   bool IsCUDASharedVar =
42967330f729Sjoerg       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
42977330f729Sjoerg   // Shadows of initialized device-side global variables are also left
42987330f729Sjoerg   // undefined.
4299*e038c9c4Sjoerg   // Managed Variables should be initialized on both host side and device side.
43007330f729Sjoerg   bool IsCUDAShadowVar =
4301*e038c9c4Sjoerg       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
43027330f729Sjoerg       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
43037330f729Sjoerg        D->hasAttr<CUDASharedAttr>());
4304*e038c9c4Sjoerg   bool IsCUDADeviceShadowVar =
4305*e038c9c4Sjoerg       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4306*e038c9c4Sjoerg       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4307*e038c9c4Sjoerg        D->getType()->isCUDADeviceBuiltinTextureType());
43087330f729Sjoerg   if (getLangOpts().CUDA &&
4309*e038c9c4Sjoerg       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4310*e038c9c4Sjoerg     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4311*e038c9c4Sjoerg   else if (D->hasAttr<LoaderUninitializedAttr>())
4312*e038c9c4Sjoerg     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
43137330f729Sjoerg   else if (!InitExpr) {
43147330f729Sjoerg     // This is a tentative definition; tentative definitions are
43157330f729Sjoerg     // implicitly initialized with { 0 }.
43167330f729Sjoerg     //
43177330f729Sjoerg     // Note that tentative definitions are only emitted at the end of
43187330f729Sjoerg     // a translation unit, so they should never have incomplete
43197330f729Sjoerg     // type. In addition, EmitTentativeDefinition makes sure that we
43207330f729Sjoerg     // never attempt to emit a tentative definition if a real one
43217330f729Sjoerg     // exists. A use may still exists, however, so we still may need
43227330f729Sjoerg     // to do a RAUW.
43237330f729Sjoerg     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
43247330f729Sjoerg     Init = EmitNullConstant(D->getType());
43257330f729Sjoerg   } else {
43267330f729Sjoerg     initializedGlobalDecl = GlobalDecl(D);
43277330f729Sjoerg     emitter.emplace(*this);
43287330f729Sjoerg     Init = emitter->tryEmitForInitializer(*InitDecl);
43297330f729Sjoerg 
43307330f729Sjoerg     if (!Init) {
43317330f729Sjoerg       QualType T = InitExpr->getType();
43327330f729Sjoerg       if (D->getType()->isReferenceType())
43337330f729Sjoerg         T = D->getType();
43347330f729Sjoerg 
43357330f729Sjoerg       if (getLangOpts().CPlusPlus) {
43367330f729Sjoerg         Init = EmitNullConstant(T);
43377330f729Sjoerg         NeedsGlobalCtor = true;
43387330f729Sjoerg       } else {
43397330f729Sjoerg         ErrorUnsupported(D, "static initializer");
43407330f729Sjoerg         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
43417330f729Sjoerg       }
43427330f729Sjoerg     } else {
43437330f729Sjoerg       // We don't need an initializer, so remove the entry for the delayed
43447330f729Sjoerg       // initializer position (just in case this entry was delayed) if we
43457330f729Sjoerg       // also don't need to register a destructor.
43467330f729Sjoerg       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
43477330f729Sjoerg         DelayedCXXInitPosition.erase(D);
43487330f729Sjoerg     }
43497330f729Sjoerg   }
43507330f729Sjoerg 
43517330f729Sjoerg   llvm::Type* InitType = Init->getType();
43527330f729Sjoerg   llvm::Constant *Entry =
43537330f729Sjoerg       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
43547330f729Sjoerg 
43557330f729Sjoerg   // Strip off pointer casts if we got them.
43567330f729Sjoerg   Entry = Entry->stripPointerCasts();
43577330f729Sjoerg 
43587330f729Sjoerg   // Entry is now either a Function or GlobalVariable.
43597330f729Sjoerg   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
43607330f729Sjoerg 
43617330f729Sjoerg   // We have a definition after a declaration with the wrong type.
43627330f729Sjoerg   // We must make a new GlobalVariable* and update everything that used OldGV
43637330f729Sjoerg   // (a declaration or tentative definition) with the new GlobalVariable*
43647330f729Sjoerg   // (which will be a definition).
43657330f729Sjoerg   //
43667330f729Sjoerg   // This happens if there is a prototype for a global (e.g.
43677330f729Sjoerg   // "extern int x[];") and then a definition of a different type (e.g.
43687330f729Sjoerg   // "int x[10];"). This also happens when an initializer has a different type
43697330f729Sjoerg   // from the type of the global (this happens with unions).
4370*e038c9c4Sjoerg   if (!GV || GV->getValueType() != InitType ||
43717330f729Sjoerg       GV->getType()->getAddressSpace() !=
43727330f729Sjoerg           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
43737330f729Sjoerg 
43747330f729Sjoerg     // Move the old entry aside so that we'll create a new one.
43757330f729Sjoerg     Entry->setName(StringRef());
43767330f729Sjoerg 
43777330f729Sjoerg     // Make a new global with the correct type, this is now guaranteed to work.
43787330f729Sjoerg     GV = cast<llvm::GlobalVariable>(
43797330f729Sjoerg         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
43807330f729Sjoerg             ->stripPointerCasts());
43817330f729Sjoerg 
43827330f729Sjoerg     // Replace all uses of the old global with the new global
43837330f729Sjoerg     llvm::Constant *NewPtrForOldDecl =
4384*e038c9c4Sjoerg         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4385*e038c9c4Sjoerg                                                              Entry->getType());
43867330f729Sjoerg     Entry->replaceAllUsesWith(NewPtrForOldDecl);
43877330f729Sjoerg 
43887330f729Sjoerg     // Erase the old global, since it is no longer used.
43897330f729Sjoerg     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
43907330f729Sjoerg   }
43917330f729Sjoerg 
43927330f729Sjoerg   MaybeHandleStaticInExternC(D, GV);
43937330f729Sjoerg 
43947330f729Sjoerg   if (D->hasAttr<AnnotateAttr>())
43957330f729Sjoerg     AddGlobalAnnotations(D, GV);
43967330f729Sjoerg 
43977330f729Sjoerg   // Set the llvm linkage type as appropriate.
43987330f729Sjoerg   llvm::GlobalValue::LinkageTypes Linkage =
43997330f729Sjoerg       getLLVMLinkageVarDefinition(D, GV->isConstant());
44007330f729Sjoerg 
44017330f729Sjoerg   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
44027330f729Sjoerg   // the device. [...]"
44037330f729Sjoerg   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
44047330f729Sjoerg   // __device__, declares a variable that: [...]
44057330f729Sjoerg   // Is accessible from all the threads within the grid and from the host
44067330f729Sjoerg   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
44077330f729Sjoerg   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
44087330f729Sjoerg   if (GV && LangOpts.CUDA) {
44097330f729Sjoerg     if (LangOpts.CUDAIsDevice) {
44107330f729Sjoerg       if (Linkage != llvm::GlobalValue::InternalLinkage &&
44117330f729Sjoerg           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
44127330f729Sjoerg         GV->setExternallyInitialized(true);
44137330f729Sjoerg     } else {
4414*e038c9c4Sjoerg       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
44157330f729Sjoerg     }
4416*e038c9c4Sjoerg     getCUDARuntime().handleVarRegistration(D, *GV);
44177330f729Sjoerg   }
44187330f729Sjoerg 
44197330f729Sjoerg   GV->setInitializer(Init);
4420*e038c9c4Sjoerg   if (emitter)
4421*e038c9c4Sjoerg     emitter->finalize(GV);
44227330f729Sjoerg 
44237330f729Sjoerg   // If it is safe to mark the global 'constant', do so now.
44247330f729Sjoerg   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
44257330f729Sjoerg                   isTypeConstant(D->getType(), true));
44267330f729Sjoerg 
44277330f729Sjoerg   // If it is in a read-only section, mark it 'constant'.
44287330f729Sjoerg   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
44297330f729Sjoerg     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
44307330f729Sjoerg     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
44317330f729Sjoerg       GV->setConstant(true);
44327330f729Sjoerg   }
44337330f729Sjoerg 
44347330f729Sjoerg   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
44357330f729Sjoerg 
4436*e038c9c4Sjoerg   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4437*e038c9c4Sjoerg   // function is only defined alongside the variable, not also alongside
4438*e038c9c4Sjoerg   // callers. Normally, all accesses to a thread_local go through the
4439*e038c9c4Sjoerg   // thread-wrapper in order to ensure initialization has occurred, underlying
4440*e038c9c4Sjoerg   // variable will never be used other than the thread-wrapper, so it can be
4441*e038c9c4Sjoerg   // converted to internal linkage.
4442*e038c9c4Sjoerg   //
4443*e038c9c4Sjoerg   // However, if the variable has the 'constinit' attribute, it _can_ be
4444*e038c9c4Sjoerg   // referenced directly, without calling the thread-wrapper, so the linkage
4445*e038c9c4Sjoerg   // must not be changed.
4446*e038c9c4Sjoerg   //
4447*e038c9c4Sjoerg   // Additionally, if the variable isn't plain external linkage, e.g. if it's
4448*e038c9c4Sjoerg   // weak or linkonce, the de-duplication semantics are important to preserve,
4449*e038c9c4Sjoerg   // so we don't change the linkage.
4450*e038c9c4Sjoerg   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4451*e038c9c4Sjoerg       Linkage == llvm::GlobalValue::ExternalLinkage &&
44527330f729Sjoerg       Context.getTargetInfo().getTriple().isOSDarwin() &&
4453*e038c9c4Sjoerg       !D->hasAttr<ConstInitAttr>())
44547330f729Sjoerg     Linkage = llvm::GlobalValue::InternalLinkage;
44557330f729Sjoerg 
44567330f729Sjoerg   GV->setLinkage(Linkage);
44577330f729Sjoerg   if (D->hasAttr<DLLImportAttr>())
44587330f729Sjoerg     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
44597330f729Sjoerg   else if (D->hasAttr<DLLExportAttr>())
44607330f729Sjoerg     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
44617330f729Sjoerg   else
44627330f729Sjoerg     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
44637330f729Sjoerg 
44647330f729Sjoerg   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
44657330f729Sjoerg     // common vars aren't constant even if declared const.
44667330f729Sjoerg     GV->setConstant(false);
44677330f729Sjoerg     // Tentative definition of global variables may be initialized with
44687330f729Sjoerg     // non-zero null pointers. In this case they should have weak linkage
44697330f729Sjoerg     // since common linkage must have zero initializer and must not have
44707330f729Sjoerg     // explicit section therefore cannot have non-zero initial value.
44717330f729Sjoerg     if (!GV->getInitializer()->isNullValue())
44727330f729Sjoerg       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
44737330f729Sjoerg   }
44747330f729Sjoerg 
44757330f729Sjoerg   setNonAliasAttributes(D, GV);
44767330f729Sjoerg 
44777330f729Sjoerg   if (D->getTLSKind() && !GV->isThreadLocal()) {
44787330f729Sjoerg     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
44797330f729Sjoerg       CXXThreadLocals.push_back(D);
44807330f729Sjoerg     setTLSMode(GV, *D);
44817330f729Sjoerg   }
44827330f729Sjoerg 
44837330f729Sjoerg   maybeSetTrivialComdat(*D, *GV);
44847330f729Sjoerg 
44857330f729Sjoerg   // Emit the initializer function if necessary.
44867330f729Sjoerg   if (NeedsGlobalCtor || NeedsGlobalDtor)
44877330f729Sjoerg     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
44887330f729Sjoerg 
44897330f729Sjoerg   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
44907330f729Sjoerg 
44917330f729Sjoerg   // Emit global variable debug information.
44927330f729Sjoerg   if (CGDebugInfo *DI = getModuleDebugInfo())
4493*e038c9c4Sjoerg     if (getCodeGenOpts().hasReducedDebugInfo())
44947330f729Sjoerg       DI->EmitGlobalVariable(GV, D);
44957330f729Sjoerg }
44967330f729Sjoerg 
EmitExternalVarDeclaration(const VarDecl * D)4497*e038c9c4Sjoerg void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4498*e038c9c4Sjoerg   if (CGDebugInfo *DI = getModuleDebugInfo())
4499*e038c9c4Sjoerg     if (getCodeGenOpts().hasReducedDebugInfo()) {
4500*e038c9c4Sjoerg       QualType ASTTy = D->getType();
4501*e038c9c4Sjoerg       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4502*e038c9c4Sjoerg       llvm::Constant *GV = GetOrCreateLLVMGlobal(
4503*e038c9c4Sjoerg           D->getName(), Ty, getContext().getTargetAddressSpace(ASTTy), D);
4504*e038c9c4Sjoerg       DI->EmitExternalVariable(
4505*e038c9c4Sjoerg           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4506*e038c9c4Sjoerg     }
4507*e038c9c4Sjoerg }
4508*e038c9c4Sjoerg 
isVarDeclStrongDefinition(const ASTContext & Context,CodeGenModule & CGM,const VarDecl * D,bool NoCommon)45097330f729Sjoerg static bool isVarDeclStrongDefinition(const ASTContext &Context,
45107330f729Sjoerg                                       CodeGenModule &CGM, const VarDecl *D,
45117330f729Sjoerg                                       bool NoCommon) {
45127330f729Sjoerg   // Don't give variables common linkage if -fno-common was specified unless it
45137330f729Sjoerg   // was overridden by a NoCommon attribute.
45147330f729Sjoerg   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
45157330f729Sjoerg     return true;
45167330f729Sjoerg 
45177330f729Sjoerg   // C11 6.9.2/2:
45187330f729Sjoerg   //   A declaration of an identifier for an object that has file scope without
45197330f729Sjoerg   //   an initializer, and without a storage-class specifier or with the
45207330f729Sjoerg   //   storage-class specifier static, constitutes a tentative definition.
45217330f729Sjoerg   if (D->getInit() || D->hasExternalStorage())
45227330f729Sjoerg     return true;
45237330f729Sjoerg 
45247330f729Sjoerg   // A variable cannot be both common and exist in a section.
45257330f729Sjoerg   if (D->hasAttr<SectionAttr>())
45267330f729Sjoerg     return true;
45277330f729Sjoerg 
45287330f729Sjoerg   // A variable cannot be both common and exist in a section.
45297330f729Sjoerg   // We don't try to determine which is the right section in the front-end.
45307330f729Sjoerg   // If no specialized section name is applicable, it will resort to default.
45317330f729Sjoerg   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
45327330f729Sjoerg       D->hasAttr<PragmaClangDataSectionAttr>() ||
45337330f729Sjoerg       D->hasAttr<PragmaClangRelroSectionAttr>() ||
45347330f729Sjoerg       D->hasAttr<PragmaClangRodataSectionAttr>())
45357330f729Sjoerg     return true;
45367330f729Sjoerg 
45377330f729Sjoerg   // Thread local vars aren't considered common linkage.
45387330f729Sjoerg   if (D->getTLSKind())
45397330f729Sjoerg     return true;
45407330f729Sjoerg 
45417330f729Sjoerg   // Tentative definitions marked with WeakImportAttr are true definitions.
45427330f729Sjoerg   if (D->hasAttr<WeakImportAttr>())
45437330f729Sjoerg     return true;
45447330f729Sjoerg 
45457330f729Sjoerg   // A variable cannot be both common and exist in a comdat.
45467330f729Sjoerg   if (shouldBeInCOMDAT(CGM, *D))
45477330f729Sjoerg     return true;
45487330f729Sjoerg 
45497330f729Sjoerg   // Declarations with a required alignment do not have common linkage in MSVC
45507330f729Sjoerg   // mode.
45517330f729Sjoerg   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
45527330f729Sjoerg     if (D->hasAttr<AlignedAttr>())
45537330f729Sjoerg       return true;
45547330f729Sjoerg     QualType VarType = D->getType();
45557330f729Sjoerg     if (Context.isAlignmentRequired(VarType))
45567330f729Sjoerg       return true;
45577330f729Sjoerg 
45587330f729Sjoerg     if (const auto *RT = VarType->getAs<RecordType>()) {
45597330f729Sjoerg       const RecordDecl *RD = RT->getDecl();
45607330f729Sjoerg       for (const FieldDecl *FD : RD->fields()) {
45617330f729Sjoerg         if (FD->isBitField())
45627330f729Sjoerg           continue;
45637330f729Sjoerg         if (FD->hasAttr<AlignedAttr>())
45647330f729Sjoerg           return true;
45657330f729Sjoerg         if (Context.isAlignmentRequired(FD->getType()))
45667330f729Sjoerg           return true;
45677330f729Sjoerg       }
45687330f729Sjoerg     }
45697330f729Sjoerg   }
45707330f729Sjoerg 
45717330f729Sjoerg   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
45727330f729Sjoerg   // common symbols, so symbols with greater alignment requirements cannot be
45737330f729Sjoerg   // common.
45747330f729Sjoerg   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
45757330f729Sjoerg   // alignments for common symbols via the aligncomm directive, so this
45767330f729Sjoerg   // restriction only applies to MSVC environments.
45777330f729Sjoerg   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
45787330f729Sjoerg       Context.getTypeAlignIfKnown(D->getType()) >
45797330f729Sjoerg           Context.toBits(CharUnits::fromQuantity(32)))
45807330f729Sjoerg     return true;
45817330f729Sjoerg 
45827330f729Sjoerg   return false;
45837330f729Sjoerg }
45847330f729Sjoerg 
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage,bool IsConstantVariable)45857330f729Sjoerg llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
45867330f729Sjoerg     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
45877330f729Sjoerg   if (Linkage == GVA_Internal)
45887330f729Sjoerg     return llvm::Function::InternalLinkage;
45897330f729Sjoerg 
45907330f729Sjoerg   if (D->hasAttr<WeakAttr>()) {
45917330f729Sjoerg     if (IsConstantVariable)
45927330f729Sjoerg       return llvm::GlobalVariable::WeakODRLinkage;
45937330f729Sjoerg     else
45947330f729Sjoerg       return llvm::GlobalVariable::WeakAnyLinkage;
45957330f729Sjoerg   }
45967330f729Sjoerg 
45977330f729Sjoerg   if (const auto *FD = D->getAsFunction())
45987330f729Sjoerg     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
45997330f729Sjoerg       return llvm::GlobalVariable::LinkOnceAnyLinkage;
46007330f729Sjoerg 
46017330f729Sjoerg   // We are guaranteed to have a strong definition somewhere else,
46027330f729Sjoerg   // so we can use available_externally linkage.
46037330f729Sjoerg   if (Linkage == GVA_AvailableExternally)
46047330f729Sjoerg     return llvm::GlobalValue::AvailableExternallyLinkage;
46057330f729Sjoerg 
46067330f729Sjoerg   // Note that Apple's kernel linker doesn't support symbol
46077330f729Sjoerg   // coalescing, so we need to avoid linkonce and weak linkages there.
46087330f729Sjoerg   // Normally, this means we just map to internal, but for explicit
46097330f729Sjoerg   // instantiations we'll map to external.
46107330f729Sjoerg 
46117330f729Sjoerg   // In C++, the compiler has to emit a definition in every translation unit
46127330f729Sjoerg   // that references the function.  We should use linkonce_odr because
46137330f729Sjoerg   // a) if all references in this translation unit are optimized away, we
46147330f729Sjoerg   // don't need to codegen it.  b) if the function persists, it needs to be
46157330f729Sjoerg   // merged with other definitions. c) C++ has the ODR, so we know the
46167330f729Sjoerg   // definition is dependable.
46177330f729Sjoerg   if (Linkage == GVA_DiscardableODR)
46187330f729Sjoerg     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
46197330f729Sjoerg                                             : llvm::Function::InternalLinkage;
46207330f729Sjoerg 
46217330f729Sjoerg   // An explicit instantiation of a template has weak linkage, since
46227330f729Sjoerg   // explicit instantiations can occur in multiple translation units
46237330f729Sjoerg   // and must all be equivalent. However, we are not allowed to
46247330f729Sjoerg   // throw away these explicit instantiations.
46257330f729Sjoerg   //
4626*e038c9c4Sjoerg   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
46277330f729Sjoerg   // so say that CUDA templates are either external (for kernels) or internal.
4628*e038c9c4Sjoerg   // This lets llvm perform aggressive inter-procedural optimizations. For
4629*e038c9c4Sjoerg   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4630*e038c9c4Sjoerg   // therefore we need to follow the normal linkage paradigm.
46317330f729Sjoerg   if (Linkage == GVA_StrongODR) {
4632*e038c9c4Sjoerg     if (getLangOpts().AppleKext)
46337330f729Sjoerg       return llvm::Function::ExternalLinkage;
4634*e038c9c4Sjoerg     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4635*e038c9c4Sjoerg         !getLangOpts().GPURelocatableDeviceCode)
46367330f729Sjoerg       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
46377330f729Sjoerg                                           : llvm::Function::InternalLinkage;
46387330f729Sjoerg     return llvm::Function::WeakODRLinkage;
46397330f729Sjoerg   }
46407330f729Sjoerg 
46417330f729Sjoerg   // C++ doesn't have tentative definitions and thus cannot have common
46427330f729Sjoerg   // linkage.
46437330f729Sjoerg   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
46447330f729Sjoerg       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
46457330f729Sjoerg                                  CodeGenOpts.NoCommon))
46467330f729Sjoerg     return llvm::GlobalVariable::CommonLinkage;
46477330f729Sjoerg 
46487330f729Sjoerg   // selectany symbols are externally visible, so use weak instead of
46497330f729Sjoerg   // linkonce.  MSVC optimizes away references to const selectany globals, so
46507330f729Sjoerg   // all definitions should be the same and ODR linkage should be used.
46517330f729Sjoerg   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
46527330f729Sjoerg   if (D->hasAttr<SelectAnyAttr>())
46537330f729Sjoerg     return llvm::GlobalVariable::WeakODRLinkage;
46547330f729Sjoerg 
46557330f729Sjoerg   // Otherwise, we have strong external linkage.
46567330f729Sjoerg   assert(Linkage == GVA_StrongExternal);
46577330f729Sjoerg   return llvm::GlobalVariable::ExternalLinkage;
46587330f729Sjoerg }
46597330f729Sjoerg 
getLLVMLinkageVarDefinition(const VarDecl * VD,bool IsConstant)46607330f729Sjoerg llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
46617330f729Sjoerg     const VarDecl *VD, bool IsConstant) {
46627330f729Sjoerg   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
46637330f729Sjoerg   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
46647330f729Sjoerg }
46657330f729Sjoerg 
46667330f729Sjoerg /// Replace the uses of a function that was declared with a non-proto type.
46677330f729Sjoerg /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)46687330f729Sjoerg static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
46697330f729Sjoerg                                           llvm::Function *newFn) {
46707330f729Sjoerg   // Fast path.
46717330f729Sjoerg   if (old->use_empty()) return;
46727330f729Sjoerg 
46737330f729Sjoerg   llvm::Type *newRetTy = newFn->getReturnType();
46747330f729Sjoerg   SmallVector<llvm::Value*, 4> newArgs;
46757330f729Sjoerg 
46767330f729Sjoerg   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
46777330f729Sjoerg          ui != ue; ) {
46787330f729Sjoerg     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
46797330f729Sjoerg     llvm::User *user = use->getUser();
46807330f729Sjoerg 
46817330f729Sjoerg     // Recognize and replace uses of bitcasts.  Most calls to
46827330f729Sjoerg     // unprototyped functions will use bitcasts.
46837330f729Sjoerg     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
46847330f729Sjoerg       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
46857330f729Sjoerg         replaceUsesOfNonProtoConstant(bitcast, newFn);
46867330f729Sjoerg       continue;
46877330f729Sjoerg     }
46887330f729Sjoerg 
46897330f729Sjoerg     // Recognize calls to the function.
46907330f729Sjoerg     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
46917330f729Sjoerg     if (!callSite) continue;
46927330f729Sjoerg     if (!callSite->isCallee(&*use))
46937330f729Sjoerg       continue;
46947330f729Sjoerg 
46957330f729Sjoerg     // If the return types don't match exactly, then we can't
46967330f729Sjoerg     // transform this call unless it's dead.
46977330f729Sjoerg     if (callSite->getType() != newRetTy && !callSite->use_empty())
46987330f729Sjoerg       continue;
46997330f729Sjoerg 
47007330f729Sjoerg     // Get the call site's attribute list.
47017330f729Sjoerg     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
47027330f729Sjoerg     llvm::AttributeList oldAttrs = callSite->getAttributes();
47037330f729Sjoerg 
47047330f729Sjoerg     // If the function was passed too few arguments, don't transform.
47057330f729Sjoerg     unsigned newNumArgs = newFn->arg_size();
47067330f729Sjoerg     if (callSite->arg_size() < newNumArgs)
47077330f729Sjoerg       continue;
47087330f729Sjoerg 
47097330f729Sjoerg     // If extra arguments were passed, we silently drop them.
47107330f729Sjoerg     // If any of the types mismatch, we don't transform.
47117330f729Sjoerg     unsigned argNo = 0;
47127330f729Sjoerg     bool dontTransform = false;
47137330f729Sjoerg     for (llvm::Argument &A : newFn->args()) {
47147330f729Sjoerg       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
47157330f729Sjoerg         dontTransform = true;
47167330f729Sjoerg         break;
47177330f729Sjoerg       }
47187330f729Sjoerg 
47197330f729Sjoerg       // Add any parameter attributes.
47207330f729Sjoerg       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
47217330f729Sjoerg       argNo++;
47227330f729Sjoerg     }
47237330f729Sjoerg     if (dontTransform)
47247330f729Sjoerg       continue;
47257330f729Sjoerg 
47267330f729Sjoerg     // Okay, we can transform this.  Create the new call instruction and copy
47277330f729Sjoerg     // over the required information.
47287330f729Sjoerg     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
47297330f729Sjoerg 
47307330f729Sjoerg     // Copy over any operand bundles.
4731*e038c9c4Sjoerg     SmallVector<llvm::OperandBundleDef, 1> newBundles;
47327330f729Sjoerg     callSite->getOperandBundlesAsDefs(newBundles);
47337330f729Sjoerg 
47347330f729Sjoerg     llvm::CallBase *newCall;
47357330f729Sjoerg     if (dyn_cast<llvm::CallInst>(callSite)) {
47367330f729Sjoerg       newCall =
47377330f729Sjoerg           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
47387330f729Sjoerg     } else {
47397330f729Sjoerg       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
47407330f729Sjoerg       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
47417330f729Sjoerg                                          oldInvoke->getUnwindDest(), newArgs,
47427330f729Sjoerg                                          newBundles, "", callSite);
47437330f729Sjoerg     }
47447330f729Sjoerg     newArgs.clear(); // for the next iteration
47457330f729Sjoerg 
47467330f729Sjoerg     if (!newCall->getType()->isVoidTy())
47477330f729Sjoerg       newCall->takeName(callSite);
47487330f729Sjoerg     newCall->setAttributes(llvm::AttributeList::get(
47497330f729Sjoerg         newFn->getContext(), oldAttrs.getFnAttributes(),
47507330f729Sjoerg         oldAttrs.getRetAttributes(), newArgAttrs));
47517330f729Sjoerg     newCall->setCallingConv(callSite->getCallingConv());
47527330f729Sjoerg 
47537330f729Sjoerg     // Finally, remove the old call, replacing any uses with the new one.
47547330f729Sjoerg     if (!callSite->use_empty())
47557330f729Sjoerg       callSite->replaceAllUsesWith(newCall);
47567330f729Sjoerg 
47577330f729Sjoerg     // Copy debug location attached to CI.
47587330f729Sjoerg     if (callSite->getDebugLoc())
47597330f729Sjoerg       newCall->setDebugLoc(callSite->getDebugLoc());
47607330f729Sjoerg 
47617330f729Sjoerg     callSite->eraseFromParent();
47627330f729Sjoerg   }
47637330f729Sjoerg }
47647330f729Sjoerg 
47657330f729Sjoerg /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
47667330f729Sjoerg /// implement a function with no prototype, e.g. "int foo() {}".  If there are
47677330f729Sjoerg /// existing call uses of the old function in the module, this adjusts them to
47687330f729Sjoerg /// call the new function directly.
47697330f729Sjoerg ///
47707330f729Sjoerg /// This is not just a cleanup: the always_inline pass requires direct calls to
47717330f729Sjoerg /// functions to be able to inline them.  If there is a bitcast in the way, it
47727330f729Sjoerg /// won't inline them.  Instcombine normally deletes these calls, but it isn't
47737330f729Sjoerg /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)47747330f729Sjoerg static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
47757330f729Sjoerg                                                       llvm::Function *NewFn) {
47767330f729Sjoerg   // If we're redefining a global as a function, don't transform it.
47777330f729Sjoerg   if (!isa<llvm::Function>(Old)) return;
47787330f729Sjoerg 
47797330f729Sjoerg   replaceUsesOfNonProtoConstant(Old, NewFn);
47807330f729Sjoerg }
47817330f729Sjoerg 
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)47827330f729Sjoerg void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
47837330f729Sjoerg   auto DK = VD->isThisDeclarationADefinition();
47847330f729Sjoerg   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
47857330f729Sjoerg     return;
47867330f729Sjoerg 
47877330f729Sjoerg   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
47887330f729Sjoerg   // If we have a definition, this might be a deferred decl. If the
47897330f729Sjoerg   // instantiation is explicit, make sure we emit it at the end.
47907330f729Sjoerg   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
47917330f729Sjoerg     GetAddrOfGlobalVar(VD);
47927330f729Sjoerg 
47937330f729Sjoerg   EmitTopLevelDecl(VD);
47947330f729Sjoerg }
47957330f729Sjoerg 
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)47967330f729Sjoerg void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
47977330f729Sjoerg                                                  llvm::GlobalValue *GV) {
47987330f729Sjoerg   const auto *D = cast<FunctionDecl>(GD.getDecl());
47997330f729Sjoerg 
48007330f729Sjoerg   // Compute the function info and LLVM type.
48017330f729Sjoerg   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
48027330f729Sjoerg   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
48037330f729Sjoerg 
48047330f729Sjoerg   // Get or create the prototype for the function.
4805*e038c9c4Sjoerg   if (!GV || (GV->getValueType() != Ty))
48067330f729Sjoerg     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
48077330f729Sjoerg                                                    /*DontDefer=*/true,
48087330f729Sjoerg                                                    ForDefinition));
48097330f729Sjoerg 
48107330f729Sjoerg   // Already emitted.
48117330f729Sjoerg   if (!GV->isDeclaration())
48127330f729Sjoerg     return;
48137330f729Sjoerg 
48147330f729Sjoerg   // We need to set linkage and visibility on the function before
48157330f729Sjoerg   // generating code for it because various parts of IR generation
48167330f729Sjoerg   // want to propagate this information down (e.g. to local static
48177330f729Sjoerg   // declarations).
48187330f729Sjoerg   auto *Fn = cast<llvm::Function>(GV);
48197330f729Sjoerg   setFunctionLinkage(GD, Fn);
48207330f729Sjoerg 
48217330f729Sjoerg   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
48227330f729Sjoerg   setGVProperties(Fn, GD);
48237330f729Sjoerg 
48247330f729Sjoerg   MaybeHandleStaticInExternC(D, Fn);
48257330f729Sjoerg 
48267330f729Sjoerg   maybeSetTrivialComdat(*D, *Fn);
48277330f729Sjoerg 
4828*e038c9c4Sjoerg   // Set CodeGen attributes that represent floating point environment.
4829*e038c9c4Sjoerg   setLLVMFunctionFEnvAttributes(D, Fn);
4830*e038c9c4Sjoerg 
4831*e038c9c4Sjoerg   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
48327330f729Sjoerg 
48337330f729Sjoerg   setNonAliasAttributes(GD, Fn);
48347330f729Sjoerg   SetLLVMFunctionAttributesForDefinition(D, Fn);
48357330f729Sjoerg 
48367330f729Sjoerg   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
48377330f729Sjoerg     AddGlobalCtor(Fn, CA->getPriority());
48387330f729Sjoerg   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4839*e038c9c4Sjoerg     AddGlobalDtor(Fn, DA->getPriority(), true);
48407330f729Sjoerg   if (D->hasAttr<AnnotateAttr>())
48417330f729Sjoerg     AddGlobalAnnotations(D, Fn);
48427330f729Sjoerg }
48437330f729Sjoerg 
EmitAliasDefinition(GlobalDecl GD)48447330f729Sjoerg void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
48457330f729Sjoerg   const auto *D = cast<ValueDecl>(GD.getDecl());
48467330f729Sjoerg   const AliasAttr *AA = D->getAttr<AliasAttr>();
48477330f729Sjoerg   assert(AA && "Not an alias?");
48487330f729Sjoerg 
48497330f729Sjoerg   StringRef MangledName = getMangledName(GD);
48507330f729Sjoerg 
48517330f729Sjoerg   if (AA->getAliasee() == MangledName) {
48527330f729Sjoerg     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
48537330f729Sjoerg     return;
48547330f729Sjoerg   }
48557330f729Sjoerg 
48567330f729Sjoerg   // If there is a definition in the module, then it wins over the alias.
48577330f729Sjoerg   // This is dubious, but allow it to be safe.  Just ignore the alias.
48587330f729Sjoerg   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
48597330f729Sjoerg   if (Entry && !Entry->isDeclaration())
48607330f729Sjoerg     return;
48617330f729Sjoerg 
48627330f729Sjoerg   Aliases.push_back(GD);
48637330f729Sjoerg 
48647330f729Sjoerg   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
48657330f729Sjoerg 
48667330f729Sjoerg   // Create a reference to the named value.  This ensures that it is emitted
48677330f729Sjoerg   // if a deferred decl.
48687330f729Sjoerg   llvm::Constant *Aliasee;
48697330f729Sjoerg   llvm::GlobalValue::LinkageTypes LT;
48707330f729Sjoerg   if (isa<llvm::FunctionType>(DeclTy)) {
48717330f729Sjoerg     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
48727330f729Sjoerg                                       /*ForVTable=*/false);
48737330f729Sjoerg     LT = getFunctionLinkage(GD);
48747330f729Sjoerg   } else {
4875*e038c9c4Sjoerg     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0,
48767330f729Sjoerg                                     /*D=*/nullptr);
4877*e038c9c4Sjoerg     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4878*e038c9c4Sjoerg       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4879*e038c9c4Sjoerg     else
4880*e038c9c4Sjoerg       LT = getFunctionLinkage(GD);
48817330f729Sjoerg   }
48827330f729Sjoerg 
48837330f729Sjoerg   // Create the new alias itself, but don't set a name yet.
4884*e038c9c4Sjoerg   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
48857330f729Sjoerg   auto *GA =
4886*e038c9c4Sjoerg       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
48877330f729Sjoerg 
48887330f729Sjoerg   if (Entry) {
48897330f729Sjoerg     if (GA->getAliasee() == Entry) {
48907330f729Sjoerg       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
48917330f729Sjoerg       return;
48927330f729Sjoerg     }
48937330f729Sjoerg 
48947330f729Sjoerg     assert(Entry->isDeclaration());
48957330f729Sjoerg 
48967330f729Sjoerg     // If there is a declaration in the module, then we had an extern followed
48977330f729Sjoerg     // by the alias, as in:
48987330f729Sjoerg     //   extern int test6();
48997330f729Sjoerg     //   ...
49007330f729Sjoerg     //   int test6() __attribute__((alias("test7")));
49017330f729Sjoerg     //
49027330f729Sjoerg     // Remove it and replace uses of it with the alias.
49037330f729Sjoerg     GA->takeName(Entry);
49047330f729Sjoerg 
49057330f729Sjoerg     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
49067330f729Sjoerg                                                           Entry->getType()));
49077330f729Sjoerg     Entry->eraseFromParent();
49087330f729Sjoerg   } else {
49097330f729Sjoerg     GA->setName(MangledName);
49107330f729Sjoerg   }
49117330f729Sjoerg 
49127330f729Sjoerg   // Set attributes which are particular to an alias; this is a
49137330f729Sjoerg   // specialization of the attributes which may be set on a global
49147330f729Sjoerg   // variable/function.
49157330f729Sjoerg   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
49167330f729Sjoerg       D->isWeakImported()) {
49177330f729Sjoerg     GA->setLinkage(llvm::Function::WeakAnyLinkage);
49187330f729Sjoerg   }
49197330f729Sjoerg 
49207330f729Sjoerg   if (const auto *VD = dyn_cast<VarDecl>(D))
49217330f729Sjoerg     if (VD->getTLSKind())
49227330f729Sjoerg       setTLSMode(GA, *VD);
49237330f729Sjoerg 
49247330f729Sjoerg   SetCommonAttributes(GD, GA);
49257330f729Sjoerg }
49267330f729Sjoerg 
emitIFuncDefinition(GlobalDecl GD)49277330f729Sjoerg void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
49287330f729Sjoerg   const auto *D = cast<ValueDecl>(GD.getDecl());
49297330f729Sjoerg   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
49307330f729Sjoerg   assert(IFA && "Not an ifunc?");
49317330f729Sjoerg 
49327330f729Sjoerg   StringRef MangledName = getMangledName(GD);
49337330f729Sjoerg 
49347330f729Sjoerg   if (IFA->getResolver() == MangledName) {
49357330f729Sjoerg     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
49367330f729Sjoerg     return;
49377330f729Sjoerg   }
49387330f729Sjoerg 
49397330f729Sjoerg   // Report an error if some definition overrides ifunc.
49407330f729Sjoerg   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
49417330f729Sjoerg   if (Entry && !Entry->isDeclaration()) {
49427330f729Sjoerg     GlobalDecl OtherGD;
49437330f729Sjoerg     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
49447330f729Sjoerg         DiagnosedConflictingDefinitions.insert(GD).second) {
49457330f729Sjoerg       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
49467330f729Sjoerg           << MangledName;
49477330f729Sjoerg       Diags.Report(OtherGD.getDecl()->getLocation(),
49487330f729Sjoerg                    diag::note_previous_definition);
49497330f729Sjoerg     }
49507330f729Sjoerg     return;
49517330f729Sjoerg   }
49527330f729Sjoerg 
49537330f729Sjoerg   Aliases.push_back(GD);
49547330f729Sjoerg 
49557330f729Sjoerg   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
49567330f729Sjoerg   llvm::Constant *Resolver =
49577330f729Sjoerg       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
49587330f729Sjoerg                               /*ForVTable=*/false);
49597330f729Sjoerg   llvm::GlobalIFunc *GIF =
49607330f729Sjoerg       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
49617330f729Sjoerg                                 "", Resolver, &getModule());
49627330f729Sjoerg   if (Entry) {
49637330f729Sjoerg     if (GIF->getResolver() == Entry) {
49647330f729Sjoerg       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
49657330f729Sjoerg       return;
49667330f729Sjoerg     }
49677330f729Sjoerg     assert(Entry->isDeclaration());
49687330f729Sjoerg 
49697330f729Sjoerg     // If there is a declaration in the module, then we had an extern followed
49707330f729Sjoerg     // by the ifunc, as in:
49717330f729Sjoerg     //   extern int test();
49727330f729Sjoerg     //   ...
49737330f729Sjoerg     //   int test() __attribute__((ifunc("resolver")));
49747330f729Sjoerg     //
49757330f729Sjoerg     // Remove it and replace uses of it with the ifunc.
49767330f729Sjoerg     GIF->takeName(Entry);
49777330f729Sjoerg 
49787330f729Sjoerg     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
49797330f729Sjoerg                                                           Entry->getType()));
49807330f729Sjoerg     Entry->eraseFromParent();
49817330f729Sjoerg   } else
49827330f729Sjoerg     GIF->setName(MangledName);
49837330f729Sjoerg 
49847330f729Sjoerg   SetCommonAttributes(GD, GIF);
49857330f729Sjoerg }
49867330f729Sjoerg 
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)49877330f729Sjoerg llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
49887330f729Sjoerg                                             ArrayRef<llvm::Type*> Tys) {
49897330f729Sjoerg   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
49907330f729Sjoerg                                          Tys);
49917330f729Sjoerg }
49927330f729Sjoerg 
49937330f729Sjoerg static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)49947330f729Sjoerg GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
49957330f729Sjoerg                          const StringLiteral *Literal, bool TargetIsLSB,
49967330f729Sjoerg                          bool &IsUTF16, unsigned &StringLength) {
49977330f729Sjoerg   StringRef String = Literal->getString();
49987330f729Sjoerg   unsigned NumBytes = String.size();
49997330f729Sjoerg 
50007330f729Sjoerg   // Check for simple case.
50017330f729Sjoerg   if (!Literal->containsNonAsciiOrNull()) {
50027330f729Sjoerg     StringLength = NumBytes;
50037330f729Sjoerg     return *Map.insert(std::make_pair(String, nullptr)).first;
50047330f729Sjoerg   }
50057330f729Sjoerg 
50067330f729Sjoerg   // Otherwise, convert the UTF8 literals into a string of shorts.
50077330f729Sjoerg   IsUTF16 = true;
50087330f729Sjoerg 
50097330f729Sjoerg   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
50107330f729Sjoerg   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
50117330f729Sjoerg   llvm::UTF16 *ToPtr = &ToBuf[0];
50127330f729Sjoerg 
50137330f729Sjoerg   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
50147330f729Sjoerg                                  ToPtr + NumBytes, llvm::strictConversion);
50157330f729Sjoerg 
50167330f729Sjoerg   // ConvertUTF8toUTF16 returns the length in ToPtr.
50177330f729Sjoerg   StringLength = ToPtr - &ToBuf[0];
50187330f729Sjoerg 
50197330f729Sjoerg   // Add an explicit null.
50207330f729Sjoerg   *ToPtr = 0;
50217330f729Sjoerg   return *Map.insert(std::make_pair(
50227330f729Sjoerg                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
50237330f729Sjoerg                                    (StringLength + 1) * 2),
50247330f729Sjoerg                          nullptr)).first;
50257330f729Sjoerg }
50267330f729Sjoerg 
50277330f729Sjoerg ConstantAddress
GetAddrOfConstantCFString(const StringLiteral * Literal)50287330f729Sjoerg CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
50297330f729Sjoerg   unsigned StringLength = 0;
50307330f729Sjoerg   bool isUTF16 = false;
50317330f729Sjoerg   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
50327330f729Sjoerg       GetConstantCFStringEntry(CFConstantStringMap, Literal,
50337330f729Sjoerg                                getDataLayout().isLittleEndian(), isUTF16,
50347330f729Sjoerg                                StringLength);
50357330f729Sjoerg 
50367330f729Sjoerg   if (auto *C = Entry.second)
50377330f729Sjoerg     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
50387330f729Sjoerg 
50397330f729Sjoerg   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
50407330f729Sjoerg   llvm::Constant *Zeros[] = { Zero, Zero };
50417330f729Sjoerg 
50427330f729Sjoerg   const ASTContext &Context = getContext();
50437330f729Sjoerg   const llvm::Triple &Triple = getTriple();
50447330f729Sjoerg 
50457330f729Sjoerg   const auto CFRuntime = getLangOpts().CFRuntime;
50467330f729Sjoerg   const bool IsSwiftABI =
50477330f729Sjoerg       static_cast<unsigned>(CFRuntime) >=
50487330f729Sjoerg       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
50497330f729Sjoerg   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
50507330f729Sjoerg 
50517330f729Sjoerg   // If we don't already have it, get __CFConstantStringClassReference.
50527330f729Sjoerg   if (!CFConstantStringClassRef) {
50537330f729Sjoerg     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
50547330f729Sjoerg     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
50557330f729Sjoerg     Ty = llvm::ArrayType::get(Ty, 0);
50567330f729Sjoerg 
50577330f729Sjoerg     switch (CFRuntime) {
50587330f729Sjoerg     default: break;
50597330f729Sjoerg     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
50607330f729Sjoerg     case LangOptions::CoreFoundationABI::Swift5_0:
50617330f729Sjoerg       CFConstantStringClassName =
50627330f729Sjoerg           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
50637330f729Sjoerg                               : "$s10Foundation19_NSCFConstantStringCN";
50647330f729Sjoerg       Ty = IntPtrTy;
50657330f729Sjoerg       break;
50667330f729Sjoerg     case LangOptions::CoreFoundationABI::Swift4_2:
50677330f729Sjoerg       CFConstantStringClassName =
50687330f729Sjoerg           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
50697330f729Sjoerg                               : "$S10Foundation19_NSCFConstantStringCN";
50707330f729Sjoerg       Ty = IntPtrTy;
50717330f729Sjoerg       break;
50727330f729Sjoerg     case LangOptions::CoreFoundationABI::Swift4_1:
50737330f729Sjoerg       CFConstantStringClassName =
50747330f729Sjoerg           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
50757330f729Sjoerg                               : "__T010Foundation19_NSCFConstantStringCN";
50767330f729Sjoerg       Ty = IntPtrTy;
50777330f729Sjoerg       break;
50787330f729Sjoerg     }
50797330f729Sjoerg 
50807330f729Sjoerg     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
50817330f729Sjoerg 
50827330f729Sjoerg     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
50837330f729Sjoerg       llvm::GlobalValue *GV = nullptr;
50847330f729Sjoerg 
50857330f729Sjoerg       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
50867330f729Sjoerg         IdentifierInfo &II = Context.Idents.get(GV->getName());
50877330f729Sjoerg         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
50887330f729Sjoerg         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
50897330f729Sjoerg 
50907330f729Sjoerg         const VarDecl *VD = nullptr;
5091*e038c9c4Sjoerg         for (const auto *Result : DC->lookup(&II))
50927330f729Sjoerg           if ((VD = dyn_cast<VarDecl>(Result)))
50937330f729Sjoerg             break;
50947330f729Sjoerg 
50957330f729Sjoerg         if (Triple.isOSBinFormatELF()) {
50967330f729Sjoerg           if (!VD)
50977330f729Sjoerg             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
50987330f729Sjoerg         } else {
50997330f729Sjoerg           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
51007330f729Sjoerg           if (!VD || !VD->hasAttr<DLLExportAttr>())
51017330f729Sjoerg             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
51027330f729Sjoerg           else
51037330f729Sjoerg             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
51047330f729Sjoerg         }
51057330f729Sjoerg 
51067330f729Sjoerg         setDSOLocal(GV);
51077330f729Sjoerg       }
51087330f729Sjoerg     }
51097330f729Sjoerg 
51107330f729Sjoerg     // Decay array -> ptr
51117330f729Sjoerg     CFConstantStringClassRef =
51127330f729Sjoerg         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
51137330f729Sjoerg                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
51147330f729Sjoerg   }
51157330f729Sjoerg 
51167330f729Sjoerg   QualType CFTy = Context.getCFConstantStringType();
51177330f729Sjoerg 
51187330f729Sjoerg   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
51197330f729Sjoerg 
51207330f729Sjoerg   ConstantInitBuilder Builder(*this);
51217330f729Sjoerg   auto Fields = Builder.beginStruct(STy);
51227330f729Sjoerg 
51237330f729Sjoerg   // Class pointer.
51247330f729Sjoerg   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
51257330f729Sjoerg 
51267330f729Sjoerg   // Flags.
51277330f729Sjoerg   if (IsSwiftABI) {
51287330f729Sjoerg     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
51297330f729Sjoerg     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
51307330f729Sjoerg   } else {
51317330f729Sjoerg     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
51327330f729Sjoerg   }
51337330f729Sjoerg 
51347330f729Sjoerg   // String pointer.
51357330f729Sjoerg   llvm::Constant *C = nullptr;
51367330f729Sjoerg   if (isUTF16) {
51377330f729Sjoerg     auto Arr = llvm::makeArrayRef(
51387330f729Sjoerg         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
51397330f729Sjoerg         Entry.first().size() / 2);
51407330f729Sjoerg     C = llvm::ConstantDataArray::get(VMContext, Arr);
51417330f729Sjoerg   } else {
51427330f729Sjoerg     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
51437330f729Sjoerg   }
51447330f729Sjoerg 
51457330f729Sjoerg   // Note: -fwritable-strings doesn't make the backing store strings of
51467330f729Sjoerg   // CFStrings writable. (See <rdar://problem/10657500>)
51477330f729Sjoerg   auto *GV =
51487330f729Sjoerg       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
51497330f729Sjoerg                                llvm::GlobalValue::PrivateLinkage, C, ".str");
51507330f729Sjoerg   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
51517330f729Sjoerg   // Don't enforce the target's minimum global alignment, since the only use
51527330f729Sjoerg   // of the string is via this class initializer.
51537330f729Sjoerg   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
51547330f729Sjoerg                             : Context.getTypeAlignInChars(Context.CharTy);
51557330f729Sjoerg   GV->setAlignment(Align.getAsAlign());
51567330f729Sjoerg 
51577330f729Sjoerg   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
51587330f729Sjoerg   // Without it LLVM can merge the string with a non unnamed_addr one during
51597330f729Sjoerg   // LTO.  Doing that changes the section it ends in, which surprises ld64.
51607330f729Sjoerg   if (Triple.isOSBinFormatMachO())
51617330f729Sjoerg     GV->setSection(isUTF16 ? "__TEXT,__ustring"
51627330f729Sjoerg                            : "__TEXT,__cstring,cstring_literals");
51637330f729Sjoerg   // Make sure the literal ends up in .rodata to allow for safe ICF and for
51647330f729Sjoerg   // the static linker to adjust permissions to read-only later on.
51657330f729Sjoerg   else if (Triple.isOSBinFormatELF())
51667330f729Sjoerg     GV->setSection(".rodata");
51677330f729Sjoerg 
51687330f729Sjoerg   // String.
51697330f729Sjoerg   llvm::Constant *Str =
51707330f729Sjoerg       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
51717330f729Sjoerg 
51727330f729Sjoerg   if (isUTF16)
51737330f729Sjoerg     // Cast the UTF16 string to the correct type.
51747330f729Sjoerg     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
51757330f729Sjoerg   Fields.add(Str);
51767330f729Sjoerg 
51777330f729Sjoerg   // String length.
51787330f729Sjoerg   llvm::IntegerType *LengthTy =
51797330f729Sjoerg       llvm::IntegerType::get(getModule().getContext(),
51807330f729Sjoerg                              Context.getTargetInfo().getLongWidth());
51817330f729Sjoerg   if (IsSwiftABI) {
51827330f729Sjoerg     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
51837330f729Sjoerg         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
51847330f729Sjoerg       LengthTy = Int32Ty;
51857330f729Sjoerg     else
51867330f729Sjoerg       LengthTy = IntPtrTy;
51877330f729Sjoerg   }
51887330f729Sjoerg   Fields.addInt(LengthTy, StringLength);
51897330f729Sjoerg 
51907330f729Sjoerg   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
51917330f729Sjoerg   // properly aligned on 32-bit platforms.
51927330f729Sjoerg   CharUnits Alignment =
51937330f729Sjoerg       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
51947330f729Sjoerg 
51957330f729Sjoerg   // The struct.
51967330f729Sjoerg   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
51977330f729Sjoerg                                     /*isConstant=*/false,
51987330f729Sjoerg                                     llvm::GlobalVariable::PrivateLinkage);
51997330f729Sjoerg   GV->addAttribute("objc_arc_inert");
52007330f729Sjoerg   switch (Triple.getObjectFormat()) {
52017330f729Sjoerg   case llvm::Triple::UnknownObjectFormat:
52027330f729Sjoerg     llvm_unreachable("unknown file format");
5203*e038c9c4Sjoerg   case llvm::Triple::GOFF:
5204*e038c9c4Sjoerg     llvm_unreachable("GOFF is not yet implemented");
52057330f729Sjoerg   case llvm::Triple::XCOFF:
52067330f729Sjoerg     llvm_unreachable("XCOFF is not yet implemented");
52077330f729Sjoerg   case llvm::Triple::COFF:
52087330f729Sjoerg   case llvm::Triple::ELF:
52097330f729Sjoerg   case llvm::Triple::Wasm:
52107330f729Sjoerg     GV->setSection("cfstring");
52117330f729Sjoerg     break;
52127330f729Sjoerg   case llvm::Triple::MachO:
52137330f729Sjoerg     GV->setSection("__DATA,__cfstring");
52147330f729Sjoerg     break;
52157330f729Sjoerg   }
52167330f729Sjoerg   Entry.second = GV;
52177330f729Sjoerg 
52187330f729Sjoerg   return ConstantAddress(GV, Alignment);
52197330f729Sjoerg }
52207330f729Sjoerg 
getExpressionLocationsEnabled() const52217330f729Sjoerg bool CodeGenModule::getExpressionLocationsEnabled() const {
52227330f729Sjoerg   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
52237330f729Sjoerg }
52247330f729Sjoerg 
getObjCFastEnumerationStateType()52257330f729Sjoerg QualType CodeGenModule::getObjCFastEnumerationStateType() {
52267330f729Sjoerg   if (ObjCFastEnumerationStateType.isNull()) {
52277330f729Sjoerg     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
52287330f729Sjoerg     D->startDefinition();
52297330f729Sjoerg 
52307330f729Sjoerg     QualType FieldTypes[] = {
52317330f729Sjoerg       Context.UnsignedLongTy,
52327330f729Sjoerg       Context.getPointerType(Context.getObjCIdType()),
52337330f729Sjoerg       Context.getPointerType(Context.UnsignedLongTy),
52347330f729Sjoerg       Context.getConstantArrayType(Context.UnsignedLongTy,
52357330f729Sjoerg                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
52367330f729Sjoerg     };
52377330f729Sjoerg 
52387330f729Sjoerg     for (size_t i = 0; i < 4; ++i) {
52397330f729Sjoerg       FieldDecl *Field = FieldDecl::Create(Context,
52407330f729Sjoerg                                            D,
52417330f729Sjoerg                                            SourceLocation(),
52427330f729Sjoerg                                            SourceLocation(), nullptr,
52437330f729Sjoerg                                            FieldTypes[i], /*TInfo=*/nullptr,
52447330f729Sjoerg                                            /*BitWidth=*/nullptr,
52457330f729Sjoerg                                            /*Mutable=*/false,
52467330f729Sjoerg                                            ICIS_NoInit);
52477330f729Sjoerg       Field->setAccess(AS_public);
52487330f729Sjoerg       D->addDecl(Field);
52497330f729Sjoerg     }
52507330f729Sjoerg 
52517330f729Sjoerg     D->completeDefinition();
52527330f729Sjoerg     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
52537330f729Sjoerg   }
52547330f729Sjoerg 
52557330f729Sjoerg   return ObjCFastEnumerationStateType;
52567330f729Sjoerg }
52577330f729Sjoerg 
52587330f729Sjoerg llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)52597330f729Sjoerg CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
52607330f729Sjoerg   assert(!E->getType()->isPointerType() && "Strings are always arrays");
52617330f729Sjoerg 
52627330f729Sjoerg   // Don't emit it as the address of the string, emit the string data itself
52637330f729Sjoerg   // as an inline array.
52647330f729Sjoerg   if (E->getCharByteWidth() == 1) {
52657330f729Sjoerg     SmallString<64> Str(E->getString());
52667330f729Sjoerg 
52677330f729Sjoerg     // Resize the string to the right size, which is indicated by its type.
52687330f729Sjoerg     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
52697330f729Sjoerg     Str.resize(CAT->getSize().getZExtValue());
52707330f729Sjoerg     return llvm::ConstantDataArray::getString(VMContext, Str, false);
52717330f729Sjoerg   }
52727330f729Sjoerg 
52737330f729Sjoerg   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
52747330f729Sjoerg   llvm::Type *ElemTy = AType->getElementType();
52757330f729Sjoerg   unsigned NumElements = AType->getNumElements();
52767330f729Sjoerg 
52777330f729Sjoerg   // Wide strings have either 2-byte or 4-byte elements.
52787330f729Sjoerg   if (ElemTy->getPrimitiveSizeInBits() == 16) {
52797330f729Sjoerg     SmallVector<uint16_t, 32> Elements;
52807330f729Sjoerg     Elements.reserve(NumElements);
52817330f729Sjoerg 
52827330f729Sjoerg     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
52837330f729Sjoerg       Elements.push_back(E->getCodeUnit(i));
52847330f729Sjoerg     Elements.resize(NumElements);
52857330f729Sjoerg     return llvm::ConstantDataArray::get(VMContext, Elements);
52867330f729Sjoerg   }
52877330f729Sjoerg 
52887330f729Sjoerg   assert(ElemTy->getPrimitiveSizeInBits() == 32);
52897330f729Sjoerg   SmallVector<uint32_t, 32> Elements;
52907330f729Sjoerg   Elements.reserve(NumElements);
52917330f729Sjoerg 
52927330f729Sjoerg   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
52937330f729Sjoerg     Elements.push_back(E->getCodeUnit(i));
52947330f729Sjoerg   Elements.resize(NumElements);
52957330f729Sjoerg   return llvm::ConstantDataArray::get(VMContext, Elements);
52967330f729Sjoerg }
52977330f729Sjoerg 
52987330f729Sjoerg static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,CharUnits Alignment)52997330f729Sjoerg GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
53007330f729Sjoerg                       CodeGenModule &CGM, StringRef GlobalName,
53017330f729Sjoerg                       CharUnits Alignment) {
53027330f729Sjoerg   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5303*e038c9c4Sjoerg       CGM.GetGlobalConstantAddressSpace());
53047330f729Sjoerg 
53057330f729Sjoerg   llvm::Module &M = CGM.getModule();
53067330f729Sjoerg   // Create a global variable for this string
53077330f729Sjoerg   auto *GV = new llvm::GlobalVariable(
53087330f729Sjoerg       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
53097330f729Sjoerg       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
53107330f729Sjoerg   GV->setAlignment(Alignment.getAsAlign());
53117330f729Sjoerg   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
53127330f729Sjoerg   if (GV->isWeakForLinker()) {
53137330f729Sjoerg     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
53147330f729Sjoerg     GV->setComdat(M.getOrInsertComdat(GV->getName()));
53157330f729Sjoerg   }
53167330f729Sjoerg   CGM.setDSOLocal(GV);
53177330f729Sjoerg 
53187330f729Sjoerg   return GV;
53197330f729Sjoerg }
53207330f729Sjoerg 
53217330f729Sjoerg /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
53227330f729Sjoerg /// constant array for the given string literal.
53237330f729Sjoerg ConstantAddress
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)53247330f729Sjoerg CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
53257330f729Sjoerg                                                   StringRef Name) {
53267330f729Sjoerg   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
53277330f729Sjoerg 
53287330f729Sjoerg   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
53297330f729Sjoerg   llvm::GlobalVariable **Entry = nullptr;
53307330f729Sjoerg   if (!LangOpts.WritableStrings) {
53317330f729Sjoerg     Entry = &ConstantStringMap[C];
53327330f729Sjoerg     if (auto GV = *Entry) {
53337330f729Sjoerg       if (Alignment.getQuantity() > GV->getAlignment())
53347330f729Sjoerg         GV->setAlignment(Alignment.getAsAlign());
53357330f729Sjoerg       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53367330f729Sjoerg                              Alignment);
53377330f729Sjoerg     }
53387330f729Sjoerg   }
53397330f729Sjoerg 
53407330f729Sjoerg   SmallString<256> MangledNameBuffer;
53417330f729Sjoerg   StringRef GlobalVariableName;
53427330f729Sjoerg   llvm::GlobalValue::LinkageTypes LT;
53437330f729Sjoerg 
53447330f729Sjoerg   // Mangle the string literal if that's how the ABI merges duplicate strings.
53457330f729Sjoerg   // Don't do it if they are writable, since we don't want writes in one TU to
53467330f729Sjoerg   // affect strings in another.
53477330f729Sjoerg   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
53487330f729Sjoerg       !LangOpts.WritableStrings) {
53497330f729Sjoerg     llvm::raw_svector_ostream Out(MangledNameBuffer);
53507330f729Sjoerg     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
53517330f729Sjoerg     LT = llvm::GlobalValue::LinkOnceODRLinkage;
53527330f729Sjoerg     GlobalVariableName = MangledNameBuffer;
53537330f729Sjoerg   } else {
53547330f729Sjoerg     LT = llvm::GlobalValue::PrivateLinkage;
53557330f729Sjoerg     GlobalVariableName = Name;
53567330f729Sjoerg   }
53577330f729Sjoerg 
53587330f729Sjoerg   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
53597330f729Sjoerg   if (Entry)
53607330f729Sjoerg     *Entry = GV;
53617330f729Sjoerg 
53627330f729Sjoerg   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
53637330f729Sjoerg                                   QualType());
53647330f729Sjoerg 
53657330f729Sjoerg   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53667330f729Sjoerg                          Alignment);
53677330f729Sjoerg }
53687330f729Sjoerg 
53697330f729Sjoerg /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
53707330f729Sjoerg /// array for the given ObjCEncodeExpr node.
53717330f729Sjoerg ConstantAddress
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)53727330f729Sjoerg CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
53737330f729Sjoerg   std::string Str;
53747330f729Sjoerg   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
53757330f729Sjoerg 
53767330f729Sjoerg   return GetAddrOfConstantCString(Str);
53777330f729Sjoerg }
53787330f729Sjoerg 
53797330f729Sjoerg /// GetAddrOfConstantCString - Returns a pointer to a character array containing
53807330f729Sjoerg /// the literal and a terminating '\0' character.
53817330f729Sjoerg /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName)53827330f729Sjoerg ConstantAddress CodeGenModule::GetAddrOfConstantCString(
53837330f729Sjoerg     const std::string &Str, const char *GlobalName) {
53847330f729Sjoerg   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
53857330f729Sjoerg   CharUnits Alignment =
53867330f729Sjoerg     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
53877330f729Sjoerg 
53887330f729Sjoerg   llvm::Constant *C =
53897330f729Sjoerg       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
53907330f729Sjoerg 
53917330f729Sjoerg   // Don't share any string literals if strings aren't constant.
53927330f729Sjoerg   llvm::GlobalVariable **Entry = nullptr;
53937330f729Sjoerg   if (!LangOpts.WritableStrings) {
53947330f729Sjoerg     Entry = &ConstantStringMap[C];
53957330f729Sjoerg     if (auto GV = *Entry) {
53967330f729Sjoerg       if (Alignment.getQuantity() > GV->getAlignment())
53977330f729Sjoerg         GV->setAlignment(Alignment.getAsAlign());
53987330f729Sjoerg       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53997330f729Sjoerg                              Alignment);
54007330f729Sjoerg     }
54017330f729Sjoerg   }
54027330f729Sjoerg 
54037330f729Sjoerg   // Get the default prefix if a name wasn't specified.
54047330f729Sjoerg   if (!GlobalName)
54057330f729Sjoerg     GlobalName = ".str";
54067330f729Sjoerg   // Create a global variable for this.
54077330f729Sjoerg   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
54087330f729Sjoerg                                   GlobalName, Alignment);
54097330f729Sjoerg   if (Entry)
54107330f729Sjoerg     *Entry = GV;
54117330f729Sjoerg 
54127330f729Sjoerg   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
54137330f729Sjoerg                          Alignment);
54147330f729Sjoerg }
54157330f729Sjoerg 
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)54167330f729Sjoerg ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
54177330f729Sjoerg     const MaterializeTemporaryExpr *E, const Expr *Init) {
54187330f729Sjoerg   assert((E->getStorageDuration() == SD_Static ||
54197330f729Sjoerg           E->getStorageDuration() == SD_Thread) && "not a global temporary");
54207330f729Sjoerg   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
54217330f729Sjoerg 
54227330f729Sjoerg   // If we're not materializing a subobject of the temporary, keep the
54237330f729Sjoerg   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
54247330f729Sjoerg   QualType MaterializedType = Init->getType();
5425*e038c9c4Sjoerg   if (Init == E->getSubExpr())
54267330f729Sjoerg     MaterializedType = E->getType();
54277330f729Sjoerg 
54287330f729Sjoerg   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
54297330f729Sjoerg 
5430*e038c9c4Sjoerg   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5431*e038c9c4Sjoerg   if (!InsertResult.second) {
5432*e038c9c4Sjoerg     // We've seen this before: either we already created it or we're in the
5433*e038c9c4Sjoerg     // process of doing so.
5434*e038c9c4Sjoerg     if (!InsertResult.first->second) {
5435*e038c9c4Sjoerg       // We recursively re-entered this function, probably during emission of
5436*e038c9c4Sjoerg       // the initializer. Create a placeholder. We'll clean this up in the
5437*e038c9c4Sjoerg       // outer call, at the end of this function.
5438*e038c9c4Sjoerg       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5439*e038c9c4Sjoerg       InsertResult.first->second = new llvm::GlobalVariable(
5440*e038c9c4Sjoerg           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5441*e038c9c4Sjoerg           nullptr);
5442*e038c9c4Sjoerg     }
5443*e038c9c4Sjoerg     return ConstantAddress(InsertResult.first->second, Align);
5444*e038c9c4Sjoerg   }
54457330f729Sjoerg 
54467330f729Sjoerg   // FIXME: If an externally-visible declaration extends multiple temporaries,
54477330f729Sjoerg   // we need to give each temporary the same name in every translation unit (and
54487330f729Sjoerg   // we also need to make the temporaries externally-visible).
54497330f729Sjoerg   SmallString<256> Name;
54507330f729Sjoerg   llvm::raw_svector_ostream Out(Name);
54517330f729Sjoerg   getCXXABI().getMangleContext().mangleReferenceTemporary(
54527330f729Sjoerg       VD, E->getManglingNumber(), Out);
54537330f729Sjoerg 
54547330f729Sjoerg   APValue *Value = nullptr;
54557330f729Sjoerg   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
54567330f729Sjoerg     // If the initializer of the extending declaration is a constant
54577330f729Sjoerg     // initializer, we should have a cached constant initializer for this
54587330f729Sjoerg     // temporary. Note that this might have a different value from the value
54597330f729Sjoerg     // computed by evaluating the initializer if the surrounding constant
54607330f729Sjoerg     // expression modifies the temporary.
5461*e038c9c4Sjoerg     Value = E->getOrCreateValue(false);
54627330f729Sjoerg   }
54637330f729Sjoerg 
54647330f729Sjoerg   // Try evaluating it now, it might have a constant initializer.
54657330f729Sjoerg   Expr::EvalResult EvalResult;
54667330f729Sjoerg   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
54677330f729Sjoerg       !EvalResult.hasSideEffects())
54687330f729Sjoerg     Value = &EvalResult.Val;
54697330f729Sjoerg 
54707330f729Sjoerg   LangAS AddrSpace =
54717330f729Sjoerg       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
54727330f729Sjoerg 
54737330f729Sjoerg   Optional<ConstantEmitter> emitter;
54747330f729Sjoerg   llvm::Constant *InitialValue = nullptr;
54757330f729Sjoerg   bool Constant = false;
54767330f729Sjoerg   llvm::Type *Type;
54777330f729Sjoerg   if (Value) {
54787330f729Sjoerg     // The temporary has a constant initializer, use it.
54797330f729Sjoerg     emitter.emplace(*this);
54807330f729Sjoerg     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
54817330f729Sjoerg                                                MaterializedType);
54827330f729Sjoerg     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
54837330f729Sjoerg     Type = InitialValue->getType();
54847330f729Sjoerg   } else {
54857330f729Sjoerg     // No initializer, the initialization will be provided when we
54867330f729Sjoerg     // initialize the declaration which performed lifetime extension.
54877330f729Sjoerg     Type = getTypes().ConvertTypeForMem(MaterializedType);
54887330f729Sjoerg   }
54897330f729Sjoerg 
54907330f729Sjoerg   // Create a global variable for this lifetime-extended temporary.
54917330f729Sjoerg   llvm::GlobalValue::LinkageTypes Linkage =
54927330f729Sjoerg       getLLVMLinkageVarDefinition(VD, Constant);
54937330f729Sjoerg   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
54947330f729Sjoerg     const VarDecl *InitVD;
54957330f729Sjoerg     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
54967330f729Sjoerg         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
54977330f729Sjoerg       // Temporaries defined inside a class get linkonce_odr linkage because the
54987330f729Sjoerg       // class can be defined in multiple translation units.
54997330f729Sjoerg       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
55007330f729Sjoerg     } else {
55017330f729Sjoerg       // There is no need for this temporary to have external linkage if the
55027330f729Sjoerg       // VarDecl has external linkage.
55037330f729Sjoerg       Linkage = llvm::GlobalVariable::InternalLinkage;
55047330f729Sjoerg     }
55057330f729Sjoerg   }
55067330f729Sjoerg   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
55077330f729Sjoerg   auto *GV = new llvm::GlobalVariable(
55087330f729Sjoerg       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
55097330f729Sjoerg       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
55107330f729Sjoerg   if (emitter) emitter->finalize(GV);
55117330f729Sjoerg   setGVProperties(GV, VD);
55127330f729Sjoerg   GV->setAlignment(Align.getAsAlign());
55137330f729Sjoerg   if (supportsCOMDAT() && GV->isWeakForLinker())
55147330f729Sjoerg     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
55157330f729Sjoerg   if (VD->getTLSKind())
55167330f729Sjoerg     setTLSMode(GV, *VD);
55177330f729Sjoerg   llvm::Constant *CV = GV;
55187330f729Sjoerg   if (AddrSpace != LangAS::Default)
55197330f729Sjoerg     CV = getTargetCodeGenInfo().performAddrSpaceCast(
55207330f729Sjoerg         *this, GV, AddrSpace, LangAS::Default,
55217330f729Sjoerg         Type->getPointerTo(
55227330f729Sjoerg             getContext().getTargetAddressSpace(LangAS::Default)));
5523*e038c9c4Sjoerg 
5524*e038c9c4Sjoerg   // Update the map with the new temporary. If we created a placeholder above,
5525*e038c9c4Sjoerg   // replace it with the new global now.
5526*e038c9c4Sjoerg   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5527*e038c9c4Sjoerg   if (Entry) {
5528*e038c9c4Sjoerg     Entry->replaceAllUsesWith(
5529*e038c9c4Sjoerg         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5530*e038c9c4Sjoerg     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5531*e038c9c4Sjoerg   }
5532*e038c9c4Sjoerg   Entry = CV;
5533*e038c9c4Sjoerg 
55347330f729Sjoerg   return ConstantAddress(CV, Align);
55357330f729Sjoerg }
55367330f729Sjoerg 
55377330f729Sjoerg /// EmitObjCPropertyImplementations - Emit information for synthesized
55387330f729Sjoerg /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)55397330f729Sjoerg void CodeGenModule::EmitObjCPropertyImplementations(const
55407330f729Sjoerg                                                     ObjCImplementationDecl *D) {
55417330f729Sjoerg   for (const auto *PID : D->property_impls()) {
55427330f729Sjoerg     // Dynamic is just for type-checking.
55437330f729Sjoerg     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
55447330f729Sjoerg       ObjCPropertyDecl *PD = PID->getPropertyDecl();
55457330f729Sjoerg 
55467330f729Sjoerg       // Determine which methods need to be implemented, some may have
55477330f729Sjoerg       // been overridden. Note that ::isPropertyAccessor is not the method
55487330f729Sjoerg       // we want, that just indicates if the decl came from a
55497330f729Sjoerg       // property. What we want to know is if the method is defined in
55507330f729Sjoerg       // this implementation.
5551*e038c9c4Sjoerg       auto *Getter = PID->getGetterMethodDecl();
5552*e038c9c4Sjoerg       if (!Getter || Getter->isSynthesizedAccessorStub())
55537330f729Sjoerg         CodeGenFunction(*this).GenerateObjCGetter(
55547330f729Sjoerg             const_cast<ObjCImplementationDecl *>(D), PID);
5555*e038c9c4Sjoerg       auto *Setter = PID->getSetterMethodDecl();
5556*e038c9c4Sjoerg       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
55577330f729Sjoerg         CodeGenFunction(*this).GenerateObjCSetter(
55587330f729Sjoerg                                  const_cast<ObjCImplementationDecl *>(D), PID);
55597330f729Sjoerg     }
55607330f729Sjoerg   }
55617330f729Sjoerg }
55627330f729Sjoerg 
needsDestructMethod(ObjCImplementationDecl * impl)55637330f729Sjoerg static bool needsDestructMethod(ObjCImplementationDecl *impl) {
55647330f729Sjoerg   const ObjCInterfaceDecl *iface = impl->getClassInterface();
55657330f729Sjoerg   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
55667330f729Sjoerg        ivar; ivar = ivar->getNextIvar())
55677330f729Sjoerg     if (ivar->getType().isDestructedType())
55687330f729Sjoerg       return true;
55697330f729Sjoerg 
55707330f729Sjoerg   return false;
55717330f729Sjoerg }
55727330f729Sjoerg 
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)55737330f729Sjoerg static bool AllTrivialInitializers(CodeGenModule &CGM,
55747330f729Sjoerg                                    ObjCImplementationDecl *D) {
55757330f729Sjoerg   CodeGenFunction CGF(CGM);
55767330f729Sjoerg   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
55777330f729Sjoerg        E = D->init_end(); B != E; ++B) {
55787330f729Sjoerg     CXXCtorInitializer *CtorInitExp = *B;
55797330f729Sjoerg     Expr *Init = CtorInitExp->getInit();
55807330f729Sjoerg     if (!CGF.isTrivialInitializer(Init))
55817330f729Sjoerg       return false;
55827330f729Sjoerg   }
55837330f729Sjoerg   return true;
55847330f729Sjoerg }
55857330f729Sjoerg 
55867330f729Sjoerg /// EmitObjCIvarInitializations - Emit information for ivar initialization
55877330f729Sjoerg /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)55887330f729Sjoerg void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
55897330f729Sjoerg   // We might need a .cxx_destruct even if we don't have any ivar initializers.
55907330f729Sjoerg   if (needsDestructMethod(D)) {
55917330f729Sjoerg     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
55927330f729Sjoerg     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5593*e038c9c4Sjoerg     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5594*e038c9c4Sjoerg         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5595*e038c9c4Sjoerg         getContext().VoidTy, nullptr, D,
55967330f729Sjoerg         /*isInstance=*/true, /*isVariadic=*/false,
5597*e038c9c4Sjoerg         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5598*e038c9c4Sjoerg         /*isImplicitlyDeclared=*/true,
55997330f729Sjoerg         /*isDefined=*/false, ObjCMethodDecl::Required);
56007330f729Sjoerg     D->addInstanceMethod(DTORMethod);
56017330f729Sjoerg     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
56027330f729Sjoerg     D->setHasDestructors(true);
56037330f729Sjoerg   }
56047330f729Sjoerg 
56057330f729Sjoerg   // If the implementation doesn't have any ivar initializers, we don't need
56067330f729Sjoerg   // a .cxx_construct.
56077330f729Sjoerg   if (D->getNumIvarInitializers() == 0 ||
56087330f729Sjoerg       AllTrivialInitializers(*this, D))
56097330f729Sjoerg     return;
56107330f729Sjoerg 
56117330f729Sjoerg   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
56127330f729Sjoerg   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
56137330f729Sjoerg   // The constructor returns 'self'.
5614*e038c9c4Sjoerg   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5615*e038c9c4Sjoerg       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5616*e038c9c4Sjoerg       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
56177330f729Sjoerg       /*isVariadic=*/false,
5618*e038c9c4Sjoerg       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
56197330f729Sjoerg       /*isImplicitlyDeclared=*/true,
5620*e038c9c4Sjoerg       /*isDefined=*/false, ObjCMethodDecl::Required);
56217330f729Sjoerg   D->addInstanceMethod(CTORMethod);
56227330f729Sjoerg   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
56237330f729Sjoerg   D->setHasNonZeroConstructors(true);
56247330f729Sjoerg }
56257330f729Sjoerg 
56267330f729Sjoerg // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)56277330f729Sjoerg void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
56287330f729Sjoerg   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5629*e038c9c4Sjoerg       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
56307330f729Sjoerg     ErrorUnsupported(LSD, "linkage spec");
56317330f729Sjoerg     return;
56327330f729Sjoerg   }
56337330f729Sjoerg 
56347330f729Sjoerg   EmitDeclContext(LSD);
56357330f729Sjoerg }
56367330f729Sjoerg 
EmitDeclContext(const DeclContext * DC)56377330f729Sjoerg void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
56387330f729Sjoerg   for (auto *I : DC->decls()) {
56397330f729Sjoerg     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
56407330f729Sjoerg     // are themselves considered "top-level", so EmitTopLevelDecl on an
56417330f729Sjoerg     // ObjCImplDecl does not recursively visit them. We need to do that in
56427330f729Sjoerg     // case they're nested inside another construct (LinkageSpecDecl /
56437330f729Sjoerg     // ExportDecl) that does stop them from being considered "top-level".
56447330f729Sjoerg     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
56457330f729Sjoerg       for (auto *M : OID->methods())
56467330f729Sjoerg         EmitTopLevelDecl(M);
56477330f729Sjoerg     }
56487330f729Sjoerg 
56497330f729Sjoerg     EmitTopLevelDecl(I);
56507330f729Sjoerg   }
56517330f729Sjoerg }
56527330f729Sjoerg 
56537330f729Sjoerg /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)56547330f729Sjoerg void CodeGenModule::EmitTopLevelDecl(Decl *D) {
56557330f729Sjoerg   // Ignore dependent declarations.
56567330f729Sjoerg   if (D->isTemplated())
56577330f729Sjoerg     return;
56587330f729Sjoerg 
5659*e038c9c4Sjoerg   // Consteval function shouldn't be emitted.
5660*e038c9c4Sjoerg   if (auto *FD = dyn_cast<FunctionDecl>(D))
5661*e038c9c4Sjoerg     if (FD->isConsteval())
5662*e038c9c4Sjoerg       return;
5663*e038c9c4Sjoerg 
56647330f729Sjoerg   switch (D->getKind()) {
56657330f729Sjoerg   case Decl::CXXConversion:
56667330f729Sjoerg   case Decl::CXXMethod:
56677330f729Sjoerg   case Decl::Function:
56687330f729Sjoerg     EmitGlobal(cast<FunctionDecl>(D));
56697330f729Sjoerg     // Always provide some coverage mapping
56707330f729Sjoerg     // even for the functions that aren't emitted.
56717330f729Sjoerg     AddDeferredUnusedCoverageMapping(D);
56727330f729Sjoerg     break;
56737330f729Sjoerg 
56747330f729Sjoerg   case Decl::CXXDeductionGuide:
56757330f729Sjoerg     // Function-like, but does not result in code emission.
56767330f729Sjoerg     break;
56777330f729Sjoerg 
56787330f729Sjoerg   case Decl::Var:
56797330f729Sjoerg   case Decl::Decomposition:
56807330f729Sjoerg   case Decl::VarTemplateSpecialization:
56817330f729Sjoerg     EmitGlobal(cast<VarDecl>(D));
56827330f729Sjoerg     if (auto *DD = dyn_cast<DecompositionDecl>(D))
56837330f729Sjoerg       for (auto *B : DD->bindings())
56847330f729Sjoerg         if (auto *HD = B->getHoldingVar())
56857330f729Sjoerg           EmitGlobal(HD);
56867330f729Sjoerg     break;
56877330f729Sjoerg 
56887330f729Sjoerg   // Indirect fields from global anonymous structs and unions can be
56897330f729Sjoerg   // ignored; only the actual variable requires IR gen support.
56907330f729Sjoerg   case Decl::IndirectField:
56917330f729Sjoerg     break;
56927330f729Sjoerg 
56937330f729Sjoerg   // C++ Decls
56947330f729Sjoerg   case Decl::Namespace:
56957330f729Sjoerg     EmitDeclContext(cast<NamespaceDecl>(D));
56967330f729Sjoerg     break;
56977330f729Sjoerg   case Decl::ClassTemplateSpecialization: {
56987330f729Sjoerg     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5699*e038c9c4Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
5700*e038c9c4Sjoerg       if (Spec->getSpecializationKind() ==
5701*e038c9c4Sjoerg               TSK_ExplicitInstantiationDefinition &&
57027330f729Sjoerg           Spec->hasDefinition())
5703*e038c9c4Sjoerg         DI->completeTemplateDefinition(*Spec);
57047330f729Sjoerg   } LLVM_FALLTHROUGH;
5705*e038c9c4Sjoerg   case Decl::CXXRecord: {
5706*e038c9c4Sjoerg     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5707*e038c9c4Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5708*e038c9c4Sjoerg       if (CRD->hasDefinition())
5709*e038c9c4Sjoerg         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
57107330f729Sjoerg       if (auto *ES = D->getASTContext().getExternalSource())
57117330f729Sjoerg         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5712*e038c9c4Sjoerg           DI->completeUnusedClass(*CRD);
57137330f729Sjoerg     }
57147330f729Sjoerg     // Emit any static data members, they may be definitions.
5715*e038c9c4Sjoerg     for (auto *I : CRD->decls())
57167330f729Sjoerg       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
57177330f729Sjoerg         EmitTopLevelDecl(I);
57187330f729Sjoerg     break;
5719*e038c9c4Sjoerg   }
57207330f729Sjoerg     // No code generation needed.
57217330f729Sjoerg   case Decl::UsingShadow:
57227330f729Sjoerg   case Decl::ClassTemplate:
57237330f729Sjoerg   case Decl::VarTemplate:
57247330f729Sjoerg   case Decl::Concept:
57257330f729Sjoerg   case Decl::VarTemplatePartialSpecialization:
57267330f729Sjoerg   case Decl::FunctionTemplate:
57277330f729Sjoerg   case Decl::TypeAliasTemplate:
57287330f729Sjoerg   case Decl::Block:
57297330f729Sjoerg   case Decl::Empty:
57307330f729Sjoerg   case Decl::Binding:
57317330f729Sjoerg     break;
57327330f729Sjoerg   case Decl::Using:          // using X; [C++]
57337330f729Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
57347330f729Sjoerg         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5735*e038c9c4Sjoerg     break;
57367330f729Sjoerg   case Decl::NamespaceAlias:
57377330f729Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
57387330f729Sjoerg         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5739*e038c9c4Sjoerg     break;
57407330f729Sjoerg   case Decl::UsingDirective: // using namespace X; [C++]
57417330f729Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
57427330f729Sjoerg       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5743*e038c9c4Sjoerg     break;
57447330f729Sjoerg   case Decl::CXXConstructor:
57457330f729Sjoerg     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
57467330f729Sjoerg     break;
57477330f729Sjoerg   case Decl::CXXDestructor:
57487330f729Sjoerg     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
57497330f729Sjoerg     break;
57507330f729Sjoerg 
57517330f729Sjoerg   case Decl::StaticAssert:
57527330f729Sjoerg     // Nothing to do.
57537330f729Sjoerg     break;
57547330f729Sjoerg 
57557330f729Sjoerg   // Objective-C Decls
57567330f729Sjoerg 
57577330f729Sjoerg   // Forward declarations, no (immediate) code generation.
57587330f729Sjoerg   case Decl::ObjCInterface:
57597330f729Sjoerg   case Decl::ObjCCategory:
57607330f729Sjoerg     break;
57617330f729Sjoerg 
57627330f729Sjoerg   case Decl::ObjCProtocol: {
57637330f729Sjoerg     auto *Proto = cast<ObjCProtocolDecl>(D);
57647330f729Sjoerg     if (Proto->isThisDeclarationADefinition())
57657330f729Sjoerg       ObjCRuntime->GenerateProtocol(Proto);
57667330f729Sjoerg     break;
57677330f729Sjoerg   }
57687330f729Sjoerg 
57697330f729Sjoerg   case Decl::ObjCCategoryImpl:
57707330f729Sjoerg     // Categories have properties but don't support synthesize so we
57717330f729Sjoerg     // can ignore them here.
57727330f729Sjoerg     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
57737330f729Sjoerg     break;
57747330f729Sjoerg 
57757330f729Sjoerg   case Decl::ObjCImplementation: {
57767330f729Sjoerg     auto *OMD = cast<ObjCImplementationDecl>(D);
57777330f729Sjoerg     EmitObjCPropertyImplementations(OMD);
57787330f729Sjoerg     EmitObjCIvarInitializations(OMD);
57797330f729Sjoerg     ObjCRuntime->GenerateClass(OMD);
57807330f729Sjoerg     // Emit global variable debug information.
57817330f729Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
5782*e038c9c4Sjoerg       if (getCodeGenOpts().hasReducedDebugInfo())
57837330f729Sjoerg         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
57847330f729Sjoerg             OMD->getClassInterface()), OMD->getLocation());
57857330f729Sjoerg     break;
57867330f729Sjoerg   }
57877330f729Sjoerg   case Decl::ObjCMethod: {
57887330f729Sjoerg     auto *OMD = cast<ObjCMethodDecl>(D);
57897330f729Sjoerg     // If this is not a prototype, emit the body.
57907330f729Sjoerg     if (OMD->getBody())
57917330f729Sjoerg       CodeGenFunction(*this).GenerateObjCMethod(OMD);
57927330f729Sjoerg     break;
57937330f729Sjoerg   }
57947330f729Sjoerg   case Decl::ObjCCompatibleAlias:
57957330f729Sjoerg     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
57967330f729Sjoerg     break;
57977330f729Sjoerg 
57987330f729Sjoerg   case Decl::PragmaComment: {
57997330f729Sjoerg     const auto *PCD = cast<PragmaCommentDecl>(D);
58007330f729Sjoerg     switch (PCD->getCommentKind()) {
58017330f729Sjoerg     case PCK_Unknown:
58027330f729Sjoerg       llvm_unreachable("unexpected pragma comment kind");
58037330f729Sjoerg     case PCK_Linker:
58047330f729Sjoerg       AppendLinkerOptions(PCD->getArg());
58057330f729Sjoerg       break;
58067330f729Sjoerg     case PCK_Lib:
58077330f729Sjoerg         AddDependentLib(PCD->getArg());
58087330f729Sjoerg       break;
58097330f729Sjoerg     case PCK_Compiler:
58107330f729Sjoerg     case PCK_ExeStr:
58117330f729Sjoerg     case PCK_User:
58127330f729Sjoerg       break; // We ignore all of these.
58137330f729Sjoerg     }
58147330f729Sjoerg     break;
58157330f729Sjoerg   }
58167330f729Sjoerg 
58177330f729Sjoerg   case Decl::PragmaDetectMismatch: {
58187330f729Sjoerg     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
58197330f729Sjoerg     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
58207330f729Sjoerg     break;
58217330f729Sjoerg   }
58227330f729Sjoerg 
58237330f729Sjoerg   case Decl::LinkageSpec:
58247330f729Sjoerg     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
58257330f729Sjoerg     break;
58267330f729Sjoerg 
58277330f729Sjoerg   case Decl::FileScopeAsm: {
58287330f729Sjoerg     // File-scope asm is ignored during device-side CUDA compilation.
58297330f729Sjoerg     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
58307330f729Sjoerg       break;
58317330f729Sjoerg     // File-scope asm is ignored during device-side OpenMP compilation.
58327330f729Sjoerg     if (LangOpts.OpenMPIsDevice)
58337330f729Sjoerg       break;
5834*e038c9c4Sjoerg     // File-scope asm is ignored during device-side SYCL compilation.
5835*e038c9c4Sjoerg     if (LangOpts.SYCLIsDevice)
5836*e038c9c4Sjoerg       break;
58377330f729Sjoerg     auto *AD = cast<FileScopeAsmDecl>(D);
58387330f729Sjoerg     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
58397330f729Sjoerg     break;
58407330f729Sjoerg   }
58417330f729Sjoerg 
58427330f729Sjoerg   case Decl::Import: {
58437330f729Sjoerg     auto *Import = cast<ImportDecl>(D);
58447330f729Sjoerg 
58457330f729Sjoerg     // If we've already imported this module, we're done.
58467330f729Sjoerg     if (!ImportedModules.insert(Import->getImportedModule()))
58477330f729Sjoerg       break;
58487330f729Sjoerg 
58497330f729Sjoerg     // Emit debug information for direct imports.
58507330f729Sjoerg     if (!Import->getImportedOwningModule()) {
58517330f729Sjoerg       if (CGDebugInfo *DI = getModuleDebugInfo())
58527330f729Sjoerg         DI->EmitImportDecl(*Import);
58537330f729Sjoerg     }
58547330f729Sjoerg 
58557330f729Sjoerg     // Find all of the submodules and emit the module initializers.
58567330f729Sjoerg     llvm::SmallPtrSet<clang::Module *, 16> Visited;
58577330f729Sjoerg     SmallVector<clang::Module *, 16> Stack;
58587330f729Sjoerg     Visited.insert(Import->getImportedModule());
58597330f729Sjoerg     Stack.push_back(Import->getImportedModule());
58607330f729Sjoerg 
58617330f729Sjoerg     while (!Stack.empty()) {
58627330f729Sjoerg       clang::Module *Mod = Stack.pop_back_val();
58637330f729Sjoerg       if (!EmittedModuleInitializers.insert(Mod).second)
58647330f729Sjoerg         continue;
58657330f729Sjoerg 
58667330f729Sjoerg       for (auto *D : Context.getModuleInitializers(Mod))
58677330f729Sjoerg         EmitTopLevelDecl(D);
58687330f729Sjoerg 
58697330f729Sjoerg       // Visit the submodules of this module.
58707330f729Sjoerg       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
58717330f729Sjoerg                                              SubEnd = Mod->submodule_end();
58727330f729Sjoerg            Sub != SubEnd; ++Sub) {
58737330f729Sjoerg         // Skip explicit children; they need to be explicitly imported to emit
58747330f729Sjoerg         // the initializers.
58757330f729Sjoerg         if ((*Sub)->IsExplicit)
58767330f729Sjoerg           continue;
58777330f729Sjoerg 
58787330f729Sjoerg         if (Visited.insert(*Sub).second)
58797330f729Sjoerg           Stack.push_back(*Sub);
58807330f729Sjoerg       }
58817330f729Sjoerg     }
58827330f729Sjoerg     break;
58837330f729Sjoerg   }
58847330f729Sjoerg 
58857330f729Sjoerg   case Decl::Export:
58867330f729Sjoerg     EmitDeclContext(cast<ExportDecl>(D));
58877330f729Sjoerg     break;
58887330f729Sjoerg 
58897330f729Sjoerg   case Decl::OMPThreadPrivate:
58907330f729Sjoerg     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
58917330f729Sjoerg     break;
58927330f729Sjoerg 
58937330f729Sjoerg   case Decl::OMPAllocate:
5894*e038c9c4Sjoerg     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
58957330f729Sjoerg     break;
58967330f729Sjoerg 
58977330f729Sjoerg   case Decl::OMPDeclareReduction:
58987330f729Sjoerg     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
58997330f729Sjoerg     break;
59007330f729Sjoerg 
59017330f729Sjoerg   case Decl::OMPDeclareMapper:
59027330f729Sjoerg     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
59037330f729Sjoerg     break;
59047330f729Sjoerg 
59057330f729Sjoerg   case Decl::OMPRequires:
59067330f729Sjoerg     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
59077330f729Sjoerg     break;
59087330f729Sjoerg 
5909*e038c9c4Sjoerg   case Decl::Typedef:
5910*e038c9c4Sjoerg   case Decl::TypeAlias: // using foo = bar; [C++11]
5911*e038c9c4Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
5912*e038c9c4Sjoerg       DI->EmitAndRetainType(
5913*e038c9c4Sjoerg           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5914*e038c9c4Sjoerg     break;
5915*e038c9c4Sjoerg 
5916*e038c9c4Sjoerg   case Decl::Record:
5917*e038c9c4Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
5918*e038c9c4Sjoerg       if (cast<RecordDecl>(D)->getDefinition())
5919*e038c9c4Sjoerg         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5920*e038c9c4Sjoerg     break;
5921*e038c9c4Sjoerg 
5922*e038c9c4Sjoerg   case Decl::Enum:
5923*e038c9c4Sjoerg     if (CGDebugInfo *DI = getModuleDebugInfo())
5924*e038c9c4Sjoerg       if (cast<EnumDecl>(D)->getDefinition())
5925*e038c9c4Sjoerg         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5926*e038c9c4Sjoerg     break;
5927*e038c9c4Sjoerg 
59287330f729Sjoerg   default:
59297330f729Sjoerg     // Make sure we handled everything we should, every other kind is a
59307330f729Sjoerg     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
59317330f729Sjoerg     // function. Need to recode Decl::Kind to do that easily.
59327330f729Sjoerg     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
59337330f729Sjoerg     break;
59347330f729Sjoerg   }
59357330f729Sjoerg }
59367330f729Sjoerg 
AddDeferredUnusedCoverageMapping(Decl * D)59377330f729Sjoerg void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
59387330f729Sjoerg   // Do we need to generate coverage mapping?
59397330f729Sjoerg   if (!CodeGenOpts.CoverageMapping)
59407330f729Sjoerg     return;
59417330f729Sjoerg   switch (D->getKind()) {
59427330f729Sjoerg   case Decl::CXXConversion:
59437330f729Sjoerg   case Decl::CXXMethod:
59447330f729Sjoerg   case Decl::Function:
59457330f729Sjoerg   case Decl::ObjCMethod:
59467330f729Sjoerg   case Decl::CXXConstructor:
59477330f729Sjoerg   case Decl::CXXDestructor: {
59487330f729Sjoerg     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5949*e038c9c4Sjoerg       break;
59507330f729Sjoerg     SourceManager &SM = getContext().getSourceManager();
59517330f729Sjoerg     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5952*e038c9c4Sjoerg       break;
59537330f729Sjoerg     auto I = DeferredEmptyCoverageMappingDecls.find(D);
59547330f729Sjoerg     if (I == DeferredEmptyCoverageMappingDecls.end())
59557330f729Sjoerg       DeferredEmptyCoverageMappingDecls[D] = true;
59567330f729Sjoerg     break;
59577330f729Sjoerg   }
59587330f729Sjoerg   default:
59597330f729Sjoerg     break;
59607330f729Sjoerg   };
59617330f729Sjoerg }
59627330f729Sjoerg 
ClearUnusedCoverageMapping(const Decl * D)59637330f729Sjoerg void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
59647330f729Sjoerg   // Do we need to generate coverage mapping?
59657330f729Sjoerg   if (!CodeGenOpts.CoverageMapping)
59667330f729Sjoerg     return;
59677330f729Sjoerg   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
59687330f729Sjoerg     if (Fn->isTemplateInstantiation())
59697330f729Sjoerg       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
59707330f729Sjoerg   }
59717330f729Sjoerg   auto I = DeferredEmptyCoverageMappingDecls.find(D);
59727330f729Sjoerg   if (I == DeferredEmptyCoverageMappingDecls.end())
59737330f729Sjoerg     DeferredEmptyCoverageMappingDecls[D] = false;
59747330f729Sjoerg   else
59757330f729Sjoerg     I->second = false;
59767330f729Sjoerg }
59777330f729Sjoerg 
EmitDeferredUnusedCoverageMappings()59787330f729Sjoerg void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
59797330f729Sjoerg   // We call takeVector() here to avoid use-after-free.
59807330f729Sjoerg   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
59817330f729Sjoerg   // we deserialize function bodies to emit coverage info for them, and that
59827330f729Sjoerg   // deserializes more declarations. How should we handle that case?
59837330f729Sjoerg   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
59847330f729Sjoerg     if (!Entry.second)
59857330f729Sjoerg       continue;
59867330f729Sjoerg     const Decl *D = Entry.first;
59877330f729Sjoerg     switch (D->getKind()) {
59887330f729Sjoerg     case Decl::CXXConversion:
59897330f729Sjoerg     case Decl::CXXMethod:
59907330f729Sjoerg     case Decl::Function:
59917330f729Sjoerg     case Decl::ObjCMethod: {
59927330f729Sjoerg       CodeGenPGO PGO(*this);
59937330f729Sjoerg       GlobalDecl GD(cast<FunctionDecl>(D));
59947330f729Sjoerg       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
59957330f729Sjoerg                                   getFunctionLinkage(GD));
59967330f729Sjoerg       break;
59977330f729Sjoerg     }
59987330f729Sjoerg     case Decl::CXXConstructor: {
59997330f729Sjoerg       CodeGenPGO PGO(*this);
60007330f729Sjoerg       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
60017330f729Sjoerg       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
60027330f729Sjoerg                                   getFunctionLinkage(GD));
60037330f729Sjoerg       break;
60047330f729Sjoerg     }
60057330f729Sjoerg     case Decl::CXXDestructor: {
60067330f729Sjoerg       CodeGenPGO PGO(*this);
60077330f729Sjoerg       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
60087330f729Sjoerg       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
60097330f729Sjoerg                                   getFunctionLinkage(GD));
60107330f729Sjoerg       break;
60117330f729Sjoerg     }
60127330f729Sjoerg     default:
60137330f729Sjoerg       break;
60147330f729Sjoerg     };
60157330f729Sjoerg   }
60167330f729Sjoerg }
60177330f729Sjoerg 
EmitMainVoidAlias()6018*e038c9c4Sjoerg void CodeGenModule::EmitMainVoidAlias() {
6019*e038c9c4Sjoerg   // In order to transition away from "__original_main" gracefully, emit an
6020*e038c9c4Sjoerg   // alias for "main" in the no-argument case so that libc can detect when
6021*e038c9c4Sjoerg   // new-style no-argument main is in used.
6022*e038c9c4Sjoerg   if (llvm::Function *F = getModule().getFunction("main")) {
6023*e038c9c4Sjoerg     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6024*e038c9c4Sjoerg         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
6025*e038c9c4Sjoerg       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
6026*e038c9c4Sjoerg   }
6027*e038c9c4Sjoerg }
6028*e038c9c4Sjoerg 
60297330f729Sjoerg /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)60307330f729Sjoerg static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
60317330f729Sjoerg                                           const void *Ptr) {
60327330f729Sjoerg   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
60337330f729Sjoerg   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
60347330f729Sjoerg   return llvm::ConstantInt::get(i64, PtrInt);
60357330f729Sjoerg }
60367330f729Sjoerg 
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)60377330f729Sjoerg static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
60387330f729Sjoerg                                    llvm::NamedMDNode *&GlobalMetadata,
60397330f729Sjoerg                                    GlobalDecl D,
60407330f729Sjoerg                                    llvm::GlobalValue *Addr) {
60417330f729Sjoerg   if (!GlobalMetadata)
60427330f729Sjoerg     GlobalMetadata =
60437330f729Sjoerg       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
60447330f729Sjoerg 
60457330f729Sjoerg   // TODO: should we report variant information for ctors/dtors?
60467330f729Sjoerg   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
60477330f729Sjoerg                            llvm::ConstantAsMetadata::get(GetPointerConstant(
60487330f729Sjoerg                                CGM.getLLVMContext(), D.getDecl()))};
60497330f729Sjoerg   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
60507330f729Sjoerg }
60517330f729Sjoerg 
60527330f729Sjoerg /// For each function which is declared within an extern "C" region and marked
60537330f729Sjoerg /// as 'used', but has internal linkage, create an alias from the unmangled
60547330f729Sjoerg /// name to the mangled name if possible. People expect to be able to refer
60557330f729Sjoerg /// to such functions with an unmangled name from inline assembly within the
60567330f729Sjoerg /// same translation unit.
EmitStaticExternCAliases()60577330f729Sjoerg void CodeGenModule::EmitStaticExternCAliases() {
60587330f729Sjoerg   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
60597330f729Sjoerg     return;
60607330f729Sjoerg   for (auto &I : StaticExternCValues) {
60617330f729Sjoerg     IdentifierInfo *Name = I.first;
60627330f729Sjoerg     llvm::GlobalValue *Val = I.second;
60637330f729Sjoerg     if (Val && !getModule().getNamedValue(Name->getName()))
6064*e038c9c4Sjoerg       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
60657330f729Sjoerg   }
60667330f729Sjoerg }
60677330f729Sjoerg 
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const60687330f729Sjoerg bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
60697330f729Sjoerg                                              GlobalDecl &Result) const {
60707330f729Sjoerg   auto Res = Manglings.find(MangledName);
60717330f729Sjoerg   if (Res == Manglings.end())
60727330f729Sjoerg     return false;
60737330f729Sjoerg   Result = Res->getValue();
60747330f729Sjoerg   return true;
60757330f729Sjoerg }
60767330f729Sjoerg 
60777330f729Sjoerg /// Emits metadata nodes associating all the global values in the
60787330f729Sjoerg /// current module with the Decls they came from.  This is useful for
60797330f729Sjoerg /// projects using IR gen as a subroutine.
60807330f729Sjoerg ///
60817330f729Sjoerg /// Since there's currently no way to associate an MDNode directly
60827330f729Sjoerg /// with an llvm::GlobalValue, we create a global named metadata
60837330f729Sjoerg /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()60847330f729Sjoerg void CodeGenModule::EmitDeclMetadata() {
60857330f729Sjoerg   llvm::NamedMDNode *GlobalMetadata = nullptr;
60867330f729Sjoerg 
60877330f729Sjoerg   for (auto &I : MangledDeclNames) {
60887330f729Sjoerg     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
60897330f729Sjoerg     // Some mangled names don't necessarily have an associated GlobalValue
60907330f729Sjoerg     // in this module, e.g. if we mangled it for DebugInfo.
60917330f729Sjoerg     if (Addr)
60927330f729Sjoerg       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
60937330f729Sjoerg   }
60947330f729Sjoerg }
60957330f729Sjoerg 
60967330f729Sjoerg /// Emits metadata nodes for all the local variables in the current
60977330f729Sjoerg /// function.
EmitDeclMetadata()60987330f729Sjoerg void CodeGenFunction::EmitDeclMetadata() {
60997330f729Sjoerg   if (LocalDeclMap.empty()) return;
61007330f729Sjoerg 
61017330f729Sjoerg   llvm::LLVMContext &Context = getLLVMContext();
61027330f729Sjoerg 
61037330f729Sjoerg   // Find the unique metadata ID for this name.
61047330f729Sjoerg   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
61057330f729Sjoerg 
61067330f729Sjoerg   llvm::NamedMDNode *GlobalMetadata = nullptr;
61077330f729Sjoerg 
61087330f729Sjoerg   for (auto &I : LocalDeclMap) {
61097330f729Sjoerg     const Decl *D = I.first;
61107330f729Sjoerg     llvm::Value *Addr = I.second.getPointer();
61117330f729Sjoerg     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
61127330f729Sjoerg       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
61137330f729Sjoerg       Alloca->setMetadata(
61147330f729Sjoerg           DeclPtrKind, llvm::MDNode::get(
61157330f729Sjoerg                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
61167330f729Sjoerg     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
61177330f729Sjoerg       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
61187330f729Sjoerg       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
61197330f729Sjoerg     }
61207330f729Sjoerg   }
61217330f729Sjoerg }
61227330f729Sjoerg 
EmitVersionIdentMetadata()61237330f729Sjoerg void CodeGenModule::EmitVersionIdentMetadata() {
61247330f729Sjoerg   llvm::NamedMDNode *IdentMetadata =
61257330f729Sjoerg     TheModule.getOrInsertNamedMetadata("llvm.ident");
61267330f729Sjoerg   std::string Version = getClangFullVersion();
61277330f729Sjoerg   llvm::LLVMContext &Ctx = TheModule.getContext();
61287330f729Sjoerg 
61297330f729Sjoerg   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
61307330f729Sjoerg   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
61317330f729Sjoerg }
61327330f729Sjoerg 
EmitCommandLineMetadata()61337330f729Sjoerg void CodeGenModule::EmitCommandLineMetadata() {
61347330f729Sjoerg   llvm::NamedMDNode *CommandLineMetadata =
61357330f729Sjoerg     TheModule.getOrInsertNamedMetadata("llvm.commandline");
61367330f729Sjoerg   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
61377330f729Sjoerg   llvm::LLVMContext &Ctx = TheModule.getContext();
61387330f729Sjoerg 
61397330f729Sjoerg   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
61407330f729Sjoerg   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
61417330f729Sjoerg }
61427330f729Sjoerg 
EmitCoverageFile()61437330f729Sjoerg void CodeGenModule::EmitCoverageFile() {
61447330f729Sjoerg   if (getCodeGenOpts().CoverageDataFile.empty() &&
61457330f729Sjoerg       getCodeGenOpts().CoverageNotesFile.empty())
61467330f729Sjoerg     return;
61477330f729Sjoerg 
61487330f729Sjoerg   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
61497330f729Sjoerg   if (!CUNode)
61507330f729Sjoerg     return;
61517330f729Sjoerg 
61527330f729Sjoerg   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
61537330f729Sjoerg   llvm::LLVMContext &Ctx = TheModule.getContext();
61547330f729Sjoerg   auto *CoverageDataFile =
61557330f729Sjoerg       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
61567330f729Sjoerg   auto *CoverageNotesFile =
61577330f729Sjoerg       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
61587330f729Sjoerg   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
61597330f729Sjoerg     llvm::MDNode *CU = CUNode->getOperand(i);
61607330f729Sjoerg     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
61617330f729Sjoerg     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
61627330f729Sjoerg   }
61637330f729Sjoerg }
61647330f729Sjoerg 
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)61657330f729Sjoerg llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
61667330f729Sjoerg                                                        bool ForEH) {
61677330f729Sjoerg   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
61687330f729Sjoerg   // FIXME: should we even be calling this method if RTTI is disabled
61697330f729Sjoerg   // and it's not for EH?
6170*e038c9c4Sjoerg   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6171*e038c9c4Sjoerg       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6172*e038c9c4Sjoerg        getTriple().isNVPTX()))
61737330f729Sjoerg     return llvm::Constant::getNullValue(Int8PtrTy);
61747330f729Sjoerg 
61757330f729Sjoerg   if (ForEH && Ty->isObjCObjectPointerType() &&
61767330f729Sjoerg       LangOpts.ObjCRuntime.isGNUFamily())
61777330f729Sjoerg     return ObjCRuntime->GetEHType(Ty);
61787330f729Sjoerg 
61797330f729Sjoerg   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
61807330f729Sjoerg }
61817330f729Sjoerg 
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)61827330f729Sjoerg void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
61837330f729Sjoerg   // Do not emit threadprivates in simd-only mode.
61847330f729Sjoerg   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
61857330f729Sjoerg     return;
61867330f729Sjoerg   for (auto RefExpr : D->varlists()) {
61877330f729Sjoerg     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
61887330f729Sjoerg     bool PerformInit =
61897330f729Sjoerg         VD->getAnyInitializer() &&
61907330f729Sjoerg         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
61917330f729Sjoerg                                                         /*ForRef=*/false);
61927330f729Sjoerg 
61937330f729Sjoerg     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
61947330f729Sjoerg     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
61957330f729Sjoerg             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
61967330f729Sjoerg       CXXGlobalInits.push_back(InitFunction);
61977330f729Sjoerg   }
61987330f729Sjoerg }
61997330f729Sjoerg 
62007330f729Sjoerg llvm::Metadata *
CreateMetadataIdentifierImpl(QualType T,MetadataTypeMap & Map,StringRef Suffix)62017330f729Sjoerg CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
62027330f729Sjoerg                                             StringRef Suffix) {
62037330f729Sjoerg   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
62047330f729Sjoerg   if (InternalId)
62057330f729Sjoerg     return InternalId;
62067330f729Sjoerg 
62077330f729Sjoerg   if (isExternallyVisible(T->getLinkage())) {
62087330f729Sjoerg     std::string OutName;
62097330f729Sjoerg     llvm::raw_string_ostream Out(OutName);
62107330f729Sjoerg     getCXXABI().getMangleContext().mangleTypeName(T, Out);
62117330f729Sjoerg     Out << Suffix;
62127330f729Sjoerg 
62137330f729Sjoerg     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
62147330f729Sjoerg   } else {
62157330f729Sjoerg     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
62167330f729Sjoerg                                            llvm::ArrayRef<llvm::Metadata *>());
62177330f729Sjoerg   }
62187330f729Sjoerg 
62197330f729Sjoerg   return InternalId;
62207330f729Sjoerg }
62217330f729Sjoerg 
CreateMetadataIdentifierForType(QualType T)62227330f729Sjoerg llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
62237330f729Sjoerg   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
62247330f729Sjoerg }
62257330f729Sjoerg 
62267330f729Sjoerg llvm::Metadata *
CreateMetadataIdentifierForVirtualMemPtrType(QualType T)62277330f729Sjoerg CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
62287330f729Sjoerg   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
62297330f729Sjoerg }
62307330f729Sjoerg 
62317330f729Sjoerg // Generalize pointer types to a void pointer with the qualifiers of the
62327330f729Sjoerg // originally pointed-to type, e.g. 'const char *' and 'char * const *'
62337330f729Sjoerg // generalize to 'const void *' while 'char *' and 'const char **' generalize to
62347330f729Sjoerg // 'void *'.
GeneralizeType(ASTContext & Ctx,QualType Ty)62357330f729Sjoerg static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
62367330f729Sjoerg   if (!Ty->isPointerType())
62377330f729Sjoerg     return Ty;
62387330f729Sjoerg 
62397330f729Sjoerg   return Ctx.getPointerType(
62407330f729Sjoerg       QualType(Ctx.VoidTy).withCVRQualifiers(
62417330f729Sjoerg           Ty->getPointeeType().getCVRQualifiers()));
62427330f729Sjoerg }
62437330f729Sjoerg 
62447330f729Sjoerg // Apply type generalization to a FunctionType's return and argument types
GeneralizeFunctionType(ASTContext & Ctx,QualType Ty)62457330f729Sjoerg static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
62467330f729Sjoerg   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
62477330f729Sjoerg     SmallVector<QualType, 8> GeneralizedParams;
62487330f729Sjoerg     for (auto &Param : FnType->param_types())
62497330f729Sjoerg       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
62507330f729Sjoerg 
62517330f729Sjoerg     return Ctx.getFunctionType(
62527330f729Sjoerg         GeneralizeType(Ctx, FnType->getReturnType()),
62537330f729Sjoerg         GeneralizedParams, FnType->getExtProtoInfo());
62547330f729Sjoerg   }
62557330f729Sjoerg 
62567330f729Sjoerg   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
62577330f729Sjoerg     return Ctx.getFunctionNoProtoType(
62587330f729Sjoerg         GeneralizeType(Ctx, FnType->getReturnType()));
62597330f729Sjoerg 
62607330f729Sjoerg   llvm_unreachable("Encountered unknown FunctionType");
62617330f729Sjoerg }
62627330f729Sjoerg 
CreateMetadataIdentifierGeneralized(QualType T)62637330f729Sjoerg llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
62647330f729Sjoerg   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
62657330f729Sjoerg                                       GeneralizedMetadataIdMap, ".generalized");
62667330f729Sjoerg }
62677330f729Sjoerg 
62687330f729Sjoerg /// Returns whether this module needs the "all-vtables" type identifier.
NeedAllVtablesTypeId() const62697330f729Sjoerg bool CodeGenModule::NeedAllVtablesTypeId() const {
62707330f729Sjoerg   // Returns true if at least one of vtable-based CFI checkers is enabled and
62717330f729Sjoerg   // is not in the trapping mode.
62727330f729Sjoerg   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
62737330f729Sjoerg            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
62747330f729Sjoerg           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
62757330f729Sjoerg            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
62767330f729Sjoerg           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
62777330f729Sjoerg            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
62787330f729Sjoerg           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
62797330f729Sjoerg            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
62807330f729Sjoerg }
62817330f729Sjoerg 
AddVTableTypeMetadata(llvm::GlobalVariable * VTable,CharUnits Offset,const CXXRecordDecl * RD)62827330f729Sjoerg void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
62837330f729Sjoerg                                           CharUnits Offset,
62847330f729Sjoerg                                           const CXXRecordDecl *RD) {
62857330f729Sjoerg   llvm::Metadata *MD =
62867330f729Sjoerg       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
62877330f729Sjoerg   VTable->addTypeMetadata(Offset.getQuantity(), MD);
62887330f729Sjoerg 
62897330f729Sjoerg   if (CodeGenOpts.SanitizeCfiCrossDso)
62907330f729Sjoerg     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
62917330f729Sjoerg       VTable->addTypeMetadata(Offset.getQuantity(),
62927330f729Sjoerg                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
62937330f729Sjoerg 
62947330f729Sjoerg   if (NeedAllVtablesTypeId()) {
62957330f729Sjoerg     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
62967330f729Sjoerg     VTable->addTypeMetadata(Offset.getQuantity(), MD);
62977330f729Sjoerg   }
62987330f729Sjoerg }
62997330f729Sjoerg 
getSanStats()63007330f729Sjoerg llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
63017330f729Sjoerg   if (!SanStats)
63027330f729Sjoerg     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
63037330f729Sjoerg 
63047330f729Sjoerg   return *SanStats;
63057330f729Sjoerg }
6306*e038c9c4Sjoerg 
63077330f729Sjoerg llvm::Value *
createOpenCLIntToSamplerConversion(const Expr * E,CodeGenFunction & CGF)63087330f729Sjoerg CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
63097330f729Sjoerg                                                   CodeGenFunction &CGF) {
63107330f729Sjoerg   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6311*e038c9c4Sjoerg   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6312*e038c9c4Sjoerg   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6313*e038c9c4Sjoerg   auto *Call = CGF.EmitRuntimeCall(
6314*e038c9c4Sjoerg       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6315*e038c9c4Sjoerg   return Call;
6316*e038c9c4Sjoerg }
6317*e038c9c4Sjoerg 
getNaturalPointeeTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)6318*e038c9c4Sjoerg CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6319*e038c9c4Sjoerg     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6320*e038c9c4Sjoerg   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6321*e038c9c4Sjoerg                                  /* forPointeeType= */ true);
6322*e038c9c4Sjoerg }
6323*e038c9c4Sjoerg 
getNaturalTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,bool forPointeeType)6324*e038c9c4Sjoerg CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6325*e038c9c4Sjoerg                                                  LValueBaseInfo *BaseInfo,
6326*e038c9c4Sjoerg                                                  TBAAAccessInfo *TBAAInfo,
6327*e038c9c4Sjoerg                                                  bool forPointeeType) {
6328*e038c9c4Sjoerg   if (TBAAInfo)
6329*e038c9c4Sjoerg     *TBAAInfo = getTBAAAccessInfo(T);
6330*e038c9c4Sjoerg 
6331*e038c9c4Sjoerg   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6332*e038c9c4Sjoerg   // that doesn't return the information we need to compute BaseInfo.
6333*e038c9c4Sjoerg 
6334*e038c9c4Sjoerg   // Honor alignment typedef attributes even on incomplete types.
6335*e038c9c4Sjoerg   // We also honor them straight for C++ class types, even as pointees;
6336*e038c9c4Sjoerg   // there's an expressivity gap here.
6337*e038c9c4Sjoerg   if (auto TT = T->getAs<TypedefType>()) {
6338*e038c9c4Sjoerg     if (auto Align = TT->getDecl()->getMaxAlignment()) {
6339*e038c9c4Sjoerg       if (BaseInfo)
6340*e038c9c4Sjoerg         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6341*e038c9c4Sjoerg       return getContext().toCharUnitsFromBits(Align);
6342*e038c9c4Sjoerg     }
6343*e038c9c4Sjoerg   }
6344*e038c9c4Sjoerg 
6345*e038c9c4Sjoerg   bool AlignForArray = T->isArrayType();
6346*e038c9c4Sjoerg 
6347*e038c9c4Sjoerg   // Analyze the base element type, so we don't get confused by incomplete
6348*e038c9c4Sjoerg   // array types.
6349*e038c9c4Sjoerg   T = getContext().getBaseElementType(T);
6350*e038c9c4Sjoerg 
6351*e038c9c4Sjoerg   if (T->isIncompleteType()) {
6352*e038c9c4Sjoerg     // We could try to replicate the logic from
6353*e038c9c4Sjoerg     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6354*e038c9c4Sjoerg     // type is incomplete, so it's impossible to test. We could try to reuse
6355*e038c9c4Sjoerg     // getTypeAlignIfKnown, but that doesn't return the information we need
6356*e038c9c4Sjoerg     // to set BaseInfo.  So just ignore the possibility that the alignment is
6357*e038c9c4Sjoerg     // greater than one.
6358*e038c9c4Sjoerg     if (BaseInfo)
6359*e038c9c4Sjoerg       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6360*e038c9c4Sjoerg     return CharUnits::One();
6361*e038c9c4Sjoerg   }
6362*e038c9c4Sjoerg 
6363*e038c9c4Sjoerg   if (BaseInfo)
6364*e038c9c4Sjoerg     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6365*e038c9c4Sjoerg 
6366*e038c9c4Sjoerg   CharUnits Alignment;
6367*e038c9c4Sjoerg   const CXXRecordDecl *RD;
6368*e038c9c4Sjoerg   if (T.getQualifiers().hasUnaligned()) {
6369*e038c9c4Sjoerg     Alignment = CharUnits::One();
6370*e038c9c4Sjoerg   } else if (forPointeeType && !AlignForArray &&
6371*e038c9c4Sjoerg              (RD = T->getAsCXXRecordDecl())) {
6372*e038c9c4Sjoerg     // For C++ class pointees, we don't know whether we're pointing at a
6373*e038c9c4Sjoerg     // base or a complete object, so we generally need to use the
6374*e038c9c4Sjoerg     // non-virtual alignment.
6375*e038c9c4Sjoerg     Alignment = getClassPointerAlignment(RD);
6376*e038c9c4Sjoerg   } else {
6377*e038c9c4Sjoerg     Alignment = getContext().getTypeAlignInChars(T);
6378*e038c9c4Sjoerg   }
6379*e038c9c4Sjoerg 
6380*e038c9c4Sjoerg   // Cap to the global maximum type alignment unless the alignment
6381*e038c9c4Sjoerg   // was somehow explicit on the type.
6382*e038c9c4Sjoerg   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6383*e038c9c4Sjoerg     if (Alignment.getQuantity() > MaxAlign &&
6384*e038c9c4Sjoerg         !getContext().isAlignmentRequired(T))
6385*e038c9c4Sjoerg       Alignment = CharUnits::fromQuantity(MaxAlign);
6386*e038c9c4Sjoerg   }
6387*e038c9c4Sjoerg   return Alignment;
6388*e038c9c4Sjoerg }
6389*e038c9c4Sjoerg 
stopAutoInit()6390*e038c9c4Sjoerg bool CodeGenModule::stopAutoInit() {
6391*e038c9c4Sjoerg   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6392*e038c9c4Sjoerg   if (StopAfter) {
6393*e038c9c4Sjoerg     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6394*e038c9c4Sjoerg     // used
6395*e038c9c4Sjoerg     if (NumAutoVarInit >= StopAfter) {
6396*e038c9c4Sjoerg       return true;
6397*e038c9c4Sjoerg     }
6398*e038c9c4Sjoerg     if (!NumAutoVarInit) {
6399*e038c9c4Sjoerg       unsigned DiagID = getDiags().getCustomDiagID(
6400*e038c9c4Sjoerg           DiagnosticsEngine::Warning,
6401*e038c9c4Sjoerg           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6402*e038c9c4Sjoerg           "number of times ftrivial-auto-var-init=%1 gets applied.");
6403*e038c9c4Sjoerg       getDiags().Report(DiagID)
6404*e038c9c4Sjoerg           << StopAfter
6405*e038c9c4Sjoerg           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6406*e038c9c4Sjoerg                       LangOptions::TrivialAutoVarInitKind::Zero
6407*e038c9c4Sjoerg                   ? "zero"
6408*e038c9c4Sjoerg                   : "pattern");
6409*e038c9c4Sjoerg     }
6410*e038c9c4Sjoerg     ++NumAutoVarInit;
6411*e038c9c4Sjoerg   }
6412*e038c9c4Sjoerg   return false;
6413*e038c9c4Sjoerg }
6414*e038c9c4Sjoerg 
printPostfixForExternalizedStaticVar(llvm::raw_ostream & OS) const6415*e038c9c4Sjoerg void CodeGenModule::printPostfixForExternalizedStaticVar(
6416*e038c9c4Sjoerg     llvm::raw_ostream &OS) const {
6417*e038c9c4Sjoerg   OS << ".static." << getContext().getCUIDHash();
64187330f729Sjoerg }
6419