xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 23408297fbf3089f0388a8873b02fa75ab3f5bb9)
10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenModule.h"
140b57cec5SDimitry Andric #include "CGBlocks.h"
150b57cec5SDimitry Andric #include "CGCUDARuntime.h"
160b57cec5SDimitry Andric #include "CGCXXABI.h"
170b57cec5SDimitry Andric #include "CGCall.h"
180b57cec5SDimitry Andric #include "CGDebugInfo.h"
190b57cec5SDimitry Andric #include "CGObjCRuntime.h"
200b57cec5SDimitry Andric #include "CGOpenCLRuntime.h"
210b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
22e8d8bef9SDimitry Andric #include "CGOpenMPRuntimeAMDGCN.h"
230b57cec5SDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
240b57cec5SDimitry Andric #include "CodeGenFunction.h"
250b57cec5SDimitry Andric #include "CodeGenPGO.h"
260b57cec5SDimitry Andric #include "ConstantEmitter.h"
270b57cec5SDimitry Andric #include "CoverageMappingGen.h"
280b57cec5SDimitry Andric #include "TargetInfo.h"
290b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
300b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
310b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
320b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
330b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
340b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
350b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h"
360b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
370b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
380b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
390b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
400b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
410b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
425ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h"
430b57cec5SDimitry Andric #include "clang/Basic/Module.h"
440b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
450b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
460b57cec5SDimitry Andric #include "clang/Basic/Version.h"
470b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
480b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
490b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
500b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
510b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
52480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
530b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
540b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
550b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
560b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
570b57cec5SDimitry Andric #include "llvm/IR/Module.h"
580b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
590b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
600b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
61480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
620b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
630b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
640b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
650b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric using namespace clang;
680b57cec5SDimitry Andric using namespace CodeGen;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
710b57cec5SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
720b57cec5SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
730b57cec5SDimitry Andric     llvm::cl::init(false));
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
760b57cec5SDimitry Andric 
770b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
780b57cec5SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
79e8d8bef9SDimitry Andric   case TargetCXXABI::AppleARM64:
80480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
810b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
820b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
830b57cec5SDimitry Andric   case TargetCXXABI::iOS:
840b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
850b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
860b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
870b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
885ffd83dbSDimitry Andric   case TargetCXXABI::XL:
890b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
900b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
910b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
920b57cec5SDimitry Andric   }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
950b57cec5SDimitry Andric }
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
980b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
990b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
1000b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
1010b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
1020b57cec5SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
1030b57cec5SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
1040b57cec5SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
1050b57cec5SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
1060b57cec5SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // Initialize the type cache.
1090b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
1100b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
1110b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1120b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
1130b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1140b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1150b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
1165ffd83dbSDimitry Andric   BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
1170b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
1180b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
1190b57cec5SDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
1200b57cec5SDimitry Andric   PointerAlignInBytes =
1210b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1220b57cec5SDimitry Andric   SizeSizeInBytes =
1230b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1240b57cec5SDimitry Andric   IntAlignInBytes =
1250b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
126e8d8bef9SDimitry Andric   CharTy =
127e8d8bef9SDimitry Andric     llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
1280b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1290b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
1300b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
1310b57cec5SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
1320b57cec5SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1330b57cec5SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1340b57cec5SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
1350b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric   if (LangOpts.ObjC)
1400b57cec5SDimitry Andric     createObjCRuntime();
1410b57cec5SDimitry Andric   if (LangOpts.OpenCL)
1420b57cec5SDimitry Andric     createOpenCLRuntime();
1430b57cec5SDimitry Andric   if (LangOpts.OpenMP)
1440b57cec5SDimitry Andric     createOpenMPRuntime();
1450b57cec5SDimitry Andric   if (LangOpts.CUDA)
1460b57cec5SDimitry Andric     createCUDARuntime();
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
1490b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1500b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1510b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
1520b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1550b57cec5SDimitry Andric   // object.
1560b57cec5SDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
1570b57cec5SDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
1580b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
1630b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
1660b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
1670b57cec5SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
1680b57cec5SDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
1690b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1700b57cec5SDimitry Andric                                               "Could not read profile %0: %1");
1710b57cec5SDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1720b57cec5SDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
1730b57cec5SDimitry Andric                                   << EI.message();
1740b57cec5SDimitry Andric       });
1750b57cec5SDimitry Andric     } else
1760b57cec5SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
1770b57cec5SDimitry Andric   }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
1800b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
1810b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
1820b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
1830b57cec5SDimitry Andric }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
1880b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1890b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
1900b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1910b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
1920b57cec5SDimitry Andric   case ObjCRuntime::GCC:
1930b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
1940b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1950b57cec5SDimitry Andric     return;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1980b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
1990b57cec5SDimitry Andric   case ObjCRuntime::iOS:
2000b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
2010b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
2020b57cec5SDimitry Andric     return;
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
2080b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
2120b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
2130b57cec5SDimitry Andric   // If it does not exist use the default implementation.
2140b57cec5SDimitry Andric   switch (getTriple().getArch()) {
2150b57cec5SDimitry Andric   case llvm::Triple::nvptx:
2160b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
2170b57cec5SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
2180b57cec5SDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
2190b57cec5SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
2200b57cec5SDimitry Andric     break;
221e8d8bef9SDimitry Andric   case llvm::Triple::amdgcn:
222e8d8bef9SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
223e8d8bef9SDimitry Andric            "OpenMP AMDGCN is only prepared to deal with device code.");
224e8d8bef9SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this));
225e8d8bef9SDimitry Andric     break;
2260b57cec5SDimitry Andric   default:
2270b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
2280b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
2290b57cec5SDimitry Andric     else
2300b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
2310b57cec5SDimitry Andric     break;
2320b57cec5SDimitry Andric   }
2330b57cec5SDimitry Andric }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
2360b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
2400b57cec5SDimitry Andric   Replacements[Name] = C;
2410b57cec5SDimitry Andric }
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
2440b57cec5SDimitry Andric   for (auto &I : Replacements) {
2450b57cec5SDimitry Andric     StringRef MangledName = I.first();
2460b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
2470b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2480b57cec5SDimitry Andric     if (!Entry)
2490b57cec5SDimitry Andric       continue;
2500b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
2510b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
2520b57cec5SDimitry Andric     if (!NewF) {
2530b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
2540b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
2550b57cec5SDimitry Andric       } else {
2560b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
2570b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2580b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
2590b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
2600b57cec5SDimitry Andric       }
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
2640b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
2650b57cec5SDimitry Andric     if (NewF) {
2660b57cec5SDimitry Andric       NewF->removeFromParent();
2670b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2680b57cec5SDimitry Andric                                                        NewF);
2690b57cec5SDimitry Andric     }
2700b57cec5SDimitry Andric     OldF->eraseFromParent();
2710b57cec5SDimitry Andric   }
2720b57cec5SDimitry Andric }
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2750b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2790b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
2800b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
2810b57cec5SDimitry Andric     llvm::Constant *C = I.second;
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
2840b57cec5SDimitry Andric     GV->eraseFromParent();
2850b57cec5SDimitry Andric   }
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
2890b57cec5SDimitry Andric // linear structure.
2900b57cec5SDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
2910b57cec5SDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
2920b57cec5SDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
2930b57cec5SDimitry Andric   const llvm::Constant *C = &GIS;
2940b57cec5SDimitry Andric   for (;;) {
2950b57cec5SDimitry Andric     C = C->stripPointerCasts();
2960b57cec5SDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
2970b57cec5SDimitry Andric       return GO;
2980b57cec5SDimitry Andric     // stripPointerCasts will not walk over weak aliases.
2990b57cec5SDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
3000b57cec5SDimitry Andric     if (!GIS2)
3010b57cec5SDimitry Andric       return nullptr;
3020b57cec5SDimitry Andric     if (!Visited.insert(GIS2).second)
3030b57cec5SDimitry Andric       return nullptr;
3040b57cec5SDimitry Andric     C = GIS2->getIndirectSymbol();
3050b57cec5SDimitry Andric   }
3060b57cec5SDimitry Andric }
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
3090b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
3100b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
3110b57cec5SDimitry Andric   // and aliases during codegen.
3120b57cec5SDimitry Andric   bool Error = false;
3130b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
3140b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3150b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
3160b57cec5SDimitry Andric     SourceLocation Location;
3170b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
3180b57cec5SDimitry Andric     if (const Attr *A = D->getDefiningAttr())
3190b57cec5SDimitry Andric       Location = A->getLocation();
3200b57cec5SDimitry Andric     else
3210b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
3220b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3230b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3240b57cec5SDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
3250b57cec5SDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
3260b57cec5SDimitry Andric     if (!GV) {
3270b57cec5SDimitry Andric       Error = true;
3280b57cec5SDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
3290b57cec5SDimitry Andric     } else if (GV->isDeclaration()) {
3300b57cec5SDimitry Andric       Error = true;
3310b57cec5SDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
3320b57cec5SDimitry Andric           << IsIFunc << IsIFunc;
3330b57cec5SDimitry Andric     } else if (IsIFunc) {
3340b57cec5SDimitry Andric       // Check resolver function type.
3350b57cec5SDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
3360b57cec5SDimitry Andric           GV->getType()->getPointerElementType());
3370b57cec5SDimitry Andric       assert(FTy);
3380b57cec5SDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
3390b57cec5SDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
3400b57cec5SDimitry Andric     }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
3430b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
3440b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
3450b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
3460b57cec5SDimitry Andric     else
3470b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3500b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
3510b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
3520b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
3530b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
3540b57cec5SDimitry Andric     }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
3570b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
3580b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
3590b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
3600b57cec5SDimitry Andric     // expecting the link to be weak.
3610b57cec5SDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
3620b57cec5SDimitry Andric       if (GA->isInterposable()) {
3630b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
3640b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
3650b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3660b57cec5SDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
3670b57cec5SDimitry Andric         Alias->setIndirectSymbol(Aliasee);
3680b57cec5SDimitry Andric       }
3690b57cec5SDimitry Andric     }
3700b57cec5SDimitry Andric   }
3710b57cec5SDimitry Andric   if (!Error)
3720b57cec5SDimitry Andric     return;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3750b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3760b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
377e8d8bef9SDimitry Andric     auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
3780b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
3790b57cec5SDimitry Andric     Alias->eraseFromParent();
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric void CodeGenModule::clear() {
3840b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
3850b57cec5SDimitry Andric   if (OpenMPRuntime)
3860b57cec5SDimitry Andric     OpenMPRuntime->clear();
3870b57cec5SDimitry Andric }
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
3900b57cec5SDimitry Andric                                        StringRef MainFile) {
3910b57cec5SDimitry Andric   if (!hasDiagnostics())
3920b57cec5SDimitry Andric     return;
3930b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
3940b57cec5SDimitry Andric     if (MainFile.empty())
3950b57cec5SDimitry Andric       MainFile = "<stdin>";
3960b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
3970b57cec5SDimitry Andric   } else {
3980b57cec5SDimitry Andric     if (Mismatched > 0)
3990b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric     if (Missing > 0)
4020b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
4030b57cec5SDimitry Andric   }
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric 
406e8d8bef9SDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
407e8d8bef9SDimitry Andric                                              llvm::Module &M) {
408e8d8bef9SDimitry Andric   if (!LO.VisibilityFromDLLStorageClass)
409e8d8bef9SDimitry Andric     return;
410e8d8bef9SDimitry Andric 
411e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
412e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
413e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
414e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
415e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
416e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
417e8d8bef9SDimitry Andric   llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
418e8d8bef9SDimitry Andric       CodeGenModule::GetLLVMVisibility(
419e8d8bef9SDimitry Andric           LO.getExternDeclNoDLLStorageClassVisibility());
420e8d8bef9SDimitry Andric 
421e8d8bef9SDimitry Andric   for (llvm::GlobalValue &GV : M.global_values()) {
422e8d8bef9SDimitry Andric     if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
423e8d8bef9SDimitry Andric       continue;
424e8d8bef9SDimitry Andric 
425e8d8bef9SDimitry Andric     // Reset DSO locality before setting the visibility. This removes
426e8d8bef9SDimitry Andric     // any effects that visibility options and annotations may have
427e8d8bef9SDimitry Andric     // had on the DSO locality. Setting the visibility will implicitly set
428e8d8bef9SDimitry Andric     // appropriate globals to DSO Local; however, this will be pessimistic
429e8d8bef9SDimitry Andric     // w.r.t. to the normal compiler IRGen.
430e8d8bef9SDimitry Andric     GV.setDSOLocal(false);
431e8d8bef9SDimitry Andric 
432e8d8bef9SDimitry Andric     if (GV.isDeclarationForLinker()) {
433e8d8bef9SDimitry Andric       GV.setVisibility(GV.getDLLStorageClass() ==
434e8d8bef9SDimitry Andric                                llvm::GlobalValue::DLLImportStorageClass
435e8d8bef9SDimitry Andric                            ? ExternDeclDLLImportVisibility
436e8d8bef9SDimitry Andric                            : ExternDeclNoDLLStorageClassVisibility);
437e8d8bef9SDimitry Andric     } else {
438e8d8bef9SDimitry Andric       GV.setVisibility(GV.getDLLStorageClass() ==
439e8d8bef9SDimitry Andric                                llvm::GlobalValue::DLLExportStorageClass
440e8d8bef9SDimitry Andric                            ? DLLExportVisibility
441e8d8bef9SDimitry Andric                            : NoDLLStorageClassVisibility);
442e8d8bef9SDimitry Andric     }
443e8d8bef9SDimitry Andric 
444e8d8bef9SDimitry Andric     GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
445e8d8bef9SDimitry Andric   }
446e8d8bef9SDimitry Andric }
447e8d8bef9SDimitry Andric 
4480b57cec5SDimitry Andric void CodeGenModule::Release() {
4490b57cec5SDimitry Andric   EmitDeferred();
4500b57cec5SDimitry Andric   EmitVTablesOpportunistically();
4510b57cec5SDimitry Andric   applyGlobalValReplacements();
4520b57cec5SDimitry Andric   applyReplacements();
4530b57cec5SDimitry Andric   checkAliases();
4540b57cec5SDimitry Andric   emitMultiVersionFunctions();
4550b57cec5SDimitry Andric   EmitCXXGlobalInitFunc();
4565ffd83dbSDimitry Andric   EmitCXXGlobalCleanUpFunc();
4570b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
4580b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
4590b57cec5SDimitry Andric   if (ObjCRuntime)
4600b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
4610b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
4620b57cec5SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
4630b57cec5SDimitry Andric       CUDARuntime) {
4640b57cec5SDimitry Andric     if (llvm::Function *CudaCtorFunction =
4650b57cec5SDimitry Andric             CUDARuntime->makeModuleCtorFunction())
4660b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
4670b57cec5SDimitry Andric   }
4680b57cec5SDimitry Andric   if (OpenMPRuntime) {
4690b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
4700b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
4710b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
4720b57cec5SDimitry Andric     }
473a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
4740b57cec5SDimitry Andric     OpenMPRuntime->clear();
4750b57cec5SDimitry Andric   }
4760b57cec5SDimitry Andric   if (PGOReader) {
4770b57cec5SDimitry Andric     getModule().setProfileSummary(
4780b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
4790b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
4800b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
4810b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
4840b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4850b57cec5SDimitry Andric   EmitGlobalAnnotations();
4860b57cec5SDimitry Andric   EmitStaticExternCAliases();
4870b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
4880b57cec5SDimitry Andric   if (CoverageMapping)
4890b57cec5SDimitry Andric     CoverageMapping->emit();
4900b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4910b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
4920b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
4955ffd83dbSDimitry Andric   if (Context.getTargetInfo().getTriple().isWasm() &&
4965ffd83dbSDimitry Andric       !Context.getTargetInfo().getTriple().isOSEmscripten()) {
4975ffd83dbSDimitry Andric     EmitMainVoidAlias();
4985ffd83dbSDimitry Andric   }
4990b57cec5SDimitry Andric   emitLLVMUsed();
5000b57cec5SDimitry Andric   if (SanStats)
5010b57cec5SDimitry Andric     SanStats->finish();
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
5040b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
5050b57cec5SDimitry Andric     EmitModuleLinkOptions();
5060b57cec5SDimitry Andric   }
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
5090b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
5100b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
5110b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
5120b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
5130b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
5140b57cec5SDimitry Andric   // libs to the linker.
5150b57cec5SDimitry Andric   //
5160b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
5170b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
5180b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
5190b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
5200b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
5210b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
5220b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
5230b57cec5SDimitry Andric       NMD->addOperand(MD);
5240b57cec5SDimitry Andric   }
5250b57cec5SDimitry Andric 
5260b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
5270b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5280b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
5290b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
532480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
5330b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
5340b57cec5SDimitry Andric   }
5355ffd83dbSDimitry Andric 
5365ffd83dbSDimitry Andric   if (Context.getLangOpts().SemanticInterposition)
5375ffd83dbSDimitry Andric     // Require various optimization to respect semantic interposition.
5385ffd83dbSDimitry Andric     getModule().setSemanticInterposition(1);
5395ffd83dbSDimitry Andric 
5400b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
5410b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
5420b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
5430b57cec5SDimitry Andric   }
5440b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
5450b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
5460b57cec5SDimitry Andric   }
5470b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
548480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
549480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
550480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
551480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
552480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
5530b57cec5SDimitry Andric   }
5540b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
5550b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
5560b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
5570b57cec5SDimitry Andric     // by StrictVTablePointers.
5580b57cec5SDimitry Andric 
5590b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
5620b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
5630b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5640b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
5670b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
5680b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
5690b57cec5SDimitry Andric   }
5705ffd83dbSDimitry Andric   if (getModuleDebugInfo())
5710b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
5720b57cec5SDimitry Andric     // parser will drop debug info with a different version number
5730b57cec5SDimitry Andric     // (and warn about it, too).
5740b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
5750b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
5780b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
5790b57cec5SDimitry Andric   // TargetLibraryInfo.
5800b57cec5SDimitry Andric   uint64_t WCharWidth =
5810b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
5820b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
5850b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
5860b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
5870b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
5880b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
5890b57cec5SDimitry Andric     // The minimum width of an enum in bytes
5900b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
5910b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
59413138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
59513138422SDimitry Andric     StringRef ABIStr = Target.getABI();
59613138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
59713138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
59813138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
59913138422SDimitry Andric   }
60013138422SDimitry Andric 
6010b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
6020b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
6030b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
6040b57cec5SDimitry Andric   }
6050b57cec5SDimitry Andric 
6065ffd83dbSDimitry Andric   if (CodeGenOpts.WholeProgramVTables) {
6075ffd83dbSDimitry Andric     // Indicate whether VFE was enabled for this module, so that the
6085ffd83dbSDimitry Andric     // vcall_visibility metadata added under whole program vtables is handled
6095ffd83dbSDimitry Andric     // appropriately in the optimizer.
6105ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
6115ffd83dbSDimitry Andric                               CodeGenOpts.VirtualFunctionElimination);
6125ffd83dbSDimitry Andric   }
6135ffd83dbSDimitry Andric 
614a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
615a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
616a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
617a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
618a7dea167SDimitry Andric   }
619a7dea167SDimitry Andric 
6200b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
6210b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
6220b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
6230b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
6240b57cec5SDimitry Andric                               1);
6250b57cec5SDimitry Andric   }
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
6280b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
6290b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
6300b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
6310b57cec5SDimitry Andric                               1);
6320b57cec5SDimitry Andric   }
6330b57cec5SDimitry Andric 
634e8d8bef9SDimitry Andric   if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 ||
635e8d8bef9SDimitry Andric       Arch == llvm::Triple::aarch64_be) {
636e8d8bef9SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error,
637e8d8bef9SDimitry Andric                               "branch-target-enforcement",
638e8d8bef9SDimitry Andric                               LangOpts.BranchTargetEnforcement);
639e8d8bef9SDimitry Andric 
640e8d8bef9SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
641e8d8bef9SDimitry Andric                               LangOpts.hasSignReturnAddress());
642e8d8bef9SDimitry Andric 
643e8d8bef9SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
644e8d8bef9SDimitry Andric                               LangOpts.isSignReturnAddressScopeAll());
645e8d8bef9SDimitry Andric 
646e8d8bef9SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error,
647e8d8bef9SDimitry Andric                               "sign-return-address-with-bkey",
648e8d8bef9SDimitry Andric                               !LangOpts.isSignReturnAddressWithAKey());
649e8d8bef9SDimitry Andric   }
650e8d8bef9SDimitry Andric 
651e8d8bef9SDimitry Andric   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
652e8d8bef9SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
653e8d8bef9SDimitry Andric     getModule().addModuleFlag(
654e8d8bef9SDimitry Andric         llvm::Module::Error, "MemProfProfileFilename",
655e8d8bef9SDimitry Andric         llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
656e8d8bef9SDimitry Andric   }
657e8d8bef9SDimitry Andric 
6580b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
6590b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
6600b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
6610b57cec5SDimitry Andric     // property.)
6620b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
6635ffd83dbSDimitry Andric                               CodeGenOpts.FP32DenormalMode.Output !=
6645ffd83dbSDimitry Andric                                   llvm::DenormalMode::IEEE);
6650b57cec5SDimitry Andric   }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
6680b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
6690b57cec5SDimitry Andric     EmitOpenCLMetadata();
6700b57cec5SDimitry Andric     // Emit SPIR version.
6710b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
6720b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
6730b57cec5SDimitry Andric       // opencl.spir.version named metadata.
6740b57cec5SDimitry Andric       // C++ is backwards compatible with OpenCL v2.0.
6750b57cec5SDimitry Andric       auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
6760b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
6770b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6780b57cec5SDimitry Andric               Int32Ty, Version / 100)),
6790b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6800b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
6810b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
6820b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
6830b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
6840b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
6850b57cec5SDimitry Andric     }
6860b57cec5SDimitry Andric   }
6870b57cec5SDimitry Andric 
6880b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
6890b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
6900b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
6910b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
6920b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
6930b57cec5SDimitry Andric   }
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
6960b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
6970b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
6980b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
6990b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
7000b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
7010b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
7020b57cec5SDimitry Andric                   .Default(~0u);
7030b57cec5SDimitry Andric     if (CM != ~0u) {
7040b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
7050b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
7060b57cec5SDimitry Andric     }
7070b57cec5SDimitry Andric   }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
7100b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   SimplifyPersonality();
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
7150b57cec5SDimitry Andric     EmitDeclMetadata();
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
7180b57cec5SDimitry Andric     EmitCoverageFile();
7190b57cec5SDimitry Andric 
7205ffd83dbSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
7215ffd83dbSDimitry Andric     DI->finalize();
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
7240b57cec5SDimitry Andric     EmitVersionIdentMetadata();
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
7270b57cec5SDimitry Andric     EmitCommandLineMetadata();
7280b57cec5SDimitry Andric 
7295ffd83dbSDimitry Andric   getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
7305ffd83dbSDimitry Andric 
7315ffd83dbSDimitry Andric   EmitBackendOptionsMetadata(getCodeGenOpts());
732e8d8bef9SDimitry Andric 
733e8d8bef9SDimitry Andric   // Set visibility from DLL storage class
734e8d8bef9SDimitry Andric   // We do this at the end of LLVM IR generation; after any operation
735e8d8bef9SDimitry Andric   // that might affect the DLL storage class or the visibility, and
736e8d8bef9SDimitry Andric   // before anything that might act on these.
737e8d8bef9SDimitry Andric   setVisibilityFromDLLStorageClass(LangOpts, getModule());
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric 
7400b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
7410b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7420b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
7430b57cec5SDimitry Andric   // C++ is backwards compatible with OpenCL v2.0.
7440b57cec5SDimitry Andric   // FIXME: We might need to add CXX version at some point too?
7450b57cec5SDimitry Andric   auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
7460b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
7470b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7480b57cec5SDimitry Andric           Int32Ty, Version / 100)),
7490b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7500b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
7510b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
7520b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
7530b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
7540b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
7575ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata(
7585ffd83dbSDimitry Andric     const CodeGenOptions CodeGenOpts) {
7595ffd83dbSDimitry Andric   switch (getTriple().getArch()) {
7605ffd83dbSDimitry Andric   default:
7615ffd83dbSDimitry Andric     break;
7625ffd83dbSDimitry Andric   case llvm::Triple::riscv32:
7635ffd83dbSDimitry Andric   case llvm::Triple::riscv64:
7645ffd83dbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
7655ffd83dbSDimitry Andric                               CodeGenOpts.SmallDataLimit);
7665ffd83dbSDimitry Andric     break;
7675ffd83dbSDimitry Andric   }
7685ffd83dbSDimitry Andric }
7695ffd83dbSDimitry Andric 
7700b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
7710b57cec5SDimitry Andric   // Make sure that this type is translated.
7720b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
7760b57cec5SDimitry Andric   // Make sure that this type is translated.
7770b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
7810b57cec5SDimitry Andric   if (!TBAA)
7820b57cec5SDimitry Andric     return nullptr;
7830b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
7840b57cec5SDimitry Andric }
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
7870b57cec5SDimitry Andric   if (!TBAA)
7880b57cec5SDimitry Andric     return TBAAAccessInfo();
7895ffd83dbSDimitry Andric   if (getLangOpts().CUDAIsDevice) {
7905ffd83dbSDimitry Andric     // As CUDA builtin surface/texture types are replaced, skip generating TBAA
7915ffd83dbSDimitry Andric     // access info.
7925ffd83dbSDimitry Andric     if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
7935ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
7945ffd83dbSDimitry Andric           nullptr)
7955ffd83dbSDimitry Andric         return TBAAAccessInfo();
7965ffd83dbSDimitry Andric     } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
7975ffd83dbSDimitry Andric       if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
7985ffd83dbSDimitry Andric           nullptr)
7995ffd83dbSDimitry Andric         return TBAAAccessInfo();
8005ffd83dbSDimitry Andric     }
8015ffd83dbSDimitry Andric   }
8020b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
8030b57cec5SDimitry Andric }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric TBAAAccessInfo
8060b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
8070b57cec5SDimitry Andric   if (!TBAA)
8080b57cec5SDimitry Andric     return TBAAAccessInfo();
8090b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
8130b57cec5SDimitry Andric   if (!TBAA)
8140b57cec5SDimitry Andric     return nullptr;
8150b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
8190b57cec5SDimitry Andric   if (!TBAA)
8200b57cec5SDimitry Andric     return nullptr;
8210b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
8220b57cec5SDimitry Andric }
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
8250b57cec5SDimitry Andric   if (!TBAA)
8260b57cec5SDimitry Andric     return nullptr;
8270b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
8310b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
8320b57cec5SDimitry Andric   if (!TBAA)
8330b57cec5SDimitry Andric     return TBAAAccessInfo();
8340b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
8350b57cec5SDimitry Andric }
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric TBAAAccessInfo
8380b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
8390b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
8400b57cec5SDimitry Andric   if (!TBAA)
8410b57cec5SDimitry Andric     return TBAAAccessInfo();
8420b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
8430b57cec5SDimitry Andric }
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric TBAAAccessInfo
8460b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
8470b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
8480b57cec5SDimitry Andric   if (!TBAA)
8490b57cec5SDimitry Andric     return TBAAAccessInfo();
8500b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
8510b57cec5SDimitry Andric }
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
8540b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
8550b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
8560b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
8570b57cec5SDimitry Andric }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
8600b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
8610b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
8620b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
8660b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
8670b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
8710b57cec5SDimitry Andric /// specified stmt yet.
8720b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
8730b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
8740b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
8750b57cec5SDimitry Andric   std::string Msg = Type;
8760b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
8770b57cec5SDimitry Andric       << Msg << S->getSourceRange();
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
8810b57cec5SDimitry Andric /// specified decl yet.
8820b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
8830b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
8840b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
8850b57cec5SDimitry Andric   std::string Msg = Type;
8860b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
8870b57cec5SDimitry Andric }
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
8900b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
8940b57cec5SDimitry Andric                                         const NamedDecl *D) const {
8950b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
8960b57cec5SDimitry Andric     return;
8970b57cec5SDimitry Andric   // Internal definitions always have default visibility.
8980b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
8990b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
9000b57cec5SDimitry Andric     return;
9010b57cec5SDimitry Andric   }
9020b57cec5SDimitry Andric   if (!D)
9030b57cec5SDimitry Andric     return;
9040b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
9050b57cec5SDimitry Andric   // or set explicitly.
9060b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
9070b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
9080b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
9090b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
9100b57cec5SDimitry Andric }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
9130b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
9140b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
9150b57cec5SDimitry Andric     return true;
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
9180b57cec5SDimitry Andric     return true;
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
9210b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
9220b57cec5SDimitry Andric     return false;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
9250b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
9260b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
9270b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
9280b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
9290b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
9300b57cec5SDimitry Andric         !GV->isThreadLocal())
9310b57cec5SDimitry Andric       return false;
9320b57cec5SDimitry Andric   }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
9350b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
9360b57cec5SDimitry Andric   // outside the current DSO.
9370b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
9380b57cec5SDimitry Andric     return false;
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   // Every other GV is local on COFF.
9410b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
9420b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
9430b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
9440b57cec5SDimitry Andric   // FIXME: even thread local variables?
9450b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
9460b57cec5SDimitry Andric     return true;
9470b57cec5SDimitry Andric 
948e8d8bef9SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
949e8d8bef9SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
950e8d8bef9SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
951e8d8bef9SDimitry Andric 
952e8d8bef9SDimitry Andric   if (TT.isOSBinFormatMachO()) {
953e8d8bef9SDimitry Andric     if (RM == llvm::Reloc::Static)
954e8d8bef9SDimitry Andric       return true;
955e8d8bef9SDimitry Andric     return GV->isStrongDefinitionForLinker();
956e8d8bef9SDimitry Andric   }
957e8d8bef9SDimitry Andric 
9580b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
9590b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
9600b57cec5SDimitry Andric     return false;
9610b57cec5SDimitry Andric 
962e8d8bef9SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE) {
963e8d8bef9SDimitry Andric     // On ELF, if -fno-semantic-interposition is specified and the target
964e8d8bef9SDimitry Andric     // supports local aliases, there will be neither CC1
965e8d8bef9SDimitry Andric     // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
966e8d8bef9SDimitry Andric     // dso_local if using a local alias is preferable (can avoid GOT
967e8d8bef9SDimitry Andric     // indirection).
968e8d8bef9SDimitry Andric     if (!GV->canBenefitFromLocalAlias())
9690b57cec5SDimitry Andric       return false;
970e8d8bef9SDimitry Andric     return !(CGM.getLangOpts().SemanticInterposition ||
971e8d8bef9SDimitry Andric              CGM.getLangOpts().HalfNoSemanticInterposition);
972e8d8bef9SDimitry Andric   }
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
9750b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
9760b57cec5SDimitry Andric     return true;
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
9790b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
9800b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
9810b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
9820b57cec5SDimitry Andric     return false;
9830b57cec5SDimitry Andric 
984e8d8bef9SDimitry Andric   // PowerPC64 prefers TOC indirection to avoid copy relocations.
985e8d8bef9SDimitry Andric   if (TT.isPPC64())
9860b57cec5SDimitry Andric     return false;
9870b57cec5SDimitry Andric 
988e8d8bef9SDimitry Andric   if (CGOpts.DirectAccessExternalData) {
989e8d8bef9SDimitry Andric     // If -fdirect-access-external-data (default for -fno-pic), set dso_local
990e8d8bef9SDimitry Andric     // for non-thread-local variables. If the symbol is not defined in the
991e8d8bef9SDimitry Andric     // executable, a copy relocation will be needed at link time. dso_local is
992e8d8bef9SDimitry Andric     // excluded for thread-local variables because they generally don't support
993e8d8bef9SDimitry Andric     // copy relocations.
9940b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
995e8d8bef9SDimitry Andric       if (!Var->isThreadLocal())
9960b57cec5SDimitry Andric         return true;
9970b57cec5SDimitry Andric 
998e8d8bef9SDimitry Andric     // -fno-pic sets dso_local on a function declaration to allow direct
999e8d8bef9SDimitry Andric     // accesses when taking its address (similar to a data symbol). If the
1000e8d8bef9SDimitry Andric     // function is not defined in the executable, a canonical PLT entry will be
1001e8d8bef9SDimitry Andric     // needed at link time. -fno-direct-access-external-data can avoid the
1002e8d8bef9SDimitry Andric     // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1003e8d8bef9SDimitry Andric     // it could just cause trouble without providing perceptible benefits.
10040b57cec5SDimitry Andric     if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
10050b57cec5SDimitry Andric       return true;
1006e8d8bef9SDimitry Andric   }
1007e8d8bef9SDimitry Andric 
1008e8d8bef9SDimitry Andric   // If we can use copy relocations we can assume it is local.
10090b57cec5SDimitry Andric 
10105ffd83dbSDimitry Andric   // Otherwise don't assume it is local.
10110b57cec5SDimitry Andric   return false;
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
10150b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
10190b57cec5SDimitry Andric                                           GlobalDecl GD) const {
10200b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
10210b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
10220b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
10230b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
10240b57cec5SDimitry Andric     return;
10250b57cec5SDimitry Andric   }
10260b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
10300b57cec5SDimitry Andric                                           const NamedDecl *D) const {
10310b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
10320b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
10330b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
10340b57cec5SDimitry Andric     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
10350b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
10360b57cec5SDimitry Andric   }
10370b57cec5SDimitry Andric }
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
10400b57cec5SDimitry Andric                                     GlobalDecl GD) const {
10410b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
10420b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric 
10450b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
10460b57cec5SDimitry Andric                                     const NamedDecl *D) const {
10470b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
10480b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
10490b57cec5SDimitry Andric }
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
10520b57cec5SDimitry Andric                                        const NamedDecl *D) const {
10530b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
10540b57cec5SDimitry Andric   setDSOLocal(GV);
10550b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
10560b57cec5SDimitry Andric }
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
10590b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
10600b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
10610b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
10620b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
10630b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
10640b57cec5SDimitry Andric }
10650b57cec5SDimitry Andric 
10665ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode
10675ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const {
10685ffd83dbSDimitry Andric   switch (CodeGenOpts.getDefaultTLSModel()) {
10690b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
10700b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
10710b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
10720b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
10730b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
10740b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
10750b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
10760b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
10770b57cec5SDimitry Andric   }
10780b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
10790b57cec5SDimitry Andric }
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
10820b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
10855ffd83dbSDimitry Andric   TLM = GetDefaultLLVMTLSModel();
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
10880b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
10890b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
10900b57cec5SDimitry Andric   }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
10930b57cec5SDimitry Andric }
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
10960b57cec5SDimitry Andric                                           StringRef Name) {
10970b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
10980b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
10990b57cec5SDimitry Andric }
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
11020b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
11030b57cec5SDimitry Andric                                                  unsigned CPUIndex,
11040b57cec5SDimitry Andric                                                  raw_ostream &Out) {
11050b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
11060b57cec5SDimitry Andric   // supported.
11070b57cec5SDimitry Andric   if (Attr)
11080b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
11090b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
11100b57cec5SDimitry Andric     Out << ".resolver";
11110b57cec5SDimitry Andric }
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
11140b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
11150b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
11160b57cec5SDimitry Andric     return;
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   Out << '.';
11190b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
1120480093f4SDimitry Andric   ParsedTargetAttr Info =
11210b57cec5SDimitry Andric       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
11220b57cec5SDimitry Andric         // Multiversioning doesn't allow "no-${feature}", so we can
11230b57cec5SDimitry Andric         // only have "+" prefixes here.
11240b57cec5SDimitry Andric         assert(LHS.startswith("+") && RHS.startswith("+") &&
11250b57cec5SDimitry Andric                "Features should always have a prefix.");
11260b57cec5SDimitry Andric         return Target.multiVersionSortPriority(LHS.substr(1)) >
11270b57cec5SDimitry Andric                Target.multiVersionSortPriority(RHS.substr(1));
11280b57cec5SDimitry Andric       });
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   bool IsFirst = true;
11310b57cec5SDimitry Andric 
11320b57cec5SDimitry Andric   if (!Info.Architecture.empty()) {
11330b57cec5SDimitry Andric     IsFirst = false;
11340b57cec5SDimitry Andric     Out << "arch_" << Info.Architecture;
11350b57cec5SDimitry Andric   }
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
11380b57cec5SDimitry Andric     if (!IsFirst)
11390b57cec5SDimitry Andric       Out << '_';
11400b57cec5SDimitry Andric     IsFirst = false;
11410b57cec5SDimitry Andric     Out << Feat.substr(1);
11420b57cec5SDimitry Andric   }
11430b57cec5SDimitry Andric }
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
11460b57cec5SDimitry Andric                                       const NamedDecl *ND,
11470b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
11480b57cec5SDimitry Andric   SmallString<256> Buffer;
11490b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
11500b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
11515ffd83dbSDimitry Andric   if (MC.shouldMangleDeclName(ND))
11525ffd83dbSDimitry Andric     MC.mangleName(GD.getWithDecl(ND), Out);
11535ffd83dbSDimitry Andric   else {
11540b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
11550b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
11560b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric     if (FD &&
11590b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
11600b57cec5SDimitry Andric       Out << "__regcall3__" << II->getName();
11615ffd83dbSDimitry Andric     } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
11625ffd83dbSDimitry Andric                GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
11635ffd83dbSDimitry Andric       Out << "__device_stub__" << II->getName();
11640b57cec5SDimitry Andric     } else {
11650b57cec5SDimitry Andric       Out << II->getName();
11660b57cec5SDimitry Andric     }
11670b57cec5SDimitry Andric   }
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
11700b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
11710b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
11720b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
11730b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
11740b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
11750b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
11760b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
11770b57cec5SDimitry Andric         break;
11780b57cec5SDimitry Andric       case MultiVersionKind::Target:
11790b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
11800b57cec5SDimitry Andric         break;
11810b57cec5SDimitry Andric       case MultiVersionKind::None:
11820b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
11830b57cec5SDimitry Andric       }
11840b57cec5SDimitry Andric     }
11850b57cec5SDimitry Andric 
11865ffd83dbSDimitry Andric   return std::string(Out.str());
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
11900b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
11910b57cec5SDimitry Andric   if (!FD->isMultiVersion())
11920b57cec5SDimitry Andric     return;
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
11950b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
11960b57cec5SDimitry Andric   // multiversion function.
11970b57cec5SDimitry Andric   std::string NonTargetName =
11980b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
11990b57cec5SDimitry Andric   GlobalDecl OtherGD;
12000b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
12010b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
12020b57cec5SDimitry Andric                .getDecl()
12030b57cec5SDimitry Andric                ->getAsFunction()
12040b57cec5SDimitry Andric                ->isMultiVersion() &&
12050b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
12060b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
12070b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
12080b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
12090b57cec5SDimitry Andric                                       .getDecl()
12100b57cec5SDimitry Andric                                       ->getAsFunction()
12110b57cec5SDimitry Andric                                       ->getMostRecentDecl();
12120b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
12130b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
12140b57cec5SDimitry Andric     // version, we don't try to update it.
12150b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
12160b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
12170b57cec5SDimitry Andric       // to this.
12180b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
12190b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
12200b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
12210b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
12220b57cec5SDimitry Andric       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
12230b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
12240b57cec5SDimitry Andric         Entry->setName(OtherName);
12250b57cec5SDimitry Andric     }
12260b57cec5SDimitry Andric   }
12270b57cec5SDimitry Andric }
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
12300b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
12330b57cec5SDimitry Andric   // complete constructors get mangled the same.
12340b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
12350b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
12360b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
12370b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
12380b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
12390b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
12400b57cec5SDimitry Andric     }
12410b57cec5SDimitry Andric   }
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
12440b57cec5SDimitry Andric   if (FoundName != MangledDeclNames.end())
12450b57cec5SDimitry Andric     return FoundName->second;
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
12480b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
12490b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
12500b57cec5SDimitry Andric 
12515ffd83dbSDimitry Andric   // Ensure either we have different ABIs between host and device compilations,
12525ffd83dbSDimitry Andric   // says host compilation following MSVC ABI but device compilation follows
12535ffd83dbSDimitry Andric   // Itanium C++ ABI or, if they follow the same ABI, kernel names after
12545ffd83dbSDimitry Andric   // mangling should be the same after name stubbing. The later checking is
12555ffd83dbSDimitry Andric   // very important as the device kernel name being mangled in host-compilation
12565ffd83dbSDimitry Andric   // is used to resolve the device binaries to be executed. Inconsistent naming
12575ffd83dbSDimitry Andric   // result in undefined behavior. Even though we cannot check that naming
12585ffd83dbSDimitry Andric   // directly between host- and device-compilations, the host- and
12595ffd83dbSDimitry Andric   // device-mangling in host compilation could help catching certain ones.
12605ffd83dbSDimitry Andric   assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
12615ffd83dbSDimitry Andric          getLangOpts().CUDAIsDevice ||
12625ffd83dbSDimitry Andric          (getContext().getAuxTargetInfo() &&
12635ffd83dbSDimitry Andric           (getContext().getAuxTargetInfo()->getCXXABI() !=
12645ffd83dbSDimitry Andric            getContext().getTargetInfo().getCXXABI())) ||
12655ffd83dbSDimitry Andric          getCUDARuntime().getDeviceSideName(ND) ==
12665ffd83dbSDimitry Andric              getMangledNameImpl(
12675ffd83dbSDimitry Andric                  *this,
12685ffd83dbSDimitry Andric                  GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
12695ffd83dbSDimitry Andric                  ND));
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
12720b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
12730b57cec5SDimitry Andric }
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
12760b57cec5SDimitry Andric                                              const BlockDecl *BD) {
12770b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
12780b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   SmallString<256> Buffer;
12810b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
12820b57cec5SDimitry Andric   if (!D)
12830b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
12840b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
12850b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
12860b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
12870b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
12880b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
12890b57cec5SDimitry Andric   else
12900b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
12930b57cec5SDimitry Andric   return Result.first->first();
12940b57cec5SDimitry Andric }
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
12970b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
12980b57cec5SDimitry Andric }
12990b57cec5SDimitry Andric 
13000b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
13010b57cec5SDimitry Andric /// main() runs.
13020b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
13030b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
13040b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
13050b57cec5SDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
13090b57cec5SDimitry Andric /// when the module is unloaded.
1310e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1311e8d8bef9SDimitry Andric                                   bool IsDtorAttrFunc) {
1312e8d8bef9SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1313e8d8bef9SDimitry Andric       (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) {
13140b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
13150b57cec5SDimitry Andric     return;
13160b57cec5SDimitry Andric   }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
13190b57cec5SDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
13200b57cec5SDimitry Andric }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
13230b57cec5SDimitry Andric   if (Fns.empty()) return;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   // Ctor function type is void()*.
13260b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
13270b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
13280b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
13310b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
13320b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
13350b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
13360b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
13370b57cec5SDimitry Andric   for (const auto &I : Fns) {
13380b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
13390b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
13400b57cec5SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
13410b57cec5SDimitry Andric     if (I.AssociatedData)
13420b57cec5SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
13430b57cec5SDimitry Andric     else
13440b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
13450b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
13460b57cec5SDimitry Andric   }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric   auto list =
13490b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
13500b57cec5SDimitry Andric                                 /*constant*/ false,
13510b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
13540b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
1355a7dea167SDimitry Andric   list->setAlignment(llvm::None);
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric   Fns.clear();
13580b57cec5SDimitry Andric }
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
13610b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
13620b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
13670b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
13680b57cec5SDimitry Andric 
13690b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
13700b57cec5SDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
13710b57cec5SDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13720b57cec5SDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
13730b57cec5SDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
13740b57cec5SDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
13750b57cec5SDimitry Andric     return llvm::GlobalValue::InternalLinkage;
13760b57cec5SDimitry Andric   }
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
13790b57cec5SDimitry Andric }
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
13820b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
13830b57cec5SDimitry Andric   if (!MDS) return nullptr;
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
13860b57cec5SDimitry Andric }
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
13890b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
13900b57cec5SDimitry Andric                                               llvm::Function *F) {
13910b57cec5SDimitry Andric   unsigned CallingConv;
13920b57cec5SDimitry Andric   llvm::AttributeList PAL;
13930b57cec5SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
13940b57cec5SDimitry Andric   F->setAttributes(PAL);
13950b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
13960b57cec5SDimitry Andric }
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
13990b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
14000b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
14010b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
14020b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
14030b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
14040b57cec5SDimitry Andric   else {
14050b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
14060b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
14070b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
14080b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
14090b57cec5SDimitry Andric     else {
14100b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
14110b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
14120b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
14130b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
14140b57cec5SDimitry Andric     }
14150b57cec5SDimitry Andric   }
14160b57cec5SDimitry Andric }
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric // Returns the address space id that should be produced to the
14190b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
14200b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
14210b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
14220b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
14230b57cec5SDimitry Andric // (basically all single AS CPUs).
14240b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
14250b57cec5SDimitry Andric   switch (AS) {
1426e8d8bef9SDimitry Andric   case LangAS::opencl_global:
1427e8d8bef9SDimitry Andric     return 1;
1428e8d8bef9SDimitry Andric   case LangAS::opencl_constant:
1429e8d8bef9SDimitry Andric     return 2;
1430e8d8bef9SDimitry Andric   case LangAS::opencl_local:
1431e8d8bef9SDimitry Andric     return 3;
1432e8d8bef9SDimitry Andric   case LangAS::opencl_generic:
1433e8d8bef9SDimitry Andric     return 4; // Not in SPIR 2.0 specs.
1434e8d8bef9SDimitry Andric   case LangAS::opencl_global_device:
1435e8d8bef9SDimitry Andric     return 5;
1436e8d8bef9SDimitry Andric   case LangAS::opencl_global_host:
1437e8d8bef9SDimitry Andric     return 6;
14380b57cec5SDimitry Andric   default:
14390b57cec5SDimitry Andric     return 0; // Assume private.
14400b57cec5SDimitry Andric   }
14410b57cec5SDimitry Andric }
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
14440b57cec5SDimitry Andric                                          const FunctionDecl *FD,
14450b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
14460b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
14470b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
14480b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
14490b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
14500b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
14530b57cec5SDimitry Andric 
14540b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
14550b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
14580b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
14610b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
14640b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
14670b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   // MDNode for the kernel argument names.
14700b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric   if (FD && CGF)
14730b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
14740b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
14750b57cec5SDimitry Andric       QualType ty = parm->getType();
14760b57cec5SDimitry Andric       std::string typeQuals;
14770b57cec5SDimitry Andric 
14780b57cec5SDimitry Andric       if (ty->isPointerType()) {
14790b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric         // Get address qualifier.
14820b57cec5SDimitry Andric         addressQuals.push_back(
14830b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
14840b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric         // Get argument type name.
14870b57cec5SDimitry Andric         std::string typeName =
14880b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
14910b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
14920b57cec5SDimitry Andric         if (pointeeTy.isCanonical() && pos != std::string::npos)
14930b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric         std::string baseTypeName =
14980b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
14990b57cec5SDimitry Andric                 Policy) +
15000b57cec5SDimitry Andric             "*";
15010b57cec5SDimitry Andric 
15020b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
15030b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
15040b57cec5SDimitry Andric         if (pos != std::string::npos)
15050b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric         argBaseTypeNames.push_back(
15080b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric         // Get argument type qualifiers:
15110b57cec5SDimitry Andric         if (ty.isRestrictQualified())
15120b57cec5SDimitry Andric           typeQuals = "restrict";
15130b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
15140b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
15150b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
15160b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
15170b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
15180b57cec5SDimitry Andric       } else {
15190b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
15200b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
15210b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
15220b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric         addressQuals.push_back(
15250b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric         // Get argument type name.
15280b57cec5SDimitry Andric         std::string typeName;
15290b57cec5SDimitry Andric         if (isPipe)
15300b57cec5SDimitry Andric           typeName = ty.getCanonicalType()
15315ffd83dbSDimitry Andric                          ->castAs<PipeType>()
15320b57cec5SDimitry Andric                          ->getElementType()
15330b57cec5SDimitry Andric                          .getAsString(Policy);
15340b57cec5SDimitry Andric         else
15350b57cec5SDimitry Andric           typeName = ty.getUnqualifiedType().getAsString(Policy);
15360b57cec5SDimitry Andric 
15370b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
15380b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
15390b57cec5SDimitry Andric         if (ty.isCanonical() && pos != std::string::npos)
15400b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
15410b57cec5SDimitry Andric 
15420b57cec5SDimitry Andric         std::string baseTypeName;
15430b57cec5SDimitry Andric         if (isPipe)
15440b57cec5SDimitry Andric           baseTypeName = ty.getCanonicalType()
15455ffd83dbSDimitry Andric                              ->castAs<PipeType>()
15460b57cec5SDimitry Andric                              ->getElementType()
15470b57cec5SDimitry Andric                              .getCanonicalType()
15480b57cec5SDimitry Andric                              .getAsString(Policy);
15490b57cec5SDimitry Andric         else
15500b57cec5SDimitry Andric           baseTypeName =
15510b57cec5SDimitry Andric               ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric         // Remove access qualifiers on images
15540b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
15550b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
15560b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
15570b57cec5SDimitry Andric         if (ty->isImageType()) {
15580b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
15590b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
15600b57cec5SDimitry Andric         }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
15630b57cec5SDimitry Andric 
15640b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
15650b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
15660b57cec5SDimitry Andric         if (pos != std::string::npos)
15670b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric         argBaseTypeNames.push_back(
15700b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric         if (isPipe)
15730b57cec5SDimitry Andric           typeQuals = "pipe";
15740b57cec5SDimitry Andric       }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric       // Get image and pipe access qualifier:
15790b57cec5SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
15800b57cec5SDimitry Andric         const Decl *PDecl = parm;
15810b57cec5SDimitry Andric         if (auto *TD = dyn_cast<TypedefType>(ty))
15820b57cec5SDimitry Andric           PDecl = TD->getDecl();
15830b57cec5SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
15840b57cec5SDimitry Andric         if (A && A->isWriteOnly())
15850b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
15860b57cec5SDimitry Andric         else if (A && A->isReadWrite())
15870b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
15880b57cec5SDimitry Andric         else
15890b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
15900b57cec5SDimitry Andric       } else
15910b57cec5SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
15920b57cec5SDimitry Andric 
15930b57cec5SDimitry Andric       // Get argument name.
15940b57cec5SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
15950b57cec5SDimitry Andric     }
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
15980b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, addressQuals));
15990b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
16000b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, accessQuals));
16010b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type",
16020b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeNames));
16030b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
16040b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argBaseTypeNames));
16050b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
16060b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeQuals));
16070b57cec5SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata)
16080b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
16090b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
16100b57cec5SDimitry Andric }
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric /// Determines whether the language options require us to model
16130b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
16140b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
16150b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
16160b57cec5SDimitry Andric /// enables this.
16170b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
16180b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
16190b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
16220b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
16250b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
16260b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
16270b57cec5SDimitry Andric   }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric   return true;
16300b57cec5SDimitry Andric }
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
16330b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
16340b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
16350b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
16360b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
16370b57cec5SDimitry Andric     return false;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
16400b57cec5SDimitry Andric   // need this sort of type metadata.
16410b57cec5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
16420b57cec5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
16430b57cec5SDimitry Andric }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric std::vector<const CXXRecordDecl *>
16460b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
16470b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
16500b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
16510b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
16520b57cec5SDimitry Andric       MostBases.insert(RD);
16530b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
16540b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
16550b57cec5SDimitry Andric   };
16560b57cec5SDimitry Andric   CollectMostBases(RD);
16570b57cec5SDimitry Andric   return MostBases.takeVector();
16580b57cec5SDimitry Andric }
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
16610b57cec5SDimitry Andric                                                            llvm::Function *F) {
16620b57cec5SDimitry Andric   llvm::AttrBuilder B;
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric   if (CodeGenOpts.UnwindTables)
16650b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
16660b57cec5SDimitry Andric 
16675ffd83dbSDimitry Andric   if (CodeGenOpts.StackClashProtector)
16685ffd83dbSDimitry Andric     B.addAttribute("probe-stack", "inline-asm");
16695ffd83dbSDimitry Andric 
16700b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
16710b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
16740b57cec5SDimitry Andric     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
16750b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtect);
16760b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
16770b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectStrong);
16780b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
16790b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectReq);
16800b57cec5SDimitry Andric   }
16810b57cec5SDimitry Andric 
16820b57cec5SDimitry Andric   if (!D) {
16830b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
16840b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
16850b57cec5SDimitry Andric     // disabled, mark the function as noinline.
16860b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
16870b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
16880b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
16890b57cec5SDimitry Andric 
16900b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
16910b57cec5SDimitry Andric     return;
16920b57cec5SDimitry Andric   }
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
16950b57cec5SDimitry Andric   // starting with the default for this optimization level.
16960b57cec5SDimitry Andric   bool ShouldAddOptNone =
16970b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
16980b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
16990b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
17000b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
17010b57cec5SDimitry Andric 
1702480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
1703480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1704480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
17050b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
17080b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
17110b57cec5SDimitry Andric     // much of their semantics.
17120b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
17130b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
17160b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
17170b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
17180b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
17190b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
17200b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
17210b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
17220b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
17230b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1724480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1725480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
17260b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
17270b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
17280b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
17290b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
17300b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
17310b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
17320b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
17330b57cec5SDimitry Andric     // carry an explicit noinline attribute.
17340b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
17350b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
17360b57cec5SDimitry Andric   } else {
17370b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
17380b57cec5SDimitry Andric     // absence to mark things as noinline.
17390b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17400b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
17410b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
17420b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
17430b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
17440b57cec5SDimitry Andric         };
17450b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
17460b57cec5SDimitry Andric           return true;
17470b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
17480b57cec5SDimitry Andric         if (!Pattern)
17490b57cec5SDimitry Andric           return false;
17500b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
17510b57cec5SDimitry Andric       };
17520b57cec5SDimitry Andric       if (CheckForInline(FD)) {
17530b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
17540b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
17550b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
17560b57cec5SDimitry Andric                  !FD->isInlined() &&
17570b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
17580b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
17590b57cec5SDimitry Andric       }
17600b57cec5SDimitry Andric     }
17610b57cec5SDimitry Andric   }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
17640b57cec5SDimitry Andric   // function.
17650b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
17660b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
17670b57cec5SDimitry Andric       if (!ShouldAddOptNone)
17680b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
17690b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
17700b57cec5SDimitry Andric     }
1771e8d8bef9SDimitry Andric     if (D->hasAttr<HotAttr>())
1772e8d8bef9SDimitry Andric       B.addAttribute(llvm::Attribute::Hot);
17730b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
17740b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
17750b57cec5SDimitry Andric   }
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
17780b57cec5SDimitry Andric 
17790b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
17800b57cec5SDimitry Andric   if (alignment)
1781a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
17820b57cec5SDimitry Andric 
17830b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
17840b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
1785a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
17860b57cec5SDimitry Andric 
17870b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
17880b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
17890b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
17900b57cec5SDimitry Andric   // member function, set its alignment accordingly.
17910b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
17920b57cec5SDimitry Andric     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1793a7dea167SDimitry Andric       F->setAlignment(llvm::Align(2));
17940b57cec5SDimitry Andric   }
17950b57cec5SDimitry Andric 
1796a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
1797a7dea167SDimitry Andric   // attributes on definitions only.
1798a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
1799a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1800a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1801a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
1802a7dea167SDimitry Andric       // current module anyway.
1803a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
18040b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
1805a7dea167SDimitry Andric     }
1806a7dea167SDimitry Andric   }
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
18090b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
18100b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
18110b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
18120b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
18130b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
18140b57cec5SDimitry Andric       llvm::Metadata *Id =
18150b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
18160b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
18170b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
18180b57cec5SDimitry Andric     }
18190b57cec5SDimitry Andric   }
18200b57cec5SDimitry Andric }
18210b57cec5SDimitry Andric 
1822e8d8bef9SDimitry Andric void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
1823e8d8bef9SDimitry Andric                                                   llvm::Function *F) {
1824e8d8bef9SDimitry Andric   if (D->hasAttr<StrictFPAttr>()) {
1825e8d8bef9SDimitry Andric     llvm::AttrBuilder FuncAttrs;
1826e8d8bef9SDimitry Andric     FuncAttrs.addAttribute("strictfp");
1827e8d8bef9SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1828e8d8bef9SDimitry Andric   }
1829e8d8bef9SDimitry Andric }
1830e8d8bef9SDimitry Andric 
18310b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
18320b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
18330b57cec5SDimitry Andric   if (dyn_cast_or_null<NamedDecl>(D))
18340b57cec5SDimitry Andric     setGVProperties(GV, GD);
18350b57cec5SDimitry Andric   else
18360b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
18390b57cec5SDimitry Andric     addUsedGlobal(GV);
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
18420b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(D);
18430b57cec5SDimitry Andric     if (VD->getType().isConstQualified() &&
18440b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
18450b57cec5SDimitry Andric       addUsedGlobal(GV);
18460b57cec5SDimitry Andric   }
18470b57cec5SDimitry Andric }
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
18500b57cec5SDimitry Andric                                                 llvm::AttrBuilder &Attrs) {
18510b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
18520b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
18530b57cec5SDimitry Andric   // parse that and add it to the feature set.
18540b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1855e8d8bef9SDimitry Andric   StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
18560b57cec5SDimitry Andric   std::vector<std::string> Features;
18570b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
18580b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
18590b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
18600b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
18610b57cec5SDimitry Andric   bool AddedAttr = false;
18620b57cec5SDimitry Andric   if (TD || SD) {
18630b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
1864480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
18670b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
18680b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
18710b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
18720b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
18730b57cec5SDimitry Andric     // the function.
18740b57cec5SDimitry Andric     if (TD) {
1875480093f4SDimitry Andric       ParsedTargetAttr ParsedAttr = TD->parse();
1876e8d8bef9SDimitry Andric       if (!ParsedAttr.Architecture.empty() &&
1877e8d8bef9SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Architecture)) {
18780b57cec5SDimitry Andric         TargetCPU = ParsedAttr.Architecture;
1879e8d8bef9SDimitry Andric         TuneCPU = ""; // Clear the tune CPU.
1880e8d8bef9SDimitry Andric       }
1881e8d8bef9SDimitry Andric       if (!ParsedAttr.Tune.empty() &&
1882e8d8bef9SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Tune))
1883e8d8bef9SDimitry Andric         TuneCPU = ParsedAttr.Tune;
18840b57cec5SDimitry Andric     }
18850b57cec5SDimitry Andric   } else {
18860b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
18870b57cec5SDimitry Andric     // function.
18880b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
18890b57cec5SDimitry Andric   }
18900b57cec5SDimitry Andric 
1891e8d8bef9SDimitry Andric   if (!TargetCPU.empty()) {
18920b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
18930b57cec5SDimitry Andric     AddedAttr = true;
18940b57cec5SDimitry Andric   }
1895e8d8bef9SDimitry Andric   if (!TuneCPU.empty()) {
1896e8d8bef9SDimitry Andric     Attrs.addAttribute("tune-cpu", TuneCPU);
1897e8d8bef9SDimitry Andric     AddedAttr = true;
1898e8d8bef9SDimitry Andric   }
18990b57cec5SDimitry Andric   if (!Features.empty()) {
19000b57cec5SDimitry Andric     llvm::sort(Features);
19010b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
19020b57cec5SDimitry Andric     AddedAttr = true;
19030b57cec5SDimitry Andric   }
19040b57cec5SDimitry Andric 
19050b57cec5SDimitry Andric   return AddedAttr;
19060b57cec5SDimitry Andric }
19070b57cec5SDimitry Andric 
19080b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
19090b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
19100b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
19110b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   if (D) {
19140b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
19150b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
19160b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
19170b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
19180b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
19190b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
19200b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1921a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1922a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
19230b57cec5SDimitry Andric     }
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
19260b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
19270b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
19280b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric       llvm::AttrBuilder Attrs;
19310b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
19320b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
19330b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
19340b57cec5SDimitry Andric         // new ones should replace the old.
1935e8d8bef9SDimitry Andric         llvm::AttrBuilder RemoveAttrs;
1936e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-cpu");
1937e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("target-features");
1938e8d8bef9SDimitry Andric         RemoveAttrs.addAttribute("tune-cpu");
1939e8d8bef9SDimitry Andric         F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs);
19400b57cec5SDimitry Andric         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
19410b57cec5SDimitry Andric       }
19420b57cec5SDimitry Andric     }
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
19450b57cec5SDimitry Andric       GO->setSection(CSA->getName());
19460b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
19470b57cec5SDimitry Andric       GO->setSection(SA->getName());
19480b57cec5SDimitry Andric   }
19490b57cec5SDimitry Andric 
19500b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
19510b57cec5SDimitry Andric }
19520b57cec5SDimitry Andric 
19530b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
19540b57cec5SDimitry Andric                                                   llvm::Function *F,
19550b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
19560b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
19570b57cec5SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F);
19580b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
19590b57cec5SDimitry Andric 
19600b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
19630b57cec5SDimitry Andric }
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
19660b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
19670b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
19680b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
19690b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
19700b57cec5SDimitry Andric   // separate linkage types for this.
19710b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
19720b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
19730b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
19740b57cec5SDimitry Andric }
19750b57cec5SDimitry Andric 
19760b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
19770b57cec5SDimitry Andric                                                        llvm::Function *F) {
19780b57cec5SDimitry Andric   // Only if we are checking indirect calls.
19790b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
19800b57cec5SDimitry Andric     return;
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
19830b57cec5SDimitry Andric   // checks elsewhere.
19840b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
19850b57cec5SDimitry Andric     return;
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
19880b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
19890b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
19920b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
19930b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
19940b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
19950b57cec5SDimitry Andric }
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
19980b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
19990b57cec5SDimitry Andric                                           bool IsThunk) {
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
20020b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
20030b57cec5SDimitry Andric     // to the intrinsic's attributes.
20040b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
20050b57cec5SDimitry Andric     return;
20060b57cec5SDimitry Andric   }
20070b57cec5SDimitry Andric 
20080b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
20090b57cec5SDimitry Andric 
20100b57cec5SDimitry Andric   if (!IsIncompleteFunction)
20110b57cec5SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
20140b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
20150b57cec5SDimitry Andric   // GCC and does not actually return "this".
20160b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
20170b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
20180b57cec5SDimitry Andric     assert(!F->arg_empty() &&
20190b57cec5SDimitry Andric            F->arg_begin()->getType()
20200b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
20210b57cec5SDimitry Andric            "unexpected this return");
20220b57cec5SDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
20230b57cec5SDimitry Andric   }
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
20260b57cec5SDimitry Andric   // overridden by a definition.
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   setLinkageForGV(F, FD);
20290b57cec5SDimitry Andric   setGVProperties(F, FD);
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   // Setup target-specific attributes.
20320b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
20330b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
20360b57cec5SDimitry Andric     F->setSection(CSA->getName());
20370b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
20380b57cec5SDimitry Andric      F->setSection(SA->getName());
20390b57cec5SDimitry Andric 
2040d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2041480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
2042d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
2043d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
2044d65cd7a5SDimitry Andric     (void)HasBody;
2045d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
2046d65cd7a5SDimitry Andric                       "available body!");
2047d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
2048480093f4SDimitry Andric       F->addAttribute(llvm::AttributeList::FunctionIndex,
2049480093f4SDimitry Andric                       llvm::Attribute::NoBuiltin);
2050480093f4SDimitry Andric   }
2051480093f4SDimitry Andric 
20520b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
20530b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
20540b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
20550b57cec5SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
20560b57cec5SDimitry Andric                     llvm::Attribute::NoBuiltin);
20570b57cec5SDimitry Andric   }
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
20600b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
20610b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
20620b57cec5SDimitry Andric     if (MD->isVirtual())
20630b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
2066a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
2067a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
2068a7dea167SDimitry Andric   // jump table.
2069a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
2070a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
20710b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
20720b57cec5SDimitry Andric 
20730b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
20740b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
20770b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
20780b57cec5SDimitry Andric     //  - The callback callee (as argument number).
20790b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
20800b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
20810b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
20840b57cec5SDimitry Andric     // identifies the callback callee.
20850b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
20860b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
20870b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
20880b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
20890b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
20900b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
20910b57cec5SDimitry Andric   }
20920b57cec5SDimitry Andric }
20930b57cec5SDimitry Andric 
20940b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2095e8d8bef9SDimitry Andric   assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
20960b57cec5SDimitry Andric          "Only globals with definition can force usage.");
20970b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
20980b57cec5SDimitry Andric }
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
21010b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
21020b57cec5SDimitry Andric          "Only globals with definition can force usage.");
21030b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
21040b57cec5SDimitry Andric }
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
21070b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
21080b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
21090b57cec5SDimitry Andric   if (List.empty())
21100b57cec5SDimitry Andric     return;
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
21130b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
21140b57cec5SDimitry Andric   UsedArray.resize(List.size());
21150b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
21160b57cec5SDimitry Andric     UsedArray[i] =
21170b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
21180b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
21190b57cec5SDimitry Andric   }
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric   if (UsedArray.empty())
21220b57cec5SDimitry Andric     return;
21230b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
21260b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
21270b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
21300b57cec5SDimitry Andric }
21310b57cec5SDimitry Andric 
21320b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
21330b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
21340b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
21350b57cec5SDimitry Andric }
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
21380b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
21390b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
21400b57cec5SDimitry Andric }
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
21430b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
21440b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2145480093f4SDimitry Andric   if (Opt.empty())
2146480093f4SDimitry Andric     return;
21470b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
21480b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
21490b57cec5SDimitry Andric }
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
21520b57cec5SDimitry Andric   auto &C = getLLVMContext();
21530b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
21540b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
21550b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
21560b57cec5SDimitry Andric     return;
21570b57cec5SDimitry Andric   }
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
21600b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
21610b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
21620b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
21630b57cec5SDimitry Andric }
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
21660b57cec5SDimitry Andric /// it depends on, using a postorder walk.
21670b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
21680b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
21690b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
21700b57cec5SDimitry Andric   // Import this module's parent.
21710b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
21720b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
21730b57cec5SDimitry Andric   }
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric   // Import this module's dependencies.
21760b57cec5SDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
21770b57cec5SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
21780b57cec5SDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
21790b57cec5SDimitry Andric   }
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
21820b57cec5SDimitry Andric   // described by this module.
21830b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
21840b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
21870b57cec5SDimitry Andric   // name instead.
21880b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
21890b57cec5SDimitry Andric     return;
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
21920b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
21930b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
21940b57cec5SDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
21950b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
21960b57cec5SDimitry Andric           llvm::MDString::get(Context, "-framework"),
21970b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
22000b57cec5SDimitry Andric       continue;
22010b57cec5SDimitry Andric     }
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric     // Link against a library.
22040b57cec5SDimitry Andric     if (IsELF) {
22050b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
22060b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
22070b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
22080b57cec5SDimitry Andric       };
22090b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
22100b57cec5SDimitry Andric     } else {
22110b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
22120b57cec5SDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
22130b57cec5SDimitry Andric           Mod->LinkLibraries[I - 1].Library, Opt);
22140b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
22150b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
22160b57cec5SDimitry Andric     }
22170b57cec5SDimitry Andric   }
22180b57cec5SDimitry Andric }
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
22210b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
22220b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
22230b57cec5SDimitry Andric   // non-explicit child modules.
22240b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
22250b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
22260b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
22270b57cec5SDimitry Andric 
22280b57cec5SDimitry Andric   // Seed the stack with imported modules.
22290b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
22300b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
22310b57cec5SDimitry Andric     // a header of that same module.
22320b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
22330b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
22340b57cec5SDimitry Andric       continue;
22350b57cec5SDimitry Andric     if (Visited.insert(M).second)
22360b57cec5SDimitry Andric       Stack.push_back(M);
22370b57cec5SDimitry Andric   }
22380b57cec5SDimitry Andric 
22390b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
22400b57cec5SDimitry Andric   // non-leaf modules.
22410b57cec5SDimitry Andric   while (!Stack.empty()) {
22420b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
22430b57cec5SDimitry Andric 
22440b57cec5SDimitry Andric     bool AnyChildren = false;
22450b57cec5SDimitry Andric 
22460b57cec5SDimitry Andric     // Visit the submodules of this module.
22470b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
22480b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
22490b57cec5SDimitry Andric       // linked against.
22500b57cec5SDimitry Andric       if (SM->IsExplicit)
22510b57cec5SDimitry Andric         continue;
22520b57cec5SDimitry Andric 
22530b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
22540b57cec5SDimitry Andric         Stack.push_back(SM);
22550b57cec5SDimitry Andric         AnyChildren = true;
22560b57cec5SDimitry Andric       }
22570b57cec5SDimitry Andric     }
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
22600b57cec5SDimitry Andric     // modules to link against.
22610b57cec5SDimitry Andric     if (!AnyChildren) {
22620b57cec5SDimitry Andric       LinkModules.insert(Mod);
22630b57cec5SDimitry Andric     }
22640b57cec5SDimitry Andric   }
22650b57cec5SDimitry Andric 
22660b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
22670b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
22680b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
22690b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
22700b57cec5SDimitry Andric   Visited.clear();
22710b57cec5SDimitry Andric   for (Module *M : LinkModules)
22720b57cec5SDimitry Andric     if (Visited.insert(M).second)
22730b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
22740b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
22750b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
22760b57cec5SDimitry Andric 
22770b57cec5SDimitry Andric   // Add the linker options metadata flag.
22780b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
22790b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
22800b57cec5SDimitry Andric     NMD->addOperand(MD);
22810b57cec5SDimitry Andric }
22820b57cec5SDimitry Andric 
22830b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
22840b57cec5SDimitry Andric   // Emit deferred declare target declarations.
22850b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
22860b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
22890b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
22900b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
22910b57cec5SDimitry Andric 
22920b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
22930b57cec5SDimitry Andric     EmitDeferredVTables();
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
22960b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
22970b57cec5SDimitry Andric     // emitted that then need those vtables.
22980b57cec5SDimitry Andric     assert(DeferredVTables.empty());
22990b57cec5SDimitry Andric   }
23000b57cec5SDimitry Andric 
2301e8d8bef9SDimitry Andric   // Emit CUDA/HIP static device variables referenced by host code only.
2302e8d8bef9SDimitry Andric   if (getLangOpts().CUDA)
2303e8d8bef9SDimitry Andric     for (auto V : getContext().CUDAStaticDeviceVarReferencedByHost)
2304e8d8bef9SDimitry Andric       DeferredDeclsToEmit.push_back(V);
2305e8d8bef9SDimitry Andric 
23060b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
23070b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
23080b57cec5SDimitry Andric     return;
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
23110b57cec5SDimitry Andric   // work, it will not interfere with this.
23120b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
23130b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
23160b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
23170b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
23180b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
23190b57cec5SDimitry Andric     // different type.
23200b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
23210b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
23240b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
23250b57cec5SDimitry Andric     // GlobalValue.
23260b57cec5SDimitry Andric     if (!GV)
23270b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
23300b57cec5SDimitry Andric     assert(GV);
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
23330b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
23340b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
23350b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
23360b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
23370b57cec5SDimitry Andric     // ignore these cases.
23380b57cec5SDimitry Andric     if (!GV->isDeclaration())
23390b57cec5SDimitry Andric       continue;
23400b57cec5SDimitry Andric 
2341a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
2342a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2343a7dea167SDimitry Andric       continue;
2344a7dea167SDimitry Andric 
23450b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
23460b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
23490b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
23500b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
23510b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
23520b57cec5SDimitry Andric       EmitDeferred();
23530b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
23540b57cec5SDimitry Andric     }
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
23590b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
23600b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
23610b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
23620b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
23650b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
23680b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
23690b57cec5SDimitry Andric            "This queue should only contain external vtables");
23700b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
23710b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
23720b57cec5SDimitry Andric   }
23730b57cec5SDimitry Andric   OpportunisticVTables.clear();
23740b57cec5SDimitry Andric }
23750b57cec5SDimitry Andric 
23760b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
23770b57cec5SDimitry Andric   if (Annotations.empty())
23780b57cec5SDimitry Andric     return;
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
23810b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
23820b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
23830b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
23840b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
23850b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
23860b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
23870b57cec5SDimitry Andric }
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
23900b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
23910b57cec5SDimitry Andric   if (AStr)
23920b57cec5SDimitry Andric     return AStr;
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric   // Not found yet, create a new global.
23950b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
23960b57cec5SDimitry Andric   auto *gv =
23970b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
23980b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
23990b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
24000b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
24010b57cec5SDimitry Andric   AStr = gv;
24020b57cec5SDimitry Andric   return gv;
24030b57cec5SDimitry Andric }
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
24060b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
24070b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
24080b57cec5SDimitry Andric   if (PLoc.isValid())
24090b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
24100b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
24110b57cec5SDimitry Andric }
24120b57cec5SDimitry Andric 
24130b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
24140b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
24150b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
24160b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
24170b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
24180b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
24190b57cec5SDimitry Andric }
24200b57cec5SDimitry Andric 
2421e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2422e8d8bef9SDimitry Andric   ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2423e8d8bef9SDimitry Andric   if (Exprs.empty())
2424e8d8bef9SDimitry Andric     return llvm::ConstantPointerNull::get(Int8PtrTy);
2425e8d8bef9SDimitry Andric 
2426e8d8bef9SDimitry Andric   llvm::FoldingSetNodeID ID;
2427e8d8bef9SDimitry Andric   for (Expr *E : Exprs) {
2428e8d8bef9SDimitry Andric     ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2429e8d8bef9SDimitry Andric   }
2430e8d8bef9SDimitry Andric   llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2431e8d8bef9SDimitry Andric   if (Lookup)
2432e8d8bef9SDimitry Andric     return Lookup;
2433e8d8bef9SDimitry Andric 
2434e8d8bef9SDimitry Andric   llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2435e8d8bef9SDimitry Andric   LLVMArgs.reserve(Exprs.size());
2436e8d8bef9SDimitry Andric   ConstantEmitter ConstEmiter(*this);
2437e8d8bef9SDimitry Andric   llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2438e8d8bef9SDimitry Andric     const auto *CE = cast<clang::ConstantExpr>(E);
2439e8d8bef9SDimitry Andric     return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2440e8d8bef9SDimitry Andric                                     CE->getType());
2441e8d8bef9SDimitry Andric   });
2442e8d8bef9SDimitry Andric   auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2443e8d8bef9SDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2444e8d8bef9SDimitry Andric                                       llvm::GlobalValue::PrivateLinkage, Struct,
2445e8d8bef9SDimitry Andric                                       ".args");
2446e8d8bef9SDimitry Andric   GV->setSection(AnnotationSection);
2447e8d8bef9SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2448e8d8bef9SDimitry Andric   auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
2449e8d8bef9SDimitry Andric 
2450e8d8bef9SDimitry Andric   Lookup = Bitcasted;
2451e8d8bef9SDimitry Andric   return Bitcasted;
2452e8d8bef9SDimitry Andric }
2453e8d8bef9SDimitry Andric 
24540b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
24550b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
24560b57cec5SDimitry Andric                                                 SourceLocation L) {
24570b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
24580b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
24590b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
2460e8d8bef9SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L),
2461e8d8bef9SDimitry Andric                  *Args = EmitAnnotationArgs(AA);
24620b57cec5SDimitry Andric 
2463480093f4SDimitry Andric   llvm::Constant *ASZeroGV = GV;
2464480093f4SDimitry Andric   if (GV->getAddressSpace() != 0) {
2465480093f4SDimitry Andric     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2466480093f4SDimitry Andric                    GV, GV->getValueType()->getPointerTo(0));
2467480093f4SDimitry Andric   }
2468480093f4SDimitry Andric 
24690b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
2470e8d8bef9SDimitry Andric   llvm::Constant *Fields[] = {
2471480093f4SDimitry Andric       llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
24720b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
24730b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2474e8d8bef9SDimitry Andric       LineNoCst,
2475e8d8bef9SDimitry Andric       Args,
24760b57cec5SDimitry Andric   };
24770b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
24780b57cec5SDimitry Andric }
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
24810b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
24820b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
24830b57cec5SDimitry Andric   // Get the struct elements for these annotations.
24840b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
24850b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
24860b57cec5SDimitry Andric }
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
24890b57cec5SDimitry Andric                                            llvm::Function *Fn,
24900b57cec5SDimitry Andric                                            SourceLocation Loc) const {
24910b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
24920b57cec5SDimitry Andric   // Blacklist by function name.
24930b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
24940b57cec5SDimitry Andric     return true;
24950b57cec5SDimitry Andric   // Blacklist by location.
24960b57cec5SDimitry Andric   if (Loc.isValid())
24970b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
24980b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
24990b57cec5SDimitry Andric   // it's located in the main file.
25000b57cec5SDimitry Andric   auto &SM = Context.getSourceManager();
25010b57cec5SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
25020b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
25030b57cec5SDimitry Andric   }
25040b57cec5SDimitry Andric   return false;
25050b57cec5SDimitry Andric }
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
25080b57cec5SDimitry Andric                                            SourceLocation Loc, QualType Ty,
25090b57cec5SDimitry Andric                                            StringRef Category) const {
25100b57cec5SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
25110b57cec5SDimitry Andric   const SanitizerMask EnabledAsanMask =
25120b57cec5SDimitry Andric       LangOpts.Sanitize.Mask &
25130b57cec5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress |
25140b57cec5SDimitry Andric        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
25150b57cec5SDimitry Andric        SanitizerKind::MemTag);
25160b57cec5SDimitry Andric   if (!EnabledAsanMask)
25170b57cec5SDimitry Andric     return false;
25180b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
25190b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
25200b57cec5SDimitry Andric     return true;
25210b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
25220b57cec5SDimitry Andric     return true;
25230b57cec5SDimitry Andric   // Check global type.
25240b57cec5SDimitry Andric   if (!Ty.isNull()) {
25250b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
25260b57cec5SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
25270b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
25280b57cec5SDimitry Andric       Ty = AT->getElementType();
25290b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
25300b57cec5SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
25310b57cec5SDimitry Andric     if (Ty->isRecordType()) {
25320b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
25330b57cec5SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
25340b57cec5SDimitry Andric         return true;
25350b57cec5SDimitry Andric     }
25360b57cec5SDimitry Andric   }
25370b57cec5SDimitry Andric   return false;
25380b57cec5SDimitry Andric }
25390b57cec5SDimitry Andric 
25400b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
25410b57cec5SDimitry Andric                                    StringRef Category) const {
25420b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
25430b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
25440b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
25450b57cec5SDimitry Andric   if (Loc.isValid())
25460b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
25470b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
25480b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
25490b57cec5SDimitry Andric   switch (Attr) {
25500b57cec5SDimitry Andric   case ImbueAttr::NONE:
25510b57cec5SDimitry Andric     return false;
25520b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
25530b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
25540b57cec5SDimitry Andric     break;
25550b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
25560b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
25570b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
25580b57cec5SDimitry Andric     break;
25590b57cec5SDimitry Andric   case ImbueAttr::NEVER:
25600b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
25610b57cec5SDimitry Andric     break;
25620b57cec5SDimitry Andric   }
25630b57cec5SDimitry Andric   return true;
25640b57cec5SDimitry Andric }
25650b57cec5SDimitry Andric 
2566e8d8bef9SDimitry Andric bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2567e8d8bef9SDimitry Andric                                            SourceLocation Loc) const {
2568e8d8bef9SDimitry Andric   const auto &ProfileList = getContext().getProfileList();
2569e8d8bef9SDimitry Andric   // If the profile list is empty, then instrument everything.
2570e8d8bef9SDimitry Andric   if (ProfileList.isEmpty())
2571e8d8bef9SDimitry Andric     return false;
2572e8d8bef9SDimitry Andric   CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2573e8d8bef9SDimitry Andric   // First, check the function name.
2574e8d8bef9SDimitry Andric   Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2575e8d8bef9SDimitry Andric   if (V.hasValue())
2576e8d8bef9SDimitry Andric     return *V;
2577e8d8bef9SDimitry Andric   // Next, check the source location.
2578e8d8bef9SDimitry Andric   if (Loc.isValid()) {
2579e8d8bef9SDimitry Andric     Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2580e8d8bef9SDimitry Andric     if (V.hasValue())
2581e8d8bef9SDimitry Andric       return *V;
2582e8d8bef9SDimitry Andric   }
2583e8d8bef9SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
2584e8d8bef9SDimitry Andric   // it's located in the main file.
2585e8d8bef9SDimitry Andric   auto &SM = Context.getSourceManager();
2586e8d8bef9SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2587e8d8bef9SDimitry Andric     Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2588e8d8bef9SDimitry Andric     if (V.hasValue())
2589e8d8bef9SDimitry Andric       return *V;
2590e8d8bef9SDimitry Andric   }
2591e8d8bef9SDimitry Andric   return ProfileList.getDefault();
2592e8d8bef9SDimitry Andric }
2593e8d8bef9SDimitry Andric 
25940b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
25950b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
25960b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
25970b57cec5SDimitry Andric     return true;
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts) {
26000b57cec5SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(Global);
26010b57cec5SDimitry Andric     if (VD && VD->getType().isConstQualified() &&
26020b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
26030b57cec5SDimitry Andric       return true;
26040b57cec5SDimitry Andric   }
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
26070b57cec5SDimitry Andric }
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2610a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
26110b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
26120b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
26130b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
26140b57cec5SDimitry Andric       return false;
2615a7dea167SDimitry Andric     // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2616a7dea167SDimitry Andric     // not emit them eagerly unless we sure that the function must be emitted on
2617a7dea167SDimitry Andric     // the host.
2618a7dea167SDimitry Andric     if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2619a7dea167SDimitry Andric         !LangOpts.OpenMPIsDevice &&
2620a7dea167SDimitry Andric         !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2621a7dea167SDimitry Andric         !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2622a7dea167SDimitry Andric       return false;
2623a7dea167SDimitry Andric   }
26240b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
26250b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
26260b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
26270b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
26280b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
26290b57cec5SDimitry Andric       return false;
26300b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
26310b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
26320b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
26330b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
26340b57cec5SDimitry Andric       !isTypeConstant(Global->getType(), false) &&
26350b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
26360b57cec5SDimitry Andric     return false;
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric   return true;
26390b57cec5SDimitry Andric }
26400b57cec5SDimitry Andric 
26415ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
26425ffd83dbSDimitry Andric   StringRef Name = getMangledName(GD);
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
26450b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric   // Look for an existing global.
26480b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
26490b57cec5SDimitry Andric     return ConstantAddress(GV, Alignment);
26500b57cec5SDimitry Andric 
26515ffd83dbSDimitry Andric   ConstantEmitter Emitter(*this);
26525ffd83dbSDimitry Andric   llvm::Constant *Init;
26535ffd83dbSDimitry Andric 
26545ffd83dbSDimitry Andric   APValue &V = GD->getAsAPValue();
26555ffd83dbSDimitry Andric   if (!V.isAbsent()) {
26565ffd83dbSDimitry Andric     // If possible, emit the APValue version of the initializer. In particular,
26575ffd83dbSDimitry Andric     // this gets the type of the constant right.
26585ffd83dbSDimitry Andric     Init = Emitter.emitForInitializer(
26595ffd83dbSDimitry Andric         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
26605ffd83dbSDimitry Andric   } else {
26615ffd83dbSDimitry Andric     // As a fallback, directly construct the constant.
26625ffd83dbSDimitry Andric     // FIXME: This may get padding wrong under esoteric struct layout rules.
26635ffd83dbSDimitry Andric     // MSVC appears to create a complete type 'struct __s_GUID' that it
26645ffd83dbSDimitry Andric     // presumably uses to represent these constants.
26655ffd83dbSDimitry Andric     MSGuidDecl::Parts Parts = GD->getParts();
26665ffd83dbSDimitry Andric     llvm::Constant *Fields[4] = {
26675ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
26685ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
26695ffd83dbSDimitry Andric         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
26705ffd83dbSDimitry Andric         llvm::ConstantDataArray::getRaw(
26715ffd83dbSDimitry Andric             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
26725ffd83dbSDimitry Andric             Int8Ty)};
26735ffd83dbSDimitry Andric     Init = llvm::ConstantStruct::getAnon(Fields);
26745ffd83dbSDimitry Andric   }
26750b57cec5SDimitry Andric 
26760b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
26770b57cec5SDimitry Andric       getModule(), Init->getType(),
26780b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
26790b57cec5SDimitry Andric   if (supportsCOMDAT())
26800b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
26810b57cec5SDimitry Andric   setDSOLocal(GV);
26825ffd83dbSDimitry Andric 
26835ffd83dbSDimitry Andric   llvm::Constant *Addr = GV;
26845ffd83dbSDimitry Andric   if (!V.isAbsent()) {
26855ffd83dbSDimitry Andric     Emitter.finalize(GV);
26865ffd83dbSDimitry Andric   } else {
26875ffd83dbSDimitry Andric     llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
26885ffd83dbSDimitry Andric     Addr = llvm::ConstantExpr::getBitCast(
26895ffd83dbSDimitry Andric         GV, Ty->getPointerTo(GV->getAddressSpace()));
26905ffd83dbSDimitry Andric   }
26915ffd83dbSDimitry Andric   return ConstantAddress(Addr, Alignment);
26920b57cec5SDimitry Andric }
26930b57cec5SDimitry Andric 
2694e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2695e8d8bef9SDimitry Andric     const TemplateParamObjectDecl *TPO) {
2696e8d8bef9SDimitry Andric   StringRef Name = getMangledName(TPO);
2697e8d8bef9SDimitry Andric   CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2698e8d8bef9SDimitry Andric 
2699e8d8bef9SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2700e8d8bef9SDimitry Andric     return ConstantAddress(GV, Alignment);
2701e8d8bef9SDimitry Andric 
2702e8d8bef9SDimitry Andric   ConstantEmitter Emitter(*this);
2703e8d8bef9SDimitry Andric   llvm::Constant *Init = Emitter.emitForInitializer(
2704e8d8bef9SDimitry Andric         TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2705e8d8bef9SDimitry Andric 
2706e8d8bef9SDimitry Andric   if (!Init) {
2707e8d8bef9SDimitry Andric     ErrorUnsupported(TPO, "template parameter object");
2708e8d8bef9SDimitry Andric     return ConstantAddress::invalid();
2709e8d8bef9SDimitry Andric   }
2710e8d8bef9SDimitry Andric 
2711e8d8bef9SDimitry Andric   auto *GV = new llvm::GlobalVariable(
2712e8d8bef9SDimitry Andric       getModule(), Init->getType(),
2713e8d8bef9SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2714e8d8bef9SDimitry Andric   if (supportsCOMDAT())
2715e8d8bef9SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2716e8d8bef9SDimitry Andric   Emitter.finalize(GV);
2717e8d8bef9SDimitry Andric 
2718e8d8bef9SDimitry Andric   return ConstantAddress(GV, Alignment);
2719e8d8bef9SDimitry Andric }
2720e8d8bef9SDimitry Andric 
27210b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
27220b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
27230b57cec5SDimitry Andric   assert(AA && "No alias?");
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
27260b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
27290b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
27300b57cec5SDimitry Andric   if (Entry) {
27310b57cec5SDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
27320b57cec5SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
27330b57cec5SDimitry Andric     return ConstantAddress(Ptr, Alignment);
27340b57cec5SDimitry Andric   }
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric   llvm::Constant *Aliasee;
27370b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
27380b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
27390b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
27400b57cec5SDimitry Andric                                       /*ForVTable=*/false);
27410b57cec5SDimitry Andric   else
27420b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
27430b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
27440b57cec5SDimitry Andric                                     nullptr);
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
27470b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
27480b57cec5SDimitry Andric   WeakRefReferences.insert(F);
27490b57cec5SDimitry Andric 
27500b57cec5SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
27510b57cec5SDimitry Andric }
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
27540b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
27550b57cec5SDimitry Andric 
27560b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
27570b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
27580b57cec5SDimitry Andric     return;
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
27610b57cec5SDimitry Andric   // emit it now.
27620b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
27630b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
27640b57cec5SDimitry Andric 
27650b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
27660b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
27670b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
27680b57cec5SDimitry Andric 
27690b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
27700b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
27710b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
27720b57cec5SDimitry Andric 
27730b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
27740b57cec5SDimitry Andric   if (LangOpts.CUDA) {
27750b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
27760b57cec5SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
27770b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
27780b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
27790b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
27805ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
27815ffd83dbSDimitry Andric           !Global->getType()->isCUDADeviceBuiltinTextureType())
27820b57cec5SDimitry Andric         return;
27830b57cec5SDimitry Andric     } else {
27840b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
27850b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
27860b57cec5SDimitry Andric       // size and host-side address in order to provide access to
27870b57cec5SDimitry Andric       // their device-side incarnations.
27880b57cec5SDimitry Andric 
27890b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
27900b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
27910b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
27920b57cec5SDimitry Andric         return;
27930b57cec5SDimitry Andric 
27940b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
27950b57cec5SDimitry Andric              "Expected Variable or Function");
27960b57cec5SDimitry Andric     }
27970b57cec5SDimitry Andric   }
27980b57cec5SDimitry Andric 
27990b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
2800a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
28010b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
28020b57cec5SDimitry Andric       return;
28030b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
28040b57cec5SDimitry Andric       if (MustBeEmitted(Global))
28050b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
28060b57cec5SDimitry Andric       return;
28070b57cec5SDimitry Andric     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
28080b57cec5SDimitry Andric       if (MustBeEmitted(Global))
28090b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
28100b57cec5SDimitry Andric       return;
28110b57cec5SDimitry Andric     }
28120b57cec5SDimitry Andric   }
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
28150b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
28160b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
28170b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
28180b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
28190b57cec5SDimitry Andric         return;
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
28220b57cec5SDimitry Andric 
28230b57cec5SDimitry Andric       // Compute the function info and LLVM type.
28240b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
28250b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
28280b57cec5SDimitry Andric                               /*DontDefer=*/false);
28290b57cec5SDimitry Andric       return;
28300b57cec5SDimitry Andric     }
28310b57cec5SDimitry Andric   } else {
28320b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
28330b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
28340b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
28350b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
28360b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
28370b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
28380b57cec5SDimitry Andric         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
28390b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
28400b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
28410b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
28420b57cec5SDimitry Andric           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
28430b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
28440b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
28450b57cec5SDimitry Andric           } else {
28460b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
28470b57cec5SDimitry Andric                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
28480b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
28490b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
28500b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
28510b57cec5SDimitry Andric           }
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric           return;
28540b57cec5SDimitry Andric         }
28550b57cec5SDimitry Andric       }
28560b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
28570b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
28580b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
28590b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
28600b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
28610b57cec5SDimitry Andric       return;
28620b57cec5SDimitry Andric     }
28630b57cec5SDimitry Andric   }
28640b57cec5SDimitry Andric 
28650b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
28660b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
28670b57cec5SDimitry Andric   // to benefit from cache locality.
28680b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
28690b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
28700b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
28710b57cec5SDimitry Andric     return;
28720b57cec5SDimitry Andric   }
28730b57cec5SDimitry Andric 
28740b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
28750b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
28760b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
28770b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
28780b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
28790b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
28800b57cec5SDimitry Andric   }
28810b57cec5SDimitry Andric 
28820b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
28830b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
28840b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
28850b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
28860b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
28870b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
28880b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
28890b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
28900b57cec5SDimitry Andric   } else {
28910b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
28920b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
28930b57cec5SDimitry Andric     // DeferredDeclsToEmit.
28940b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
28950b57cec5SDimitry Andric   }
28960b57cec5SDimitry Andric }
28970b57cec5SDimitry Andric 
28980b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
28990b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
29000b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
29010b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
29020b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
29030b57cec5SDimitry Andric         return true;
29040b57cec5SDimitry Andric 
29050b57cec5SDimitry Andric   return false;
29060b57cec5SDimitry Andric }
29070b57cec5SDimitry Andric 
29080b57cec5SDimitry Andric namespace {
29090b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
29100b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
29110b57cec5SDimitry Andric     const StringRef Name;
29120b57cec5SDimitry Andric     const Builtin::Context &BI;
29130b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
29140b57cec5SDimitry Andric         : Name(N), BI(C) {}
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
29170b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
29180b57cec5SDimitry Andric       if (!FD)
29190b57cec5SDimitry Andric         return false;
29200b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
29210b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
29220b57cec5SDimitry Andric         return true;
29230b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
29240b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
29250b57cec5SDimitry Andric         return false;
29260b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
29270b57cec5SDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
29280b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
29290b57cec5SDimitry Andric         return true;
29300b57cec5SDimitry Andric       }
29310b57cec5SDimitry Andric       return false;
29320b57cec5SDimitry Andric     }
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
29350b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
29360b57cec5SDimitry Andric         if (Child && this->Visit(Child))
29370b57cec5SDimitry Andric           return true;
29380b57cec5SDimitry Andric       return false;
29390b57cec5SDimitry Andric     }
29400b57cec5SDimitry Andric   };
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
29430b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
29440b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
29450b57cec5SDimitry Andric     bool SafeToInline = true;
29460b57cec5SDimitry Andric 
29470b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
29480b57cec5SDimitry Andric 
29490b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
29500b57cec5SDimitry Andric       if (VD->getTLSKind()) {
29510b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
29520b57cec5SDimitry Andric         SafeToInline = false;
29530b57cec5SDimitry Andric         return SafeToInline;
29540b57cec5SDimitry Andric       }
29550b57cec5SDimitry Andric 
29560b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
29570b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
29580b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
29590b57cec5SDimitry Andric 
29600b57cec5SDimitry Andric       return SafeToInline;
29610b57cec5SDimitry Andric     }
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
29640b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
29650b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
29660b57cec5SDimitry Andric       return SafeToInline;
29670b57cec5SDimitry Andric     }
29680b57cec5SDimitry Andric 
29690b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
29700b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
29710b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
29720b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
29730b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
29740b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
29750b57cec5SDimitry Andric       return SafeToInline;
29760b57cec5SDimitry Andric     }
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
29790b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
29800b57cec5SDimitry Andric       return SafeToInline;
29810b57cec5SDimitry Andric     }
29820b57cec5SDimitry Andric 
29830b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
29840b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
29850b57cec5SDimitry Andric       if (!M) {
29860b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
29870b57cec5SDimitry Andric         SafeToInline = true;
29880b57cec5SDimitry Andric       } else {
29890b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
29900b57cec5SDimitry Andric       }
29910b57cec5SDimitry Andric       return SafeToInline;
29920b57cec5SDimitry Andric     }
29930b57cec5SDimitry Andric 
29940b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
29950b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
29960b57cec5SDimitry Andric       return SafeToInline;
29970b57cec5SDimitry Andric     }
29980b57cec5SDimitry Andric 
29990b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
30000b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
30010b57cec5SDimitry Andric       return SafeToInline;
30020b57cec5SDimitry Andric     }
30030b57cec5SDimitry Andric   };
30040b57cec5SDimitry Andric }
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
30070b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
30080b57cec5SDimitry Andric // ends up pointing to itself.
30090b57cec5SDimitry Andric bool
30100b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
30110b57cec5SDimitry Andric   StringRef Name;
30120b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
30130b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
30140b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
30150b57cec5SDimitry Andric     if (!Attr)
30160b57cec5SDimitry Andric       return false;
30170b57cec5SDimitry Andric     Name = Attr->getLabel();
30180b57cec5SDimitry Andric   } else {
30190b57cec5SDimitry Andric     Name = FD->getName();
30200b57cec5SDimitry Andric   }
30210b57cec5SDimitry Andric 
30220b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
30230b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
30240b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
30250b57cec5SDimitry Andric }
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
30280b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
30290b57cec5SDimitry Andric     return true;
30300b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
30310b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
30320b57cec5SDimitry Andric     return false;
30330b57cec5SDimitry Andric 
30340b57cec5SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
30350b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
30360b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
30370b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
30380b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
30390b57cec5SDimitry Andric       return false;
30400b57cec5SDimitry Andric 
30410b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
30420b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
30430b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
30440b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
30450b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
30460b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
30470b57cec5SDimitry Andric             return false;
30480b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
30490b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
30500b57cec5SDimitry Andric           return false;
30510b57cec5SDimitry Andric     }
30520b57cec5SDimitry Andric   }
30530b57cec5SDimitry Andric 
30540b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
30550b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
30565ffd83dbSDimitry Andric   // but a function that calls itself through asm label/`__builtin_` trickery is
30575ffd83dbSDimitry Andric   // clearly not equivalent to the real implementation.
30580b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
30590b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
30600b57cec5SDimitry Andric }
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
30630b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
30640b57cec5SDimitry Andric }
30650b57cec5SDimitry Andric 
30660b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
30670b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
30680b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
30690b57cec5SDimitry Andric 
30700b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
30710b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
30720b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
30730b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
30740b57cec5SDimitry Andric     // Requires multiple emits.
30750b57cec5SDimitry Andric   } else
30760b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
30770b57cec5SDimitry Andric }
30780b57cec5SDimitry Andric 
30790b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
30800b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
30810b57cec5SDimitry Andric 
30820b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
30830b57cec5SDimitry Andric                                  Context.getSourceManager(),
30840b57cec5SDimitry Andric                                  "Generating code for declaration");
30850b57cec5SDimitry Andric 
30860b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
30870b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
30880b57cec5SDimitry Andric     // linkage.
30890b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
30900b57cec5SDimitry Andric       return;
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
30930b57cec5SDimitry Andric       std::string Name;
30940b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
30950b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
30960b57cec5SDimitry Andric                                /*Qualified=*/true);
30970b57cec5SDimitry Andric       return Name;
30980b57cec5SDimitry Andric     });
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
31010b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
31020b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
31030b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
31040b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
31050b57cec5SDimitry Andric       else if (FD->isMultiVersion())
31060b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
31070b57cec5SDimitry Andric       else
31080b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric       if (Method->isVirtual())
31110b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric       return;
31140b57cec5SDimitry Andric     }
31150b57cec5SDimitry Andric 
31160b57cec5SDimitry Andric     if (FD->isMultiVersion())
31170b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
31180b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
31190b57cec5SDimitry Andric   }
31200b57cec5SDimitry Andric 
31210b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
31220b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
31250b57cec5SDimitry Andric }
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
31280b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
31290b57cec5SDimitry Andric 
31300b57cec5SDimitry Andric static unsigned
31310b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
31320b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
31330b57cec5SDimitry Andric   unsigned Priority = 0;
31340b57cec5SDimitry Andric   for (StringRef Feat : RO.Conditions.Features)
31350b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
31360b57cec5SDimitry Andric 
31370b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
31380b57cec5SDimitry Andric     Priority = std::max(
31390b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
31400b57cec5SDimitry Andric   return Priority;
31410b57cec5SDimitry Andric }
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
31440b57cec5SDimitry Andric   for (GlobalDecl GD : MultiVersionFuncs) {
31450b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
31460b57cec5SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
31470b57cec5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
31480b57cec5SDimitry Andric         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
31490b57cec5SDimitry Andric           GlobalDecl CurGD{
31500b57cec5SDimitry Andric               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
31510b57cec5SDimitry Andric           StringRef MangledName = getMangledName(CurGD);
31520b57cec5SDimitry Andric           llvm::Constant *Func = GetGlobalValue(MangledName);
31530b57cec5SDimitry Andric           if (!Func) {
31540b57cec5SDimitry Andric             if (CurFD->isDefined()) {
31550b57cec5SDimitry Andric               EmitGlobalFunctionDefinition(CurGD, nullptr);
31560b57cec5SDimitry Andric               Func = GetGlobalValue(MangledName);
31570b57cec5SDimitry Andric             } else {
31580b57cec5SDimitry Andric               const CGFunctionInfo &FI =
31590b57cec5SDimitry Andric                   getTypes().arrangeGlobalDeclaration(GD);
31600b57cec5SDimitry Andric               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
31610b57cec5SDimitry Andric               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
31620b57cec5SDimitry Andric                                        /*DontDefer=*/false, ForDefinition);
31630b57cec5SDimitry Andric             }
31640b57cec5SDimitry Andric             assert(Func && "This should have just been created");
31650b57cec5SDimitry Andric           }
31660b57cec5SDimitry Andric 
31670b57cec5SDimitry Andric           const auto *TA = CurFD->getAttr<TargetAttr>();
31680b57cec5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
31690b57cec5SDimitry Andric           TA->getAddedFeatures(Feats);
31700b57cec5SDimitry Andric 
31710b57cec5SDimitry Andric           Options.emplace_back(cast<llvm::Function>(Func),
31720b57cec5SDimitry Andric                                TA->getArchitecture(), Feats);
31730b57cec5SDimitry Andric         });
31740b57cec5SDimitry Andric 
31750b57cec5SDimitry Andric     llvm::Function *ResolverFunc;
31760b57cec5SDimitry Andric     const TargetInfo &TI = getTarget();
31770b57cec5SDimitry Andric 
3178a7dea167SDimitry Andric     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
31790b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(
31800b57cec5SDimitry Andric           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3181a7dea167SDimitry Andric       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3182a7dea167SDimitry Andric     } else {
31830b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3184a7dea167SDimitry Andric     }
31850b57cec5SDimitry Andric 
31860b57cec5SDimitry Andric     if (supportsCOMDAT())
31870b57cec5SDimitry Andric       ResolverFunc->setComdat(
31880b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
31890b57cec5SDimitry Andric 
31900b57cec5SDimitry Andric     llvm::stable_sort(
31910b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
31920b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
31930b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
31940b57cec5SDimitry Andric         });
31950b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
31960b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
31970b57cec5SDimitry Andric   }
31980b57cec5SDimitry Andric }
31990b57cec5SDimitry Andric 
32000b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
32010b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
32020b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
32030b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
32040b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
32050b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
32080b57cec5SDimitry Andric     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
32090b57cec5SDimitry Andric     DeclTy = getTypes().GetFunctionType(FInfo);
32100b57cec5SDimitry Andric   }
32110b57cec5SDimitry Andric 
32120b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric   llvm::Type *ResolverType;
32150b57cec5SDimitry Andric   GlobalDecl ResolverGD;
32160b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
32170b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
32180b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
32190b57cec5SDimitry Andric                                Context.getTargetAddressSpace(FD->getType())),
32200b57cec5SDimitry Andric         false);
32210b57cec5SDimitry Andric   else {
32220b57cec5SDimitry Andric     ResolverType = DeclTy;
32230b57cec5SDimitry Andric     ResolverGD = GD;
32240b57cec5SDimitry Andric   }
32250b57cec5SDimitry Andric 
32260b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
32270b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3228a7dea167SDimitry Andric   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3229a7dea167SDimitry Andric   if (supportsCOMDAT())
3230a7dea167SDimitry Andric     ResolverFunc->setComdat(
3231a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
32340b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
32350b57cec5SDimitry Andric   unsigned Index = 0;
32360b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
32370b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
32380b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
32390b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric     if (!Func) {
32440b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
32450b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
32460b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
32470b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
32480b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
32490b57cec5SDimitry Andric       } else {
32500b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
32510b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
32540b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
32550b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
32560b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
32570b57cec5SDimitry Andric       }
32580b57cec5SDimitry Andric     }
32590b57cec5SDimitry Andric 
32600b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
32610b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
32620b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
32630b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
32640b57cec5SDimitry Andric     Features.erase(std::remove_if(
32650b57cec5SDimitry Andric         Features.begin(), Features.end(), [&Target](StringRef Feat) {
32660b57cec5SDimitry Andric           return !Target.validateCpuSupports(Feat);
32670b57cec5SDimitry Andric         }), Features.end());
32680b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
32690b57cec5SDimitry Andric     ++Index;
32700b57cec5SDimitry Andric   }
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric   llvm::sort(
32730b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
32740b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
32750b57cec5SDimitry Andric         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
32760b57cec5SDimitry Andric                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
32770b57cec5SDimitry Andric       });
32780b57cec5SDimitry Andric 
32790b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
32800b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
32810b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
32820b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
32830b57cec5SDimitry Andric   while (Options.size() > 1 &&
32840b57cec5SDimitry Andric          CodeGenFunction::GetX86CpuSupportsMask(
32850b57cec5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
32860b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
32870b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
32880b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
32890b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
32900b57cec5SDimitry Andric     else
32910b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
32920b57cec5SDimitry Andric   }
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
32950b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3296a7dea167SDimitry Andric 
3297a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
3298a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
3299a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3300a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3301a7dea167SDimitry Andric     if (!AliasFunc) {
3302a7dea167SDimitry Andric       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3303a7dea167SDimitry Andric           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3304a7dea167SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3305a7dea167SDimitry Andric       auto *GA = llvm::GlobalAlias::create(
3306a7dea167SDimitry Andric          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3307a7dea167SDimitry Andric       GA->setLinkage(llvm::Function::WeakODRLinkage);
3308a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
3309a7dea167SDimitry Andric     }
3310a7dea167SDimitry Andric   }
33110b57cec5SDimitry Andric }
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
33140b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
33150b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
33160b57cec5SDimitry Andric     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
33170b57cec5SDimitry Andric   std::string MangledName =
33180b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
33190b57cec5SDimitry Andric 
33200b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
33210b57cec5SDimitry Andric   // a separate resolver).
33220b57cec5SDimitry Andric   std::string ResolverName = MangledName;
33230b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
33240b57cec5SDimitry Andric     ResolverName += ".ifunc";
33250b57cec5SDimitry Andric   else if (FD->isTargetMultiVersion())
33260b57cec5SDimitry Andric     ResolverName += ".resolver";
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric   // If this already exists, just return that one.
33290b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
33300b57cec5SDimitry Andric     return ResolverGV;
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric   // Since this is the first time we've created this IFunc, make sure
33330b57cec5SDimitry Andric   // that we put this multiversioned function into the list to be
33340b57cec5SDimitry Andric   // replaced later if necessary (target multiversioning only).
33350b57cec5SDimitry Andric   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
33360b57cec5SDimitry Andric     MultiVersionFuncs.push_back(GD);
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric   if (getTarget().supportsIFunc()) {
33390b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
33400b57cec5SDimitry Andric         llvm::PointerType::get(
33410b57cec5SDimitry Andric             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
33420b57cec5SDimitry Andric         false);
33430b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
33440b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
33450b57cec5SDimitry Andric         /*ForVTable=*/false);
33460b57cec5SDimitry Andric     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3347a7dea167SDimitry Andric         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
33480b57cec5SDimitry Andric     GIF->setName(ResolverName);
33490b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric     return GIF;
33520b57cec5SDimitry Andric   }
33530b57cec5SDimitry Andric 
33540b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
33550b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
33560b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
33570b57cec5SDimitry Andric          "Resolver should be created for the first time");
33580b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
33590b57cec5SDimitry Andric   return Resolver;
33600b57cec5SDimitry Andric }
33610b57cec5SDimitry Andric 
33620b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
33630b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
33640b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
33650b57cec5SDimitry Andric /// bitcasted to the right type.
33660b57cec5SDimitry Andric ///
33670b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
33680b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
33690b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
33700b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
33710b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
33720b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
33730b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
33740b57cec5SDimitry Andric 
33750b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
33760b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
33770b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
33780b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
33790b57cec5SDimitry Andric     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
33800b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
33810b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
33820b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
33830b57cec5SDimitry Andric         GlobalDecl GDDef;
33840b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
33850b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
33860b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
33870b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
33880b57cec5SDimitry Andric         else
33890b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
33900b57cec5SDimitry Andric         EmitGlobal(GDDef);
33910b57cec5SDimitry Andric       }
33920b57cec5SDimitry Andric     }
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
33955ffd83dbSDimitry Andric       if (FD->hasAttr<TargetAttr>())
33960b57cec5SDimitry Andric         UpdateMultiVersionNames(GD, FD);
33970b57cec5SDimitry Andric       if (!IsForDefinition)
33980b57cec5SDimitry Andric         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
33990b57cec5SDimitry Andric     }
34000b57cec5SDimitry Andric   }
34010b57cec5SDimitry Andric 
34020b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
34030b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
34040b57cec5SDimitry Andric   if (Entry) {
34050b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
34060b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
34070b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
34080b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
34090b57cec5SDimitry Andric     }
34100b57cec5SDimitry Andric 
34110b57cec5SDimitry Andric     // Handle dropped DLL attributes.
34120b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
34130b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
34140b57cec5SDimitry Andric       setDSOLocal(Entry);
34150b57cec5SDimitry Andric     }
34160b57cec5SDimitry Andric 
34170b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
34180b57cec5SDimitry Andric     // error.
34190b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
34200b57cec5SDimitry Andric       GlobalDecl OtherGD;
34210b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
34220b57cec5SDimitry Andric       // to make sure that we issue an error only once.
34230b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
34240b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
34250b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
34260b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
34270b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
34280b57cec5SDimitry Andric             << MangledName;
34290b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
34300b57cec5SDimitry Andric                           diag::note_previous_definition);
34310b57cec5SDimitry Andric       }
34320b57cec5SDimitry Andric     }
34330b57cec5SDimitry Andric 
34340b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
34355ffd83dbSDimitry Andric         (Entry->getValueType() == Ty)) {
34360b57cec5SDimitry Andric       return Entry;
34370b57cec5SDimitry Andric     }
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric     // Make sure the result is of the correct type.
34400b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
34410b57cec5SDimitry Andric     // function, not just return a bitcast.)
34420b57cec5SDimitry Andric     if (!IsForDefinition)
34430b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
34440b57cec5SDimitry Andric   }
34450b57cec5SDimitry Andric 
34460b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
34470b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
34480b57cec5SDimitry Andric   // sure not to try to set attributes.
34490b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   llvm::FunctionType *FTy;
34520b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
34530b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
34540b57cec5SDimitry Andric   } else {
34550b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
34560b57cec5SDimitry Andric     IsIncompleteFunction = true;
34570b57cec5SDimitry Andric   }
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric   llvm::Function *F =
34600b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
34610b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
34640b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
34650b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
34660b57cec5SDimitry Andric   //
34670b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
34680b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
34690b57cec5SDimitry Andric   if (Entry) {
34700b57cec5SDimitry Andric     F->takeName(Entry);
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
34730b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
34740b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
34750b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
34760b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
34770b57cec5SDimitry Andric     // dropping arguments.
34780b57cec5SDimitry Andric     if (!Entry->use_empty()) {
34790b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
34800b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
34810b57cec5SDimitry Andric     }
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
34845ffd83dbSDimitry Andric         F, Entry->getValueType()->getPointerTo());
34850b57cec5SDimitry Andric     addGlobalValReplacement(Entry, BC);
34860b57cec5SDimitry Andric   }
34870b57cec5SDimitry Andric 
34880b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
34890b57cec5SDimitry Andric   if (D)
34900b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
34910b57cec5SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
34920b57cec5SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
34930b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
34940b57cec5SDimitry Andric   }
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric   if (!DontDefer) {
34970b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
34980b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
34990b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
35000b57cec5SDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
35010b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
35020b57cec5SDimitry Andric                                            GD.getDtorType()))
35030b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
35040b57cec5SDimitry Andric 
35050b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
35060b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
35070b57cec5SDimitry Andric     // of the file.
35080b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
35090b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
35100b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
35110b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
35120b57cec5SDimitry Andric       // don't need it anymore).
35130b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
35140b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
35150b57cec5SDimitry Andric 
35160b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
35170b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
35180b57cec5SDimitry Andric       // we might not find a top-level definition:
35190b57cec5SDimitry Andric       //   - member functions defined inline in their classes
35200b57cec5SDimitry Andric       //   - friend functions defined inline in some class
35210b57cec5SDimitry Andric       //   - special member functions with implicit definitions
35220b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
35230b57cec5SDimitry Andric       // this will be unnecessary.
35240b57cec5SDimitry Andric       //
35250b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
35260b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
35270b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
35280b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
35290b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
35300b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
35310b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
35320b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
35330b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
35340b57cec5SDimitry Andric             break;
35350b57cec5SDimitry Andric           }
35360b57cec5SDimitry Andric         }
35370b57cec5SDimitry Andric       }
35380b57cec5SDimitry Andric     }
35390b57cec5SDimitry Andric   }
35400b57cec5SDimitry Andric 
35410b57cec5SDimitry Andric   // Make sure the result is of the requested type.
35420b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
35435ffd83dbSDimitry Andric     assert(F->getFunctionType() == Ty);
35440b57cec5SDimitry Andric     return F;
35450b57cec5SDimitry Andric   }
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
35480b57cec5SDimitry Andric   return llvm::ConstantExpr::getBitCast(F, PTy);
35490b57cec5SDimitry Andric }
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
35520b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
35530b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
35540b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
35550b57cec5SDimitry Andric                                                  llvm::Type *Ty,
35560b57cec5SDimitry Andric                                                  bool ForVTable,
35570b57cec5SDimitry Andric                                                  bool DontDefer,
35580b57cec5SDimitry Andric                                               ForDefinition_t IsForDefinition) {
35595ffd83dbSDimitry Andric   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
35605ffd83dbSDimitry Andric          "consteval function should never be emitted");
35610b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
35620b57cec5SDimitry Andric   if (!Ty) {
35630b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
35640b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
35650b57cec5SDimitry Andric   }
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
35680b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
35690b57cec5SDimitry Andric   // of the complete destructor when necessary.
35700b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
35710b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
35720b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
35730b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
35740b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
35750b57cec5SDimitry Andric   }
35760b57cec5SDimitry Andric 
35770b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
35780b57cec5SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
35790b57cec5SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
35800b57cec5SDimitry Andric                                  IsForDefinition);
35810b57cec5SDimitry Andric }
35820b57cec5SDimitry Andric 
35830b57cec5SDimitry Andric static const FunctionDecl *
35840b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
35850b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
35860b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
35890b57cec5SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
35900b57cec5SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
35910b57cec5SDimitry Andric       return FD;
35920b57cec5SDimitry Andric 
35930b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
35940b57cec5SDimitry Andric     return nullptr;
35950b57cec5SDimitry Andric 
35960b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
35970b57cec5SDimitry Andric   IdentifierInfo &CXXII =
35980b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
35990b57cec5SDimitry Andric           ? C.Idents.get("terminate")
36000b57cec5SDimitry Andric           : C.Idents.get(Name);
36010b57cec5SDimitry Andric 
36020b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
36030b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
36040b57cec5SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
36050b57cec5SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
36060b57cec5SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
36070b57cec5SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
36080b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
36090b57cec5SDimitry Andric             break;
36100b57cec5SDimitry Andric 
36110b57cec5SDimitry Andric       if (ND)
36120b57cec5SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
36130b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
36140b57cec5SDimitry Andric             return FD;
36150b57cec5SDimitry Andric     }
36160b57cec5SDimitry Andric   }
36170b57cec5SDimitry Andric 
36180b57cec5SDimitry Andric   return nullptr;
36190b57cec5SDimitry Andric }
36200b57cec5SDimitry Andric 
36210b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
36220b57cec5SDimitry Andric /// type and name.
36230b57cec5SDimitry Andric llvm::FunctionCallee
36240b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3625480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
3626480093f4SDimitry Andric                                      bool AssumeConvergent) {
3627480093f4SDimitry Andric   if (AssumeConvergent) {
3628480093f4SDimitry Andric     ExtraAttrs =
3629480093f4SDimitry Andric         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3630480093f4SDimitry Andric                                 llvm::Attribute::Convergent);
3631480093f4SDimitry Andric   }
3632480093f4SDimitry Andric 
36330b57cec5SDimitry Andric   llvm::Constant *C =
36340b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
36350b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
36360b57cec5SDimitry Andric                               ExtraAttrs);
36370b57cec5SDimitry Andric 
36380b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
36390b57cec5SDimitry Andric     if (F->empty()) {
36400b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
36410b57cec5SDimitry Andric 
36420b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
36430b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
36440b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
36450b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
36460b57cec5SDimitry Andric       // and warnings.
36470b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
36480b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
36490b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
36500b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
36510b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
36520b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
36530b57cec5SDimitry Andric         }
36540b57cec5SDimitry Andric       }
36550b57cec5SDimitry Andric       setDSOLocal(F);
36560b57cec5SDimitry Andric     }
36570b57cec5SDimitry Andric   }
36580b57cec5SDimitry Andric 
36590b57cec5SDimitry Andric   return {FTy, C};
36600b57cec5SDimitry Andric }
36610b57cec5SDimitry Andric 
36620b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
36630b57cec5SDimitry Andric /// as a constant.
36640b57cec5SDimitry Andric ///
36650b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
36660b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is
36670b57cec5SDimitry Andric /// not written to during its construction.
36680b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
36690b57cec5SDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
36700b57cec5SDimitry Andric     return false;
36710b57cec5SDimitry Andric 
36720b57cec5SDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
36730b57cec5SDimitry Andric     if (const CXXRecordDecl *Record
36740b57cec5SDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
36750b57cec5SDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
36760b57cec5SDimitry Andric              Record->hasTrivialDestructor();
36770b57cec5SDimitry Andric   }
36780b57cec5SDimitry Andric 
36790b57cec5SDimitry Andric   return true;
36800b57cec5SDimitry Andric }
36810b57cec5SDimitry Andric 
36820b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
36830b57cec5SDimitry Andric /// create and return an llvm GlobalVariable with the specified type.  If there
36840b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
36850b57cec5SDimitry Andric /// bitcasted to the right type.
36860b57cec5SDimitry Andric ///
36870b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
36880b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
36890b57cec5SDimitry Andric ///
36900b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
36910b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
36920b57cec5SDimitry Andric /// mangled name but some other type.
36930b57cec5SDimitry Andric llvm::Constant *
36940b57cec5SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
36950b57cec5SDimitry Andric                                      llvm::PointerType *Ty,
36960b57cec5SDimitry Andric                                      const VarDecl *D,
36970b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
36980b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
36990b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
37000b57cec5SDimitry Andric   if (Entry) {
37010b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
37020b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
37030b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
37040b57cec5SDimitry Andric     }
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric     // Handle dropped DLL attributes.
37070b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
37080b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
37110b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
37120b57cec5SDimitry Andric 
37130b57cec5SDimitry Andric     if (Entry->getType() == Ty)
37140b57cec5SDimitry Andric       return Entry;
37150b57cec5SDimitry Andric 
37160b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
37170b57cec5SDimitry Andric     // error.
37180b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
37190b57cec5SDimitry Andric       GlobalDecl OtherGD;
37200b57cec5SDimitry Andric       const VarDecl *OtherD;
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
37230b57cec5SDimitry Andric       // to make sure that we issue an error only once.
37240b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
37250b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
37260b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
37270b57cec5SDimitry Andric           OtherD->hasInit() &&
37280b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
37290b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
37300b57cec5SDimitry Andric             << MangledName;
37310b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
37320b57cec5SDimitry Andric                           diag::note_previous_definition);
37330b57cec5SDimitry Andric       }
37340b57cec5SDimitry Andric     }
37350b57cec5SDimitry Andric 
37360b57cec5SDimitry Andric     // Make sure the result is of the correct type.
37370b57cec5SDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
37380b57cec5SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
37410b57cec5SDimitry Andric     // global, not just return a bitcast.)
37420b57cec5SDimitry Andric     if (!IsForDefinition)
37430b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty);
37440b57cec5SDimitry Andric   }
37450b57cec5SDimitry Andric 
37460b57cec5SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
37470b57cec5SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
37480b57cec5SDimitry Andric 
37490b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
37500b57cec5SDimitry Andric       getModule(), Ty->getElementType(), false,
37510b57cec5SDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
37520b57cec5SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
37530b57cec5SDimitry Andric 
37540b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
37550b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
37560b57cec5SDimitry Andric   if (Entry) {
37570b57cec5SDimitry Andric     GV->takeName(Entry);
37580b57cec5SDimitry Andric 
37590b57cec5SDimitry Andric     if (!Entry->use_empty()) {
37600b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
37610b57cec5SDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
37620b57cec5SDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
37630b57cec5SDimitry Andric     }
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric     Entry->eraseFromParent();
37660b57cec5SDimitry Andric   }
37670b57cec5SDimitry Andric 
37680b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
37690b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
37700b57cec5SDimitry Andric   // of the file.
37710b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
37720b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
37730b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
37740b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
37750b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
37760b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
37770b57cec5SDimitry Andric   }
37780b57cec5SDimitry Andric 
37790b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
37800b57cec5SDimitry Andric   if (D) {
37810b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
37820b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
37830b57cec5SDimitry Andric 
37840b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
37850b57cec5SDimitry Andric     // handling.
37860b57cec5SDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
37870b57cec5SDimitry Andric 
3788a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
37890b57cec5SDimitry Andric 
37900b57cec5SDimitry Andric     setLinkageForGV(GV, D);
37910b57cec5SDimitry Andric 
37920b57cec5SDimitry Andric     if (D->getTLSKind()) {
37930b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
37940b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
37950b57cec5SDimitry Andric       setTLSMode(GV, *D);
37960b57cec5SDimitry Andric     }
37970b57cec5SDimitry Andric 
37980b57cec5SDimitry Andric     setGVProperties(GV, D);
37990b57cec5SDimitry Andric 
38000b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
38010b57cec5SDimitry Andric     // inline initializers as definitions.
38020b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
38030b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
38040b57cec5SDimitry Andric     }
38050b57cec5SDimitry Andric 
38060b57cec5SDimitry Andric     // Emit section information for extern variables.
38070b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
38080b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
38090b57cec5SDimitry Andric         GV->setSection(SA->getName());
38100b57cec5SDimitry Andric     }
38110b57cec5SDimitry Andric 
38120b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
38130b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
38140b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
38150b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
38160b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
38170b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
38180b57cec5SDimitry Andric 
38190b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
38200b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
38210b57cec5SDimitry Andric     // optimizer.
38220b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
38230b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
38240b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
38250b57cec5SDimitry Andric       const auto *Record =
38260b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
38270b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
38280b57cec5SDimitry Andric       if (!HasMutableFields) {
38290b57cec5SDimitry Andric         const VarDecl *InitDecl;
38300b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
38310b57cec5SDimitry Andric         if (InitExpr) {
38320b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
38330b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
38340b57cec5SDimitry Andric           if (Init) {
38350b57cec5SDimitry Andric             auto *InitType = Init->getType();
38365ffd83dbSDimitry Andric             if (GV->getValueType() != InitType) {
38370b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
38380b57cec5SDimitry Andric               // This happens when an initializer has a different type from
38390b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
38400b57cec5SDimitry Andric               // structure for instance).
38410b57cec5SDimitry Andric               GV->setName(StringRef());
38420b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
38430b57cec5SDimitry Andric               // to work.
38440b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
3845a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3846a7dea167SDimitry Andric                       ->stripPointerCasts());
38470b57cec5SDimitry Andric 
38480b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
38490b57cec5SDimitry Andric               GV->eraseFromParent();
38500b57cec5SDimitry Andric               GV = NewGV;
38510b57cec5SDimitry Andric             } else {
38520b57cec5SDimitry Andric               GV->setInitializer(Init);
38530b57cec5SDimitry Andric               GV->setConstant(true);
38540b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
38550b57cec5SDimitry Andric             }
38560b57cec5SDimitry Andric             emitter.finalize(GV);
38570b57cec5SDimitry Andric           }
38580b57cec5SDimitry Andric         }
38590b57cec5SDimitry Andric       }
38600b57cec5SDimitry Andric     }
38610b57cec5SDimitry Andric   }
38620b57cec5SDimitry Andric 
3863480093f4SDimitry Andric   if (GV->isDeclaration())
3864480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3865480093f4SDimitry Andric 
38660b57cec5SDimitry Andric   LangAS ExpectedAS =
38670b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
38680b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
38690b57cec5SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
38700b57cec5SDimitry Andric          Ty->getPointerAddressSpace());
38710b57cec5SDimitry Andric   if (AddrSpace != ExpectedAS)
38720b57cec5SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
38730b57cec5SDimitry Andric                                                        ExpectedAS, Ty);
38740b57cec5SDimitry Andric 
38750b57cec5SDimitry Andric   return GV;
38760b57cec5SDimitry Andric }
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric llvm::Constant *
38795ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
38800b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
38815ffd83dbSDimitry Andric 
38820b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
38830b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
38840b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
38855ffd83dbSDimitry Andric 
38865ffd83dbSDimitry Andric   if (isa<CXXMethodDecl>(D)) {
38875ffd83dbSDimitry Andric     auto FInfo =
38885ffd83dbSDimitry Andric         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
38890b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
38900b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
38910b57cec5SDimitry Andric                              IsForDefinition);
38925ffd83dbSDimitry Andric   }
38935ffd83dbSDimitry Andric 
38945ffd83dbSDimitry Andric   if (isa<FunctionDecl>(D)) {
38950b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
38960b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
38970b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
38980b57cec5SDimitry Andric                              IsForDefinition);
38995ffd83dbSDimitry Andric   }
39005ffd83dbSDimitry Andric 
39015ffd83dbSDimitry Andric   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
39020b57cec5SDimitry Andric }
39030b57cec5SDimitry Andric 
39040b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
39050b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
39060b57cec5SDimitry Andric     unsigned Alignment) {
39070b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
39080b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
39090b57cec5SDimitry Andric 
39100b57cec5SDimitry Andric   if (GV) {
39110b57cec5SDimitry Andric     // Check if the variable has the right type.
39125ffd83dbSDimitry Andric     if (GV->getValueType() == Ty)
39130b57cec5SDimitry Andric       return GV;
39140b57cec5SDimitry Andric 
39150b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
39160b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
39170b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
39180b57cec5SDimitry Andric     OldGV = GV;
39190b57cec5SDimitry Andric   }
39200b57cec5SDimitry Andric 
39210b57cec5SDimitry Andric   // Create a new variable.
39220b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
39230b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
39240b57cec5SDimitry Andric 
39250b57cec5SDimitry Andric   if (OldGV) {
39260b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
39270b57cec5SDimitry Andric     GV->takeName(OldGV);
39280b57cec5SDimitry Andric 
39290b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
39300b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
39310b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
39320b57cec5SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
39330b57cec5SDimitry Andric     }
39340b57cec5SDimitry Andric 
39350b57cec5SDimitry Andric     OldGV->eraseFromParent();
39360b57cec5SDimitry Andric   }
39370b57cec5SDimitry Andric 
39380b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
39390b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
39400b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
39410b57cec5SDimitry Andric 
3942a7dea167SDimitry Andric   GV->setAlignment(llvm::MaybeAlign(Alignment));
39430b57cec5SDimitry Andric 
39440b57cec5SDimitry Andric   return GV;
39450b57cec5SDimitry Andric }
39460b57cec5SDimitry Andric 
39470b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
39480b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
39490b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
39500b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
39510b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
39520b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
39530b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
39540b57cec5SDimitry Andric                                                   llvm::Type *Ty,
39550b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
39560b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
39570b57cec5SDimitry Andric   QualType ASTTy = D->getType();
39580b57cec5SDimitry Andric   if (!Ty)
39590b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   llvm::PointerType *PTy =
39620b57cec5SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
39630b57cec5SDimitry Andric 
39640b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
39650b57cec5SDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
39660b57cec5SDimitry Andric }
39670b57cec5SDimitry Andric 
39680b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
39690b57cec5SDimitry Andric /// specified type and name.
39700b57cec5SDimitry Andric llvm::Constant *
39710b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
39720b57cec5SDimitry Andric                                      StringRef Name) {
39730b57cec5SDimitry Andric   auto PtrTy =
39740b57cec5SDimitry Andric       getContext().getLangOpts().OpenCL
39750b57cec5SDimitry Andric           ? llvm::PointerType::get(
39760b57cec5SDimitry Andric                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
39770b57cec5SDimitry Andric           : llvm::PointerType::getUnqual(Ty);
39780b57cec5SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
39790b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
39800b57cec5SDimitry Andric   return Ret;
39810b57cec5SDimitry Andric }
39820b57cec5SDimitry Andric 
39830b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
39840b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
39850b57cec5SDimitry Andric 
39860b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
39870b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
39880b57cec5SDimitry Andric 
39890b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
39900b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
39910b57cec5SDimitry Andric   // definition).
39920b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
39930b57cec5SDimitry Andric     return;
39940b57cec5SDimitry Andric 
39950b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
39960b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
39970b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
39980b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
39990b57cec5SDimitry Andric       return;
40000b57cec5SDimitry Andric   }
40010b57cec5SDimitry Andric 
40020b57cec5SDimitry Andric   // The tentative definition is the only definition.
40030b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
40040b57cec5SDimitry Andric }
40050b57cec5SDimitry Andric 
4006480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4007480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
4008480093f4SDimitry Andric }
4009480093f4SDimitry Andric 
40100b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
40110b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
40120b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
40130b57cec5SDimitry Andric }
40140b57cec5SDimitry Andric 
40150b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
40160b57cec5SDimitry Andric   LangAS AddrSpace = LangAS::Default;
40170b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
40180b57cec5SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
40190b57cec5SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
4020e8d8bef9SDimitry Andric            AddrSpace == LangAS::opencl_global_device ||
4021e8d8bef9SDimitry Andric            AddrSpace == LangAS::opencl_global_host ||
40220b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
40230b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_local ||
40240b57cec5SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
40250b57cec5SDimitry Andric     return AddrSpace;
40260b57cec5SDimitry Andric   }
40270b57cec5SDimitry Andric 
40280b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
40290b57cec5SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
40300b57cec5SDimitry Andric       return LangAS::cuda_constant;
40310b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
40320b57cec5SDimitry Andric       return LangAS::cuda_shared;
40330b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDADeviceAttr>())
40340b57cec5SDimitry Andric       return LangAS::cuda_device;
40350b57cec5SDimitry Andric     else if (D && D->getType().isConstQualified())
40360b57cec5SDimitry Andric       return LangAS::cuda_constant;
40370b57cec5SDimitry Andric     else
40380b57cec5SDimitry Andric       return LangAS::cuda_device;
40390b57cec5SDimitry Andric   }
40400b57cec5SDimitry Andric 
40410b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
40420b57cec5SDimitry Andric     LangAS AS;
40430b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
40440b57cec5SDimitry Andric       return AS;
40450b57cec5SDimitry Andric   }
40460b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
40470b57cec5SDimitry Andric }
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric LangAS CodeGenModule::getStringLiteralAddressSpace() const {
40500b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
40510b57cec5SDimitry Andric   if (LangOpts.OpenCL)
40520b57cec5SDimitry Andric     return LangAS::opencl_constant;
40530b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
40540b57cec5SDimitry Andric     return AS.getValue();
40550b57cec5SDimitry Andric   return LangAS::Default;
40560b57cec5SDimitry Andric }
40570b57cec5SDimitry Andric 
40580b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
40590b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
40600b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
40610b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
40620b57cec5SDimitry Andric // need to be casted to default address space before being put into address
40630b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
40640b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
40650b57cec5SDimitry Andric // they should not be casted to default address space.
40660b57cec5SDimitry Andric static llvm::Constant *
40670b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
40680b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
40690b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
40700b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
40710b57cec5SDimitry Andric     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
40720b57cec5SDimitry Andric       if (AS != LangAS::Default)
40730b57cec5SDimitry Andric         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
40740b57cec5SDimitry Andric             CGM, GV, AS.getValue(), LangAS::Default,
40750b57cec5SDimitry Andric             GV->getValueType()->getPointerTo(
40760b57cec5SDimitry Andric                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
40770b57cec5SDimitry Andric     }
40780b57cec5SDimitry Andric   }
40790b57cec5SDimitry Andric   return Cast;
40800b57cec5SDimitry Andric }
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric template<typename SomeDecl>
40830b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
40840b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
40850b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
40860b57cec5SDimitry Andric     return;
40870b57cec5SDimitry Andric 
40880b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
40890b57cec5SDimitry Andric   // the name existing.
40900b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
40910b57cec5SDimitry Andric     return;
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
40940b57cec5SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
40950b57cec5SDimitry Andric     return;
40960b57cec5SDimitry Andric 
40970b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
40980b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
40990b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
41000b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
41010b57cec5SDimitry Andric     return;
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
41040b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
41050b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
41060b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
41070b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
41080b57cec5SDimitry Andric 
41090b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
41100b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
41110b57cec5SDimitry Andric   if (!R.second)
41120b57cec5SDimitry Andric     R.first->second = nullptr;
41130b57cec5SDimitry Andric }
41140b57cec5SDimitry Andric 
41150b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
41160b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
41170b57cec5SDimitry Andric     return false;
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
41200b57cec5SDimitry Andric   // them being "merged" by the COMDAT Folding linker optimization.
41210b57cec5SDimitry Andric   if (D.hasAttr<CUDAGlobalAttr>())
41220b57cec5SDimitry Andric     return false;
41230b57cec5SDimitry Andric 
41240b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
41250b57cec5SDimitry Andric     return true;
41260b57cec5SDimitry Andric 
41270b57cec5SDimitry Andric   GVALinkage Linkage;
41280b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
41290b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
41300b57cec5SDimitry Andric   else
41310b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
41320b57cec5SDimitry Andric 
41330b57cec5SDimitry Andric   switch (Linkage) {
41340b57cec5SDimitry Andric   case GVA_Internal:
41350b57cec5SDimitry Andric   case GVA_AvailableExternally:
41360b57cec5SDimitry Andric   case GVA_StrongExternal:
41370b57cec5SDimitry Andric     return false;
41380b57cec5SDimitry Andric   case GVA_DiscardableODR:
41390b57cec5SDimitry Andric   case GVA_StrongODR:
41400b57cec5SDimitry Andric     return true;
41410b57cec5SDimitry Andric   }
41420b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
41430b57cec5SDimitry Andric }
41440b57cec5SDimitry Andric 
41450b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
41460b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
41470b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
41480b57cec5SDimitry Andric     return;
41490b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
41500b57cec5SDimitry Andric }
41510b57cec5SDimitry Andric 
41520b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
41530b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
41540b57cec5SDimitry Andric                                             bool IsTentative) {
41550b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
41560b57cec5SDimitry Andric   // therefore no need to be translated.
41570b57cec5SDimitry Andric   QualType ASTTy = D->getType();
41580b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
41590b57cec5SDimitry Andric     return;
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
41620b57cec5SDimitry Andric   // normally.
41630b57cec5SDimitry Andric   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
41640b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
41650b57cec5SDimitry Andric     return;
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric   llvm::Constant *Init = nullptr;
41680b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
4169a7dea167SDimitry Andric   bool NeedsGlobalDtor =
4170a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
41710b57cec5SDimitry Andric 
41720b57cec5SDimitry Andric   const VarDecl *InitDecl;
41730b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
41760b57cec5SDimitry Andric 
41770b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
41780b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
41790b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
41800b57cec5SDimitry Andric   bool IsCUDASharedVar =
41810b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
41820b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
41830b57cec5SDimitry Andric   // undefined.
41840b57cec5SDimitry Andric   bool IsCUDAShadowVar =
4185e8d8bef9SDimitry Andric       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
41860b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
41870b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
41885ffd83dbSDimitry Andric   bool IsCUDADeviceShadowVar =
41895ffd83dbSDimitry Andric       getLangOpts().CUDAIsDevice &&
41905ffd83dbSDimitry Andric       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4191e8d8bef9SDimitry Andric        D->getType()->isCUDADeviceBuiltinTextureType() ||
4192e8d8bef9SDimitry Andric        D->hasAttr<HIPManagedAttr>());
41930b57cec5SDimitry Andric   // HIP pinned shadow of initialized host-side global variables are also
41940b57cec5SDimitry Andric   // left undefined.
41950b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
41965ffd83dbSDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
41975ffd83dbSDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
41985ffd83dbSDimitry Andric   else if (D->hasAttr<LoaderUninitializedAttr>())
41990b57cec5SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
42000b57cec5SDimitry Andric   else if (!InitExpr) {
42010b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
42020b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
42030b57cec5SDimitry Andric     //
42040b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
42050b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
42060b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
42070b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
42080b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
42090b57cec5SDimitry Andric     // to do a RAUW.
42100b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
42110b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
42120b57cec5SDimitry Andric   } else {
42130b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
42140b57cec5SDimitry Andric     emitter.emplace(*this);
42150b57cec5SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
42160b57cec5SDimitry Andric 
42170b57cec5SDimitry Andric     if (!Init) {
42180b57cec5SDimitry Andric       QualType T = InitExpr->getType();
42190b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
42200b57cec5SDimitry Andric         T = D->getType();
42210b57cec5SDimitry Andric 
42220b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
42230b57cec5SDimitry Andric         Init = EmitNullConstant(T);
42240b57cec5SDimitry Andric         NeedsGlobalCtor = true;
42250b57cec5SDimitry Andric       } else {
42260b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
42270b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
42280b57cec5SDimitry Andric       }
42290b57cec5SDimitry Andric     } else {
42300b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
42310b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
42320b57cec5SDimitry Andric       // also don't need to register a destructor.
42330b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
42340b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
42350b57cec5SDimitry Andric     }
42360b57cec5SDimitry Andric   }
42370b57cec5SDimitry Andric 
42380b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
42390b57cec5SDimitry Andric   llvm::Constant *Entry =
42400b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
42410b57cec5SDimitry Andric 
4242a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
4243a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
42440b57cec5SDimitry Andric 
42450b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
42460b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
42470b57cec5SDimitry Andric 
42480b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
42490b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
42500b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
42510b57cec5SDimitry Andric   // (which will be a definition).
42520b57cec5SDimitry Andric   //
42530b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
42540b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
42550b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
42560b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
42575ffd83dbSDimitry Andric   if (!GV || GV->getValueType() != InitType ||
42580b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
42590b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
42600b57cec5SDimitry Andric 
42610b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
42620b57cec5SDimitry Andric     Entry->setName(StringRef());
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
42650b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
4266a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4267a7dea167SDimitry Andric             ->stripPointerCasts());
42680b57cec5SDimitry Andric 
42690b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
42700b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
42710b57cec5SDimitry Andric         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
42720b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
42730b57cec5SDimitry Andric 
42740b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
42750b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
42760b57cec5SDimitry Andric   }
42770b57cec5SDimitry Andric 
42780b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
42790b57cec5SDimitry Andric 
42800b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
42810b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
42820b57cec5SDimitry Andric 
42830b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
42840b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
42850b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
42860b57cec5SDimitry Andric 
42870b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
42880b57cec5SDimitry Andric   // the device. [...]"
42890b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
42900b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
42910b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
42920b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
42930b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
42940b57cec5SDimitry Andric   if (GV && LangOpts.CUDA) {
42950b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
42960b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
42970b57cec5SDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
42980b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
42990b57cec5SDimitry Andric     } else {
43000b57cec5SDimitry Andric       // Host-side shadows of external declarations of device-side
43010b57cec5SDimitry Andric       // global variables become internal definitions. These have to
43020b57cec5SDimitry Andric       // be internal in order to prevent name conflicts with global
43030b57cec5SDimitry Andric       // host variables with the same name in a different TUs.
43045ffd83dbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
43050b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
43065ffd83dbSDimitry Andric         // Shadow variables and their properties must be registered with CUDA
43075ffd83dbSDimitry Andric         // runtime. Skip Extern global variables, which will be registered in
43085ffd83dbSDimitry Andric         // the TU where they are defined.
4309e8d8bef9SDimitry Andric         //
4310e8d8bef9SDimitry Andric         // Don't register a C++17 inline variable. The local symbol can be
4311e8d8bef9SDimitry Andric         // discarded and referencing a discarded local symbol from outside the
4312e8d8bef9SDimitry Andric         // comdat (__cuda_register_globals) is disallowed by the ELF spec.
4313e8d8bef9SDimitry Andric         // TODO: Reject __device__ constexpr and __device__ inline in Sema.
4314e8d8bef9SDimitry Andric         if (!D->hasExternalStorage() && !D->isInline())
43155ffd83dbSDimitry Andric           getCUDARuntime().registerDeviceVar(D, *GV, !D->hasDefinition(),
43165ffd83dbSDimitry Andric                                              D->hasAttr<CUDAConstantAttr>());
43175ffd83dbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>()) {
43180b57cec5SDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
43190b57cec5SDimitry Andric         // they are not registered with the CUDA runtime, so they
43200b57cec5SDimitry Andric         // can't really be used to access their device-side
43210b57cec5SDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
43220b57cec5SDimitry Andric         // a feature, but we've got to do the same for compatibility.
43230b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
43245ffd83dbSDimitry Andric       } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
43255ffd83dbSDimitry Andric                  D->getType()->isCUDADeviceBuiltinTextureType()) {
43265ffd83dbSDimitry Andric         // Builtin surfaces and textures and their template arguments are
43275ffd83dbSDimitry Andric         // also registered with CUDA runtime.
43285ffd83dbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
43295ffd83dbSDimitry Andric         const ClassTemplateSpecializationDecl *TD =
43305ffd83dbSDimitry Andric             cast<ClassTemplateSpecializationDecl>(
43315ffd83dbSDimitry Andric                 D->getType()->getAs<RecordType>()->getDecl());
43325ffd83dbSDimitry Andric         const TemplateArgumentList &Args = TD->getTemplateArgs();
43335ffd83dbSDimitry Andric         if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
43345ffd83dbSDimitry Andric           assert(Args.size() == 2 &&
43355ffd83dbSDimitry Andric                  "Unexpected number of template arguments of CUDA device "
43365ffd83dbSDimitry Andric                  "builtin surface type.");
43375ffd83dbSDimitry Andric           auto SurfType = Args[1].getAsIntegral();
43385ffd83dbSDimitry Andric           if (!D->hasExternalStorage())
43395ffd83dbSDimitry Andric             getCUDARuntime().registerDeviceSurf(D, *GV, !D->hasDefinition(),
43405ffd83dbSDimitry Andric                                                 SurfType.getSExtValue());
43415ffd83dbSDimitry Andric         } else {
43425ffd83dbSDimitry Andric           assert(Args.size() == 3 &&
43435ffd83dbSDimitry Andric                  "Unexpected number of template arguments of CUDA device "
43445ffd83dbSDimitry Andric                  "builtin texture type.");
43455ffd83dbSDimitry Andric           auto TexType = Args[1].getAsIntegral();
43465ffd83dbSDimitry Andric           auto Normalized = Args[2].getAsIntegral();
43475ffd83dbSDimitry Andric           if (!D->hasExternalStorage())
43485ffd83dbSDimitry Andric             getCUDARuntime().registerDeviceTex(D, *GV, !D->hasDefinition(),
43495ffd83dbSDimitry Andric                                                TexType.getSExtValue(),
43505ffd83dbSDimitry Andric                                                Normalized.getZExtValue());
43515ffd83dbSDimitry Andric         }
43525ffd83dbSDimitry Andric       }
43530b57cec5SDimitry Andric     }
43540b57cec5SDimitry Andric   }
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric   GV->setInitializer(Init);
43575ffd83dbSDimitry Andric   if (emitter)
43585ffd83dbSDimitry Andric     emitter->finalize(GV);
43590b57cec5SDimitry Andric 
43600b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
43610b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
43620b57cec5SDimitry Andric                   isTypeConstant(D->getType(), true));
43630b57cec5SDimitry Andric 
43640b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
43650b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
43660b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
43670b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
43680b57cec5SDimitry Andric       GV->setConstant(true);
43690b57cec5SDimitry Andric   }
43700b57cec5SDimitry Andric 
4371a7dea167SDimitry Andric   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
43720b57cec5SDimitry Andric 
43735ffd83dbSDimitry Andric   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
43745ffd83dbSDimitry Andric   // function is only defined alongside the variable, not also alongside
43755ffd83dbSDimitry Andric   // callers. Normally, all accesses to a thread_local go through the
43765ffd83dbSDimitry Andric   // thread-wrapper in order to ensure initialization has occurred, underlying
43775ffd83dbSDimitry Andric   // variable will never be used other than the thread-wrapper, so it can be
43785ffd83dbSDimitry Andric   // converted to internal linkage.
43795ffd83dbSDimitry Andric   //
43805ffd83dbSDimitry Andric   // However, if the variable has the 'constinit' attribute, it _can_ be
43815ffd83dbSDimitry Andric   // referenced directly, without calling the thread-wrapper, so the linkage
43825ffd83dbSDimitry Andric   // must not be changed.
43835ffd83dbSDimitry Andric   //
43845ffd83dbSDimitry Andric   // Additionally, if the variable isn't plain external linkage, e.g. if it's
43855ffd83dbSDimitry Andric   // weak or linkonce, the de-duplication semantics are important to preserve,
43865ffd83dbSDimitry Andric   // so we don't change the linkage.
43875ffd83dbSDimitry Andric   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
43885ffd83dbSDimitry Andric       Linkage == llvm::GlobalValue::ExternalLinkage &&
43890b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
43905ffd83dbSDimitry Andric       !D->hasAttr<ConstInitAttr>())
43910b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
43920b57cec5SDimitry Andric 
43930b57cec5SDimitry Andric   GV->setLinkage(Linkage);
43940b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
43950b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
43960b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
43970b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
43980b57cec5SDimitry Andric   else
43990b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
44020b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
44030b57cec5SDimitry Andric     GV->setConstant(false);
44040b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
44050b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
44060b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
44070b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
44080b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
44090b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
44100b57cec5SDimitry Andric   }
44110b57cec5SDimitry Andric 
44120b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
44130b57cec5SDimitry Andric 
44140b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
44150b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
44160b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
44170b57cec5SDimitry Andric     setTLSMode(GV, *D);
44180b57cec5SDimitry Andric   }
44190b57cec5SDimitry Andric 
44200b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
44210b57cec5SDimitry Andric 
44220b57cec5SDimitry Andric   // Emit the initializer function if necessary.
44230b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
44240b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
44270b57cec5SDimitry Andric 
44280b57cec5SDimitry Andric   // Emit global variable debug information.
44290b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4430480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
44310b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
44320b57cec5SDimitry Andric }
44330b57cec5SDimitry Andric 
4434480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4435480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4436480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
4437480093f4SDimitry Andric       QualType ASTTy = D->getType();
4438480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4439480093f4SDimitry Andric       llvm::PointerType *PTy =
4440480093f4SDimitry Andric           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4441480093f4SDimitry Andric       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4442480093f4SDimitry Andric       DI->EmitExternalVariable(
4443480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4444480093f4SDimitry Andric     }
4445480093f4SDimitry Andric }
4446480093f4SDimitry Andric 
44470b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
44480b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
44490b57cec5SDimitry Andric                                       bool NoCommon) {
44500b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
44510b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
44520b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
44530b57cec5SDimitry Andric     return true;
44540b57cec5SDimitry Andric 
44550b57cec5SDimitry Andric   // C11 6.9.2/2:
44560b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
44570b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
44580b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
44590b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
44600b57cec5SDimitry Andric     return true;
44610b57cec5SDimitry Andric 
44620b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
44630b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
44640b57cec5SDimitry Andric     return true;
44650b57cec5SDimitry Andric 
44660b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
44670b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
44680b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
44690b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
44700b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
4471a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
44720b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
44730b57cec5SDimitry Andric     return true;
44740b57cec5SDimitry Andric 
44750b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
44760b57cec5SDimitry Andric   if (D->getTLSKind())
44770b57cec5SDimitry Andric     return true;
44780b57cec5SDimitry Andric 
44790b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
44800b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
44810b57cec5SDimitry Andric     return true;
44820b57cec5SDimitry Andric 
44830b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
44840b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
44850b57cec5SDimitry Andric     return true;
44860b57cec5SDimitry Andric 
44870b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
44880b57cec5SDimitry Andric   // mode.
44890b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
44900b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
44910b57cec5SDimitry Andric       return true;
44920b57cec5SDimitry Andric     QualType VarType = D->getType();
44930b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
44940b57cec5SDimitry Andric       return true;
44950b57cec5SDimitry Andric 
44960b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
44970b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
44980b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
44990b57cec5SDimitry Andric         if (FD->isBitField())
45000b57cec5SDimitry Andric           continue;
45010b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
45020b57cec5SDimitry Andric           return true;
45030b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
45040b57cec5SDimitry Andric           return true;
45050b57cec5SDimitry Andric       }
45060b57cec5SDimitry Andric     }
45070b57cec5SDimitry Andric   }
45080b57cec5SDimitry Andric 
45090b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
45100b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
45110b57cec5SDimitry Andric   // common.
45120b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
45130b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
45140b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
45150b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
45160b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
45170b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
45180b57cec5SDimitry Andric     return true;
45190b57cec5SDimitry Andric 
45200b57cec5SDimitry Andric   return false;
45210b57cec5SDimitry Andric }
45220b57cec5SDimitry Andric 
45230b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
45240b57cec5SDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
45250b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
45260b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
45270b57cec5SDimitry Andric 
45280b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>()) {
45290b57cec5SDimitry Andric     if (IsConstantVariable)
45300b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
45310b57cec5SDimitry Andric     else
45320b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
45330b57cec5SDimitry Andric   }
45340b57cec5SDimitry Andric 
45350b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
45360b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
45370b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
45380b57cec5SDimitry Andric 
45390b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
45400b57cec5SDimitry Andric   // so we can use available_externally linkage.
45410b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
45420b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
45430b57cec5SDimitry Andric 
45440b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
45450b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
45460b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
45470b57cec5SDimitry Andric   // instantiations we'll map to external.
45480b57cec5SDimitry Andric 
45490b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
45500b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
45510b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
45520b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
45530b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
45540b57cec5SDimitry Andric   // definition is dependable.
45550b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
45560b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
45570b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
45580b57cec5SDimitry Andric 
45590b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
45600b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
45610b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
45620b57cec5SDimitry Andric   // throw away these explicit instantiations.
45630b57cec5SDimitry Andric   //
4564e8d8bef9SDimitry Andric   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
45650b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
4566e8d8bef9SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations. For
4567e8d8bef9SDimitry Andric   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4568e8d8bef9SDimitry Andric   // therefore we need to follow the normal linkage paradigm.
45690b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
4570e8d8bef9SDimitry Andric     if (getLangOpts().AppleKext)
45710b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
4572e8d8bef9SDimitry Andric     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4573e8d8bef9SDimitry Andric         !getLangOpts().GPURelocatableDeviceCode)
45740b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
45750b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
45760b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
45770b57cec5SDimitry Andric   }
45780b57cec5SDimitry Andric 
45790b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
45800b57cec5SDimitry Andric   // linkage.
45810b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
45820b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
45830b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
45840b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
45850b57cec5SDimitry Andric 
45860b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
45870b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
45880b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
45890b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
45900b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
45910b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
45920b57cec5SDimitry Andric 
45930b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
45940b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
45950b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
45960b57cec5SDimitry Andric }
45970b57cec5SDimitry Andric 
45980b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
45990b57cec5SDimitry Andric     const VarDecl *VD, bool IsConstant) {
46000b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
46010b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
46020b57cec5SDimitry Andric }
46030b57cec5SDimitry Andric 
46040b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
46050b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
46060b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
46070b57cec5SDimitry Andric                                           llvm::Function *newFn) {
46080b57cec5SDimitry Andric   // Fast path.
46090b57cec5SDimitry Andric   if (old->use_empty()) return;
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
46120b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
46130b57cec5SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
46140b57cec5SDimitry Andric 
46150b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
46160b57cec5SDimitry Andric          ui != ue; ) {
46170b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
46180b57cec5SDimitry Andric     llvm::User *user = use->getUser();
46190b57cec5SDimitry Andric 
46200b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
46210b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
46220b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
46230b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
46240b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
46250b57cec5SDimitry Andric       continue;
46260b57cec5SDimitry Andric     }
46270b57cec5SDimitry Andric 
46280b57cec5SDimitry Andric     // Recognize calls to the function.
46290b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
46300b57cec5SDimitry Andric     if (!callSite) continue;
46310b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
46320b57cec5SDimitry Andric       continue;
46330b57cec5SDimitry Andric 
46340b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
46350b57cec5SDimitry Andric     // transform this call unless it's dead.
46360b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
46370b57cec5SDimitry Andric       continue;
46380b57cec5SDimitry Andric 
46390b57cec5SDimitry Andric     // Get the call site's attribute list.
46400b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
46410b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
46440b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
46450b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
46460b57cec5SDimitry Andric       continue;
46470b57cec5SDimitry Andric 
46480b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
46490b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
46500b57cec5SDimitry Andric     unsigned argNo = 0;
46510b57cec5SDimitry Andric     bool dontTransform = false;
46520b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
46530b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
46540b57cec5SDimitry Andric         dontTransform = true;
46550b57cec5SDimitry Andric         break;
46560b57cec5SDimitry Andric       }
46570b57cec5SDimitry Andric 
46580b57cec5SDimitry Andric       // Add any parameter attributes.
46590b57cec5SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
46600b57cec5SDimitry Andric       argNo++;
46610b57cec5SDimitry Andric     }
46620b57cec5SDimitry Andric     if (dontTransform)
46630b57cec5SDimitry Andric       continue;
46640b57cec5SDimitry Andric 
46650b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
46660b57cec5SDimitry Andric     // over the required information.
46670b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
46680b57cec5SDimitry Andric 
46690b57cec5SDimitry Andric     // Copy over any operand bundles.
46700b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
46710b57cec5SDimitry Andric 
46720b57cec5SDimitry Andric     llvm::CallBase *newCall;
46730b57cec5SDimitry Andric     if (dyn_cast<llvm::CallInst>(callSite)) {
46740b57cec5SDimitry Andric       newCall =
46750b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
46760b57cec5SDimitry Andric     } else {
46770b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
46780b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
46790b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
46800b57cec5SDimitry Andric                                          newBundles, "", callSite);
46810b57cec5SDimitry Andric     }
46820b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
46830b57cec5SDimitry Andric 
46840b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
46850b57cec5SDimitry Andric       newCall->takeName(callSite);
46860b57cec5SDimitry Andric     newCall->setAttributes(llvm::AttributeList::get(
46870b57cec5SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
46880b57cec5SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
46890b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
46920b57cec5SDimitry Andric     if (!callSite->use_empty())
46930b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
46940b57cec5SDimitry Andric 
46950b57cec5SDimitry Andric     // Copy debug location attached to CI.
46960b57cec5SDimitry Andric     if (callSite->getDebugLoc())
46970b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
46980b57cec5SDimitry Andric 
46990b57cec5SDimitry Andric     callSite->eraseFromParent();
47000b57cec5SDimitry Andric   }
47010b57cec5SDimitry Andric }
47020b57cec5SDimitry Andric 
47030b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
47040b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
47050b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
47060b57cec5SDimitry Andric /// call the new function directly.
47070b57cec5SDimitry Andric ///
47080b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
47090b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
47100b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
47110b57cec5SDimitry Andric /// run at -O0.
47120b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
47130b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
47140b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
47150b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
47160b57cec5SDimitry Andric 
47170b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
47180b57cec5SDimitry Andric }
47190b57cec5SDimitry Andric 
47200b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
47210b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
47220b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
47230b57cec5SDimitry Andric     return;
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
47260b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
47270b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
47280b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
47290b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
47320b57cec5SDimitry Andric }
47330b57cec5SDimitry Andric 
47340b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
47350b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
47360b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric   // Compute the function info and LLVM type.
47390b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
47400b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
47410b57cec5SDimitry Andric 
47420b57cec5SDimitry Andric   // Get or create the prototype for the function.
47435ffd83dbSDimitry Andric   if (!GV || (GV->getValueType() != Ty))
47440b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
47450b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
47460b57cec5SDimitry Andric                                                    ForDefinition));
47470b57cec5SDimitry Andric 
47480b57cec5SDimitry Andric   // Already emitted.
47490b57cec5SDimitry Andric   if (!GV->isDeclaration())
47500b57cec5SDimitry Andric     return;
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
47530b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
47540b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
47550b57cec5SDimitry Andric   // declarations).
47560b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
47570b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
47580b57cec5SDimitry Andric 
47590b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
47600b57cec5SDimitry Andric   setGVProperties(Fn, GD);
47610b57cec5SDimitry Andric 
47620b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
47650b57cec5SDimitry Andric 
4766e8d8bef9SDimitry Andric   // Set CodeGen attributes that represent floating point environment.
4767e8d8bef9SDimitry Andric   setLLVMFunctionFEnvAttributes(D, Fn);
4768e8d8bef9SDimitry Andric 
47695ffd83dbSDimitry Andric   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
47700b57cec5SDimitry Andric 
47710b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
47720b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
47730b57cec5SDimitry Andric 
47740b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
47750b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
47760b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4777e8d8bef9SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority(), true);
47780b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
47790b57cec5SDimitry Andric     AddGlobalAnnotations(D, Fn);
47800b57cec5SDimitry Andric }
47810b57cec5SDimitry Andric 
47820b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
47830b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
47840b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
47850b57cec5SDimitry Andric   assert(AA && "Not an alias?");
47860b57cec5SDimitry Andric 
47870b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
47880b57cec5SDimitry Andric 
47890b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
47900b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
47910b57cec5SDimitry Andric     return;
47920b57cec5SDimitry Andric   }
47930b57cec5SDimitry Andric 
47940b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
47950b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
47960b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
47970b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
47980b57cec5SDimitry Andric     return;
47990b57cec5SDimitry Andric 
48000b57cec5SDimitry Andric   Aliases.push_back(GD);
48010b57cec5SDimitry Andric 
48020b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
48030b57cec5SDimitry Andric 
48040b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
48050b57cec5SDimitry Andric   // if a deferred decl.
48060b57cec5SDimitry Andric   llvm::Constant *Aliasee;
48070b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
48080b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
48090b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
48100b57cec5SDimitry Andric                                       /*ForVTable=*/false);
48110b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
48120b57cec5SDimitry Andric   } else {
48130b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
48140b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
48150b57cec5SDimitry Andric                                     /*D=*/nullptr);
4816e8d8bef9SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4817e8d8bef9SDimitry Andric       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4818e8d8bef9SDimitry Andric     else
4819e8d8bef9SDimitry Andric       LT = getFunctionLinkage(GD);
48200b57cec5SDimitry Andric   }
48210b57cec5SDimitry Andric 
48220b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
48235ffd83dbSDimitry Andric   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
48240b57cec5SDimitry Andric   auto *GA =
48255ffd83dbSDimitry Andric       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
48260b57cec5SDimitry Andric 
48270b57cec5SDimitry Andric   if (Entry) {
48280b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
48290b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
48300b57cec5SDimitry Andric       return;
48310b57cec5SDimitry Andric     }
48320b57cec5SDimitry Andric 
48330b57cec5SDimitry Andric     assert(Entry->isDeclaration());
48340b57cec5SDimitry Andric 
48350b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
48360b57cec5SDimitry Andric     // by the alias, as in:
48370b57cec5SDimitry Andric     //   extern int test6();
48380b57cec5SDimitry Andric     //   ...
48390b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
48400b57cec5SDimitry Andric     //
48410b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
48420b57cec5SDimitry Andric     GA->takeName(Entry);
48430b57cec5SDimitry Andric 
48440b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
48450b57cec5SDimitry Andric                                                           Entry->getType()));
48460b57cec5SDimitry Andric     Entry->eraseFromParent();
48470b57cec5SDimitry Andric   } else {
48480b57cec5SDimitry Andric     GA->setName(MangledName);
48490b57cec5SDimitry Andric   }
48500b57cec5SDimitry Andric 
48510b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
48520b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
48530b57cec5SDimitry Andric   // variable/function.
48540b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
48550b57cec5SDimitry Andric       D->isWeakImported()) {
48560b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
48570b57cec5SDimitry Andric   }
48580b57cec5SDimitry Andric 
48590b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
48600b57cec5SDimitry Andric     if (VD->getTLSKind())
48610b57cec5SDimitry Andric       setTLSMode(GA, *VD);
48620b57cec5SDimitry Andric 
48630b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
48640b57cec5SDimitry Andric }
48650b57cec5SDimitry Andric 
48660b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
48670b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
48680b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
48690b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
48700b57cec5SDimitry Andric 
48710b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
48720b57cec5SDimitry Andric 
48730b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
48740b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
48750b57cec5SDimitry Andric     return;
48760b57cec5SDimitry Andric   }
48770b57cec5SDimitry Andric 
48780b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
48790b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
48800b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
48810b57cec5SDimitry Andric     GlobalDecl OtherGD;
48820b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
48830b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
48840b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
48850b57cec5SDimitry Andric           << MangledName;
48860b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
48870b57cec5SDimitry Andric                    diag::note_previous_definition);
48880b57cec5SDimitry Andric     }
48890b57cec5SDimitry Andric     return;
48900b57cec5SDimitry Andric   }
48910b57cec5SDimitry Andric 
48920b57cec5SDimitry Andric   Aliases.push_back(GD);
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
48950b57cec5SDimitry Andric   llvm::Constant *Resolver =
48960b57cec5SDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
48970b57cec5SDimitry Andric                               /*ForVTable=*/false);
48980b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
48990b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
49000b57cec5SDimitry Andric                                 "", Resolver, &getModule());
49010b57cec5SDimitry Andric   if (Entry) {
49020b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
49030b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
49040b57cec5SDimitry Andric       return;
49050b57cec5SDimitry Andric     }
49060b57cec5SDimitry Andric     assert(Entry->isDeclaration());
49070b57cec5SDimitry Andric 
49080b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
49090b57cec5SDimitry Andric     // by the ifunc, as in:
49100b57cec5SDimitry Andric     //   extern int test();
49110b57cec5SDimitry Andric     //   ...
49120b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
49130b57cec5SDimitry Andric     //
49140b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
49150b57cec5SDimitry Andric     GIF->takeName(Entry);
49160b57cec5SDimitry Andric 
49170b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
49180b57cec5SDimitry Andric                                                           Entry->getType()));
49190b57cec5SDimitry Andric     Entry->eraseFromParent();
49200b57cec5SDimitry Andric   } else
49210b57cec5SDimitry Andric     GIF->setName(MangledName);
49220b57cec5SDimitry Andric 
49230b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
49240b57cec5SDimitry Andric }
49250b57cec5SDimitry Andric 
49260b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
49270b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
49280b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
49290b57cec5SDimitry Andric                                          Tys);
49300b57cec5SDimitry Andric }
49310b57cec5SDimitry Andric 
49320b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
49330b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
49340b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
49350b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
49360b57cec5SDimitry Andric   StringRef String = Literal->getString();
49370b57cec5SDimitry Andric   unsigned NumBytes = String.size();
49380b57cec5SDimitry Andric 
49390b57cec5SDimitry Andric   // Check for simple case.
49400b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
49410b57cec5SDimitry Andric     StringLength = NumBytes;
49420b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
49430b57cec5SDimitry Andric   }
49440b57cec5SDimitry Andric 
49450b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
49460b57cec5SDimitry Andric   IsUTF16 = true;
49470b57cec5SDimitry Andric 
49480b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
49490b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
49500b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
49510b57cec5SDimitry Andric 
49520b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
49530b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
49540b57cec5SDimitry Andric 
49550b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
49560b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
49570b57cec5SDimitry Andric 
49580b57cec5SDimitry Andric   // Add an explicit null.
49590b57cec5SDimitry Andric   *ToPtr = 0;
49600b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
49610b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
49620b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
49630b57cec5SDimitry Andric                          nullptr)).first;
49640b57cec5SDimitry Andric }
49650b57cec5SDimitry Andric 
49660b57cec5SDimitry Andric ConstantAddress
49670b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
49680b57cec5SDimitry Andric   unsigned StringLength = 0;
49690b57cec5SDimitry Andric   bool isUTF16 = false;
49700b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
49710b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
49720b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
49730b57cec5SDimitry Andric                                StringLength);
49740b57cec5SDimitry Andric 
49750b57cec5SDimitry Andric   if (auto *C = Entry.second)
49760b57cec5SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
49790b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
49800b57cec5SDimitry Andric 
49810b57cec5SDimitry Andric   const ASTContext &Context = getContext();
49820b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
49830b57cec5SDimitry Andric 
49840b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
49850b57cec5SDimitry Andric   const bool IsSwiftABI =
49860b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
49870b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
49880b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
49890b57cec5SDimitry Andric 
49900b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
49910b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
49920b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
49930b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
49940b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric     switch (CFRuntime) {
49970b57cec5SDimitry Andric     default: break;
49980b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
49990b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
50000b57cec5SDimitry Andric       CFConstantStringClassName =
50010b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
50020b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
50030b57cec5SDimitry Andric       Ty = IntPtrTy;
50040b57cec5SDimitry Andric       break;
50050b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
50060b57cec5SDimitry Andric       CFConstantStringClassName =
50070b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
50080b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
50090b57cec5SDimitry Andric       Ty = IntPtrTy;
50100b57cec5SDimitry Andric       break;
50110b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
50120b57cec5SDimitry Andric       CFConstantStringClassName =
50130b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
50140b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
50150b57cec5SDimitry Andric       Ty = IntPtrTy;
50160b57cec5SDimitry Andric       break;
50170b57cec5SDimitry Andric     }
50180b57cec5SDimitry Andric 
50190b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
50200b57cec5SDimitry Andric 
50210b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
50220b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
50230b57cec5SDimitry Andric 
50240b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
50250b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
50260b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
50270b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
50280b57cec5SDimitry Andric 
50290b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
50300b57cec5SDimitry Andric         for (const auto &Result : DC->lookup(&II))
50310b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
50320b57cec5SDimitry Andric             break;
50330b57cec5SDimitry Andric 
50340b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
50350b57cec5SDimitry Andric           if (!VD)
50360b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
50370b57cec5SDimitry Andric         } else {
50380b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
50390b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
50400b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
50410b57cec5SDimitry Andric           else
50420b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
50430b57cec5SDimitry Andric         }
50440b57cec5SDimitry Andric 
50450b57cec5SDimitry Andric         setDSOLocal(GV);
50460b57cec5SDimitry Andric       }
50470b57cec5SDimitry Andric     }
50480b57cec5SDimitry Andric 
50490b57cec5SDimitry Andric     // Decay array -> ptr
50500b57cec5SDimitry Andric     CFConstantStringClassRef =
50510b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
50520b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
50530b57cec5SDimitry Andric   }
50540b57cec5SDimitry Andric 
50550b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
50560b57cec5SDimitry Andric 
50570b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
50580b57cec5SDimitry Andric 
50590b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
50600b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric   // Class pointer.
50630b57cec5SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
50640b57cec5SDimitry Andric 
50650b57cec5SDimitry Andric   // Flags.
50660b57cec5SDimitry Andric   if (IsSwiftABI) {
50670b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
50680b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
50690b57cec5SDimitry Andric   } else {
50700b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
50710b57cec5SDimitry Andric   }
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   // String pointer.
50740b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
50750b57cec5SDimitry Andric   if (isUTF16) {
50760b57cec5SDimitry Andric     auto Arr = llvm::makeArrayRef(
50770b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
50780b57cec5SDimitry Andric         Entry.first().size() / 2);
50790b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
50800b57cec5SDimitry Andric   } else {
50810b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
50820b57cec5SDimitry Andric   }
50830b57cec5SDimitry Andric 
50840b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
50850b57cec5SDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
50860b57cec5SDimitry Andric   auto *GV =
50870b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
50880b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
50890b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
50900b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
50910b57cec5SDimitry Andric   // of the string is via this class initializer.
50920b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
50930b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
5094a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
50950b57cec5SDimitry Andric 
50960b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
50970b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
50980b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
50990b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
51000b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
51010b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
51020b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
51030b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
51040b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
51050b57cec5SDimitry Andric     GV->setSection(".rodata");
51060b57cec5SDimitry Andric 
51070b57cec5SDimitry Andric   // String.
51080b57cec5SDimitry Andric   llvm::Constant *Str =
51090b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
51100b57cec5SDimitry Andric 
51110b57cec5SDimitry Andric   if (isUTF16)
51120b57cec5SDimitry Andric     // Cast the UTF16 string to the correct type.
51130b57cec5SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
51140b57cec5SDimitry Andric   Fields.add(Str);
51150b57cec5SDimitry Andric 
51160b57cec5SDimitry Andric   // String length.
51170b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
51180b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
51190b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
51200b57cec5SDimitry Andric   if (IsSwiftABI) {
51210b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
51220b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
51230b57cec5SDimitry Andric       LengthTy = Int32Ty;
51240b57cec5SDimitry Andric     else
51250b57cec5SDimitry Andric       LengthTy = IntPtrTy;
51260b57cec5SDimitry Andric   }
51270b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
51280b57cec5SDimitry Andric 
5129a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5130a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
5131a7dea167SDimitry Andric   CharUnits Alignment =
5132a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
51330b57cec5SDimitry Andric 
51340b57cec5SDimitry Andric   // The struct.
51350b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
51360b57cec5SDimitry Andric                                     /*isConstant=*/false,
51370b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
51380b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
51390b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
51400b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
51410b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
5142e8d8bef9SDimitry Andric   case llvm::Triple::GOFF:
5143e8d8bef9SDimitry Andric     llvm_unreachable("GOFF is not yet implemented");
51440b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
51450b57cec5SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
51460b57cec5SDimitry Andric   case llvm::Triple::COFF:
51470b57cec5SDimitry Andric   case llvm::Triple::ELF:
51480b57cec5SDimitry Andric   case llvm::Triple::Wasm:
51490b57cec5SDimitry Andric     GV->setSection("cfstring");
51500b57cec5SDimitry Andric     break;
51510b57cec5SDimitry Andric   case llvm::Triple::MachO:
51520b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
51530b57cec5SDimitry Andric     break;
51540b57cec5SDimitry Andric   }
51550b57cec5SDimitry Andric   Entry.second = GV;
51560b57cec5SDimitry Andric 
51570b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
51580b57cec5SDimitry Andric }
51590b57cec5SDimitry Andric 
51600b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
51610b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
51620b57cec5SDimitry Andric }
51630b57cec5SDimitry Andric 
51640b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
51650b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
51660b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
51670b57cec5SDimitry Andric     D->startDefinition();
51680b57cec5SDimitry Andric 
51690b57cec5SDimitry Andric     QualType FieldTypes[] = {
51700b57cec5SDimitry Andric       Context.UnsignedLongTy,
51710b57cec5SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
51720b57cec5SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
51730b57cec5SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
5174a7dea167SDimitry Andric                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
51750b57cec5SDimitry Andric     };
51760b57cec5SDimitry Andric 
51770b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
51780b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
51790b57cec5SDimitry Andric                                            D,
51800b57cec5SDimitry Andric                                            SourceLocation(),
51810b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
51820b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
51830b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
51840b57cec5SDimitry Andric                                            /*Mutable=*/false,
51850b57cec5SDimitry Andric                                            ICIS_NoInit);
51860b57cec5SDimitry Andric       Field->setAccess(AS_public);
51870b57cec5SDimitry Andric       D->addDecl(Field);
51880b57cec5SDimitry Andric     }
51890b57cec5SDimitry Andric 
51900b57cec5SDimitry Andric     D->completeDefinition();
51910b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
51920b57cec5SDimitry Andric   }
51930b57cec5SDimitry Andric 
51940b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
51950b57cec5SDimitry Andric }
51960b57cec5SDimitry Andric 
51970b57cec5SDimitry Andric llvm::Constant *
51980b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
51990b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
52000b57cec5SDimitry Andric 
52010b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
52020b57cec5SDimitry Andric   // as an inline array.
52030b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
52040b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
52050b57cec5SDimitry Andric 
52060b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
52070b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
52080b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
52090b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
52100b57cec5SDimitry Andric   }
52110b57cec5SDimitry Andric 
52120b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
52130b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
52140b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
52150b57cec5SDimitry Andric 
52160b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
52170b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
52180b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
52190b57cec5SDimitry Andric     Elements.reserve(NumElements);
52200b57cec5SDimitry Andric 
52210b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
52220b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
52230b57cec5SDimitry Andric     Elements.resize(NumElements);
52240b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
52250b57cec5SDimitry Andric   }
52260b57cec5SDimitry Andric 
52270b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
52280b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
52290b57cec5SDimitry Andric   Elements.reserve(NumElements);
52300b57cec5SDimitry Andric 
52310b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
52320b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
52330b57cec5SDimitry Andric   Elements.resize(NumElements);
52340b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
52350b57cec5SDimitry Andric }
52360b57cec5SDimitry Andric 
52370b57cec5SDimitry Andric static llvm::GlobalVariable *
52380b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
52390b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
52400b57cec5SDimitry Andric                       CharUnits Alignment) {
52410b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
52420b57cec5SDimitry Andric       CGM.getStringLiteralAddressSpace());
52430b57cec5SDimitry Andric 
52440b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
52450b57cec5SDimitry Andric   // Create a global variable for this string
52460b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
52470b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
52480b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5249a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
52500b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
52510b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
52520b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
52530b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
52540b57cec5SDimitry Andric   }
52550b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
52560b57cec5SDimitry Andric 
52570b57cec5SDimitry Andric   return GV;
52580b57cec5SDimitry Andric }
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
52610b57cec5SDimitry Andric /// constant array for the given string literal.
52620b57cec5SDimitry Andric ConstantAddress
52630b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
52640b57cec5SDimitry Andric                                                   StringRef Name) {
52650b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
52660b57cec5SDimitry Andric 
52670b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
52680b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
52690b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
52700b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
52710b57cec5SDimitry Andric     if (auto GV = *Entry) {
52720b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5273a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
52740b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
52750b57cec5SDimitry Andric                              Alignment);
52760b57cec5SDimitry Andric     }
52770b57cec5SDimitry Andric   }
52780b57cec5SDimitry Andric 
52790b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
52800b57cec5SDimitry Andric   StringRef GlobalVariableName;
52810b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
52820b57cec5SDimitry Andric 
52830b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
52840b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
52850b57cec5SDimitry Andric   // affect strings in another.
52860b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
52870b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
52880b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
52890b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
52900b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
52910b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
52920b57cec5SDimitry Andric   } else {
52930b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
52940b57cec5SDimitry Andric     GlobalVariableName = Name;
52950b57cec5SDimitry Andric   }
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
52980b57cec5SDimitry Andric   if (Entry)
52990b57cec5SDimitry Andric     *Entry = GV;
53000b57cec5SDimitry Andric 
53010b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
53020b57cec5SDimitry Andric                                   QualType());
53030b57cec5SDimitry Andric 
53040b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53050b57cec5SDimitry Andric                          Alignment);
53060b57cec5SDimitry Andric }
53070b57cec5SDimitry Andric 
53080b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
53090b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
53100b57cec5SDimitry Andric ConstantAddress
53110b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
53120b57cec5SDimitry Andric   std::string Str;
53130b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
53140b57cec5SDimitry Andric 
53150b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
53160b57cec5SDimitry Andric }
53170b57cec5SDimitry Andric 
53180b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
53190b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
53200b57cec5SDimitry Andric /// The result has pointer to array type.
53210b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
53220b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
53230b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
53240b57cec5SDimitry Andric   CharUnits Alignment =
53250b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
53260b57cec5SDimitry Andric 
53270b57cec5SDimitry Andric   llvm::Constant *C =
53280b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
53290b57cec5SDimitry Andric 
53300b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
53310b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
53320b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
53330b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
53340b57cec5SDimitry Andric     if (auto GV = *Entry) {
53350b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5336a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
53370b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53380b57cec5SDimitry Andric                              Alignment);
53390b57cec5SDimitry Andric     }
53400b57cec5SDimitry Andric   }
53410b57cec5SDimitry Andric 
53420b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
53430b57cec5SDimitry Andric   if (!GlobalName)
53440b57cec5SDimitry Andric     GlobalName = ".str";
53450b57cec5SDimitry Andric   // Create a global variable for this.
53460b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
53470b57cec5SDimitry Andric                                   GlobalName, Alignment);
53480b57cec5SDimitry Andric   if (Entry)
53490b57cec5SDimitry Andric     *Entry = GV;
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
53520b57cec5SDimitry Andric                          Alignment);
53530b57cec5SDimitry Andric }
53540b57cec5SDimitry Andric 
53550b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
53560b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
53570b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
53580b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
53590b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
53620b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
53630b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
5364480093f4SDimitry Andric   if (Init == E->getSubExpr())
53650b57cec5SDimitry Andric     MaterializedType = E->getType();
53660b57cec5SDimitry Andric 
53670b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
53680b57cec5SDimitry Andric 
53690b57cec5SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
53700b57cec5SDimitry Andric     return ConstantAddress(Slot, Align);
53710b57cec5SDimitry Andric 
53720b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
53730b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
53740b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
53750b57cec5SDimitry Andric   SmallString<256> Name;
53760b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
53770b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
53780b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
53790b57cec5SDimitry Andric 
53800b57cec5SDimitry Andric   APValue *Value = nullptr;
5381a7dea167SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5382a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
5383a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
5384a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
5385a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
5386a7dea167SDimitry Andric     // expression modifies the temporary.
5387480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
53880b57cec5SDimitry Andric   }
53890b57cec5SDimitry Andric 
53900b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
53910b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
53920b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
53930b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
53940b57cec5SDimitry Andric     Value = &EvalResult.Val;
53950b57cec5SDimitry Andric 
53960b57cec5SDimitry Andric   LangAS AddrSpace =
53970b57cec5SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
53980b57cec5SDimitry Andric 
53990b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
54000b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
54010b57cec5SDimitry Andric   bool Constant = false;
54020b57cec5SDimitry Andric   llvm::Type *Type;
54030b57cec5SDimitry Andric   if (Value) {
54040b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
54050b57cec5SDimitry Andric     emitter.emplace(*this);
54060b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
54070b57cec5SDimitry Andric                                                MaterializedType);
54080b57cec5SDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
54090b57cec5SDimitry Andric     Type = InitialValue->getType();
54100b57cec5SDimitry Andric   } else {
54110b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
54120b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
54130b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
54140b57cec5SDimitry Andric   }
54150b57cec5SDimitry Andric 
54160b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
54170b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
54180b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
54190b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
54200b57cec5SDimitry Andric     const VarDecl *InitVD;
54210b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
54220b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
54230b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
54240b57cec5SDimitry Andric       // class can be defined in multiple translation units.
54250b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
54260b57cec5SDimitry Andric     } else {
54270b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
54280b57cec5SDimitry Andric       // VarDecl has external linkage.
54290b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
54300b57cec5SDimitry Andric     }
54310b57cec5SDimitry Andric   }
54320b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
54330b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
54340b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
54350b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
54360b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
54370b57cec5SDimitry Andric   setGVProperties(GV, VD);
5438a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
54390b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
54400b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
54410b57cec5SDimitry Andric   if (VD->getTLSKind())
54420b57cec5SDimitry Andric     setTLSMode(GV, *VD);
54430b57cec5SDimitry Andric   llvm::Constant *CV = GV;
54440b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
54450b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
54460b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
54470b57cec5SDimitry Andric         Type->getPointerTo(
54480b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
54490b57cec5SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
54500b57cec5SDimitry Andric   return ConstantAddress(CV, Align);
54510b57cec5SDimitry Andric }
54520b57cec5SDimitry Andric 
54530b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
54540b57cec5SDimitry Andric /// properties for an implementation.
54550b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
54560b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
54570b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
54580b57cec5SDimitry Andric     // Dynamic is just for type-checking.
54590b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
54600b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
54630b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
54640b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
54650b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
54660b57cec5SDimitry Andric       // this implementation.
5467480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
5468480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
54690b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
54700b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
5471480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
5472480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
54730b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
54740b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
54750b57cec5SDimitry Andric     }
54760b57cec5SDimitry Andric   }
54770b57cec5SDimitry Andric }
54780b57cec5SDimitry Andric 
54790b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
54800b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
54810b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
54820b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
54830b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
54840b57cec5SDimitry Andric       return true;
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric   return false;
54870b57cec5SDimitry Andric }
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
54900b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
54910b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
54920b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
54930b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
54940b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
54950b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
54960b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
54970b57cec5SDimitry Andric       return false;
54980b57cec5SDimitry Andric   }
54990b57cec5SDimitry Andric   return true;
55000b57cec5SDimitry Andric }
55010b57cec5SDimitry Andric 
55020b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
55030b57cec5SDimitry Andric /// for an implementation.
55040b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
55050b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
55060b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
55070b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
55080b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5509480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5510480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5511480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
55120b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
5513480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5514480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
55150b57cec5SDimitry Andric         /*isDefined=*/false, ObjCMethodDecl::Required);
55160b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
55170b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
55180b57cec5SDimitry Andric     D->setHasDestructors(true);
55190b57cec5SDimitry Andric   }
55200b57cec5SDimitry Andric 
55210b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
55220b57cec5SDimitry Andric   // a .cxx_construct.
55230b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
55240b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
55250b57cec5SDimitry Andric     return;
55260b57cec5SDimitry Andric 
55270b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
55280b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
55290b57cec5SDimitry Andric   // The constructor returns 'self'.
5530480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5531480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5532480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
55330b57cec5SDimitry Andric       /*isVariadic=*/false,
5534480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
55350b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
5536480093f4SDimitry Andric       /*isDefined=*/false, ObjCMethodDecl::Required);
55370b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
55380b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
55390b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
55400b57cec5SDimitry Andric }
55410b57cec5SDimitry Andric 
55420b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
55430b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
55440b57cec5SDimitry Andric   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5545480093f4SDimitry Andric       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
55460b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
55470b57cec5SDimitry Andric     return;
55480b57cec5SDimitry Andric   }
55490b57cec5SDimitry Andric 
55500b57cec5SDimitry Andric   EmitDeclContext(LSD);
55510b57cec5SDimitry Andric }
55520b57cec5SDimitry Andric 
55530b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
55540b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
55550b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
55560b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
55570b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
55580b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
55590b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
55600b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
55610b57cec5SDimitry Andric       for (auto *M : OID->methods())
55620b57cec5SDimitry Andric         EmitTopLevelDecl(M);
55630b57cec5SDimitry Andric     }
55640b57cec5SDimitry Andric 
55650b57cec5SDimitry Andric     EmitTopLevelDecl(I);
55660b57cec5SDimitry Andric   }
55670b57cec5SDimitry Andric }
55680b57cec5SDimitry Andric 
55690b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
55700b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
55710b57cec5SDimitry Andric   // Ignore dependent declarations.
55720b57cec5SDimitry Andric   if (D->isTemplated())
55730b57cec5SDimitry Andric     return;
55740b57cec5SDimitry Andric 
55755ffd83dbSDimitry Andric   // Consteval function shouldn't be emitted.
55765ffd83dbSDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D))
55775ffd83dbSDimitry Andric     if (FD->isConsteval())
55785ffd83dbSDimitry Andric       return;
55795ffd83dbSDimitry Andric 
55800b57cec5SDimitry Andric   switch (D->getKind()) {
55810b57cec5SDimitry Andric   case Decl::CXXConversion:
55820b57cec5SDimitry Andric   case Decl::CXXMethod:
55830b57cec5SDimitry Andric   case Decl::Function:
55840b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
55850b57cec5SDimitry Andric     // Always provide some coverage mapping
55860b57cec5SDimitry Andric     // even for the functions that aren't emitted.
55870b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
55880b57cec5SDimitry Andric     break;
55890b57cec5SDimitry Andric 
55900b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
55910b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
55920b57cec5SDimitry Andric     break;
55930b57cec5SDimitry Andric 
55940b57cec5SDimitry Andric   case Decl::Var:
55950b57cec5SDimitry Andric   case Decl::Decomposition:
55960b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
55970b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
55980b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
55990b57cec5SDimitry Andric       for (auto *B : DD->bindings())
56000b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
56010b57cec5SDimitry Andric           EmitGlobal(HD);
56020b57cec5SDimitry Andric     break;
56030b57cec5SDimitry Andric 
56040b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
56050b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
56060b57cec5SDimitry Andric   case Decl::IndirectField:
56070b57cec5SDimitry Andric     break;
56080b57cec5SDimitry Andric 
56090b57cec5SDimitry Andric   // C++ Decls
56100b57cec5SDimitry Andric   case Decl::Namespace:
56110b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
56120b57cec5SDimitry Andric     break;
56130b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
56140b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
56155ffd83dbSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
56165ffd83dbSDimitry Andric       if (Spec->getSpecializationKind() ==
56175ffd83dbSDimitry Andric               TSK_ExplicitInstantiationDefinition &&
56180b57cec5SDimitry Andric           Spec->hasDefinition())
56195ffd83dbSDimitry Andric         DI->completeTemplateDefinition(*Spec);
56200b57cec5SDimitry Andric   } LLVM_FALLTHROUGH;
5621e8d8bef9SDimitry Andric   case Decl::CXXRecord: {
5622e8d8bef9SDimitry Andric     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5623e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5624e8d8bef9SDimitry Andric       if (CRD->hasDefinition())
5625e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
56260b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
56270b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5628e8d8bef9SDimitry Andric           DI->completeUnusedClass(*CRD);
5629e8d8bef9SDimitry Andric     }
56300b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
5631e8d8bef9SDimitry Andric     for (auto *I : CRD->decls())
56320b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
56330b57cec5SDimitry Andric         EmitTopLevelDecl(I);
56340b57cec5SDimitry Andric     break;
5635e8d8bef9SDimitry Andric   }
56360b57cec5SDimitry Andric     // No code generation needed.
56370b57cec5SDimitry Andric   case Decl::UsingShadow:
56380b57cec5SDimitry Andric   case Decl::ClassTemplate:
56390b57cec5SDimitry Andric   case Decl::VarTemplate:
56400b57cec5SDimitry Andric   case Decl::Concept:
56410b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
56420b57cec5SDimitry Andric   case Decl::FunctionTemplate:
56430b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
56440b57cec5SDimitry Andric   case Decl::Block:
56450b57cec5SDimitry Andric   case Decl::Empty:
56460b57cec5SDimitry Andric   case Decl::Binding:
56470b57cec5SDimitry Andric     break;
56480b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
56490b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
56500b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
56515ffd83dbSDimitry Andric     break;
56520b57cec5SDimitry Andric   case Decl::NamespaceAlias:
56530b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
56540b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
56555ffd83dbSDimitry Andric     break;
56560b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
56570b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
56580b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
56595ffd83dbSDimitry Andric     break;
56600b57cec5SDimitry Andric   case Decl::CXXConstructor:
56610b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
56620b57cec5SDimitry Andric     break;
56630b57cec5SDimitry Andric   case Decl::CXXDestructor:
56640b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
56650b57cec5SDimitry Andric     break;
56660b57cec5SDimitry Andric 
56670b57cec5SDimitry Andric   case Decl::StaticAssert:
56680b57cec5SDimitry Andric     // Nothing to do.
56690b57cec5SDimitry Andric     break;
56700b57cec5SDimitry Andric 
56710b57cec5SDimitry Andric   // Objective-C Decls
56720b57cec5SDimitry Andric 
56730b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
56740b57cec5SDimitry Andric   case Decl::ObjCInterface:
56750b57cec5SDimitry Andric   case Decl::ObjCCategory:
56760b57cec5SDimitry Andric     break;
56770b57cec5SDimitry Andric 
56780b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
56790b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
56800b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
56810b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
56820b57cec5SDimitry Andric     break;
56830b57cec5SDimitry Andric   }
56840b57cec5SDimitry Andric 
56850b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
56860b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
56870b57cec5SDimitry Andric     // can ignore them here.
56880b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
56890b57cec5SDimitry Andric     break;
56900b57cec5SDimitry Andric 
56910b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
56920b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
56930b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
56940b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
56950b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
56960b57cec5SDimitry Andric     // Emit global variable debug information.
56970b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5698480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
56990b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
57000b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
57010b57cec5SDimitry Andric     break;
57020b57cec5SDimitry Andric   }
57030b57cec5SDimitry Andric   case Decl::ObjCMethod: {
57040b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
57050b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
57060b57cec5SDimitry Andric     if (OMD->getBody())
57070b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
57080b57cec5SDimitry Andric     break;
57090b57cec5SDimitry Andric   }
57100b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
57110b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
57120b57cec5SDimitry Andric     break;
57130b57cec5SDimitry Andric 
57140b57cec5SDimitry Andric   case Decl::PragmaComment: {
57150b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
57160b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
57170b57cec5SDimitry Andric     case PCK_Unknown:
57180b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
57190b57cec5SDimitry Andric     case PCK_Linker:
57200b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
57210b57cec5SDimitry Andric       break;
57220b57cec5SDimitry Andric     case PCK_Lib:
57230b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
57240b57cec5SDimitry Andric       break;
57250b57cec5SDimitry Andric     case PCK_Compiler:
57260b57cec5SDimitry Andric     case PCK_ExeStr:
57270b57cec5SDimitry Andric     case PCK_User:
57280b57cec5SDimitry Andric       break; // We ignore all of these.
57290b57cec5SDimitry Andric     }
57300b57cec5SDimitry Andric     break;
57310b57cec5SDimitry Andric   }
57320b57cec5SDimitry Andric 
57330b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
57340b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
57350b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
57360b57cec5SDimitry Andric     break;
57370b57cec5SDimitry Andric   }
57380b57cec5SDimitry Andric 
57390b57cec5SDimitry Andric   case Decl::LinkageSpec:
57400b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
57410b57cec5SDimitry Andric     break;
57420b57cec5SDimitry Andric 
57430b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
57440b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
57450b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
57460b57cec5SDimitry Andric       break;
57470b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
57480b57cec5SDimitry Andric     if (LangOpts.OpenMPIsDevice)
57490b57cec5SDimitry Andric       break;
57500b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
57510b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
57520b57cec5SDimitry Andric     break;
57530b57cec5SDimitry Andric   }
57540b57cec5SDimitry Andric 
57550b57cec5SDimitry Andric   case Decl::Import: {
57560b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
57570b57cec5SDimitry Andric 
57580b57cec5SDimitry Andric     // If we've already imported this module, we're done.
57590b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
57600b57cec5SDimitry Andric       break;
57610b57cec5SDimitry Andric 
57620b57cec5SDimitry Andric     // Emit debug information for direct imports.
57630b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
57640b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
57650b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
57660b57cec5SDimitry Andric     }
57670b57cec5SDimitry Andric 
57680b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
57690b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
57700b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
57710b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
57720b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
57730b57cec5SDimitry Andric 
57740b57cec5SDimitry Andric     while (!Stack.empty()) {
57750b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
57760b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
57770b57cec5SDimitry Andric         continue;
57780b57cec5SDimitry Andric 
57790b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
57800b57cec5SDimitry Andric         EmitTopLevelDecl(D);
57810b57cec5SDimitry Andric 
57820b57cec5SDimitry Andric       // Visit the submodules of this module.
57830b57cec5SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
57840b57cec5SDimitry Andric                                              SubEnd = Mod->submodule_end();
57850b57cec5SDimitry Andric            Sub != SubEnd; ++Sub) {
57860b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
57870b57cec5SDimitry Andric         // the initializers.
57880b57cec5SDimitry Andric         if ((*Sub)->IsExplicit)
57890b57cec5SDimitry Andric           continue;
57900b57cec5SDimitry Andric 
57910b57cec5SDimitry Andric         if (Visited.insert(*Sub).second)
57920b57cec5SDimitry Andric           Stack.push_back(*Sub);
57930b57cec5SDimitry Andric       }
57940b57cec5SDimitry Andric     }
57950b57cec5SDimitry Andric     break;
57960b57cec5SDimitry Andric   }
57970b57cec5SDimitry Andric 
57980b57cec5SDimitry Andric   case Decl::Export:
57990b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
58000b57cec5SDimitry Andric     break;
58010b57cec5SDimitry Andric 
58020b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
58030b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
58040b57cec5SDimitry Andric     break;
58050b57cec5SDimitry Andric 
58060b57cec5SDimitry Andric   case Decl::OMPAllocate:
58070b57cec5SDimitry Andric     break;
58080b57cec5SDimitry Andric 
58090b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
58100b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
58110b57cec5SDimitry Andric     break;
58120b57cec5SDimitry Andric 
58130b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
58140b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
58150b57cec5SDimitry Andric     break;
58160b57cec5SDimitry Andric 
58170b57cec5SDimitry Andric   case Decl::OMPRequires:
58180b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
58190b57cec5SDimitry Andric     break;
58200b57cec5SDimitry Andric 
5821e8d8bef9SDimitry Andric   case Decl::Typedef:
5822e8d8bef9SDimitry Andric   case Decl::TypeAlias: // using foo = bar; [C++11]
5823e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5824e8d8bef9SDimitry Andric       DI->EmitAndRetainType(
5825e8d8bef9SDimitry Andric           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5826e8d8bef9SDimitry Andric     break;
5827e8d8bef9SDimitry Andric 
5828e8d8bef9SDimitry Andric   case Decl::Record:
5829e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5830e8d8bef9SDimitry Andric       if (cast<RecordDecl>(D)->getDefinition())
5831e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5832e8d8bef9SDimitry Andric     break;
5833e8d8bef9SDimitry Andric 
5834e8d8bef9SDimitry Andric   case Decl::Enum:
5835e8d8bef9SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5836e8d8bef9SDimitry Andric       if (cast<EnumDecl>(D)->getDefinition())
5837e8d8bef9SDimitry Andric         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5838e8d8bef9SDimitry Andric     break;
5839e8d8bef9SDimitry Andric 
58400b57cec5SDimitry Andric   default:
58410b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
58420b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
58430b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
58440b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
58450b57cec5SDimitry Andric     break;
58460b57cec5SDimitry Andric   }
58470b57cec5SDimitry Andric }
58480b57cec5SDimitry Andric 
58490b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
58500b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
58510b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
58520b57cec5SDimitry Andric     return;
58530b57cec5SDimitry Andric   switch (D->getKind()) {
58540b57cec5SDimitry Andric   case Decl::CXXConversion:
58550b57cec5SDimitry Andric   case Decl::CXXMethod:
58560b57cec5SDimitry Andric   case Decl::Function:
58570b57cec5SDimitry Andric   case Decl::ObjCMethod:
58580b57cec5SDimitry Andric   case Decl::CXXConstructor:
58590b57cec5SDimitry Andric   case Decl::CXXDestructor: {
58600b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
58615ffd83dbSDimitry Andric       break;
58620b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
58630b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
58645ffd83dbSDimitry Andric       break;
58650b57cec5SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
58660b57cec5SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
58670b57cec5SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
58680b57cec5SDimitry Andric     break;
58690b57cec5SDimitry Andric   }
58700b57cec5SDimitry Andric   default:
58710b57cec5SDimitry Andric     break;
58720b57cec5SDimitry Andric   };
58730b57cec5SDimitry Andric }
58740b57cec5SDimitry Andric 
58750b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
58760b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
58770b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
58780b57cec5SDimitry Andric     return;
58790b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
58800b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
58810b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
58820b57cec5SDimitry Andric   }
58830b57cec5SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
58840b57cec5SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
58850b57cec5SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
58860b57cec5SDimitry Andric   else
58870b57cec5SDimitry Andric     I->second = false;
58880b57cec5SDimitry Andric }
58890b57cec5SDimitry Andric 
58900b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
58910b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
58920b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
58930b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
58940b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
58950b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
58960b57cec5SDimitry Andric     if (!Entry.second)
58970b57cec5SDimitry Andric       continue;
58980b57cec5SDimitry Andric     const Decl *D = Entry.first;
58990b57cec5SDimitry Andric     switch (D->getKind()) {
59000b57cec5SDimitry Andric     case Decl::CXXConversion:
59010b57cec5SDimitry Andric     case Decl::CXXMethod:
59020b57cec5SDimitry Andric     case Decl::Function:
59030b57cec5SDimitry Andric     case Decl::ObjCMethod: {
59040b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
59050b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
59060b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
59070b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
59080b57cec5SDimitry Andric       break;
59090b57cec5SDimitry Andric     }
59100b57cec5SDimitry Andric     case Decl::CXXConstructor: {
59110b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
59120b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
59130b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
59140b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
59150b57cec5SDimitry Andric       break;
59160b57cec5SDimitry Andric     }
59170b57cec5SDimitry Andric     case Decl::CXXDestructor: {
59180b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
59190b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
59200b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
59210b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
59220b57cec5SDimitry Andric       break;
59230b57cec5SDimitry Andric     }
59240b57cec5SDimitry Andric     default:
59250b57cec5SDimitry Andric       break;
59260b57cec5SDimitry Andric     };
59270b57cec5SDimitry Andric   }
59280b57cec5SDimitry Andric }
59290b57cec5SDimitry Andric 
59305ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() {
59315ffd83dbSDimitry Andric   // In order to transition away from "__original_main" gracefully, emit an
59325ffd83dbSDimitry Andric   // alias for "main" in the no-argument case so that libc can detect when
59335ffd83dbSDimitry Andric   // new-style no-argument main is in used.
59345ffd83dbSDimitry Andric   if (llvm::Function *F = getModule().getFunction("main")) {
59355ffd83dbSDimitry Andric     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
59365ffd83dbSDimitry Andric         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
59375ffd83dbSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
59385ffd83dbSDimitry Andric   }
59395ffd83dbSDimitry Andric }
59405ffd83dbSDimitry Andric 
59410b57cec5SDimitry Andric /// Turns the given pointer into a constant.
59420b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
59430b57cec5SDimitry Andric                                           const void *Ptr) {
59440b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
59450b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
59460b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
59470b57cec5SDimitry Andric }
59480b57cec5SDimitry Andric 
59490b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
59500b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
59510b57cec5SDimitry Andric                                    GlobalDecl D,
59520b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
59530b57cec5SDimitry Andric   if (!GlobalMetadata)
59540b57cec5SDimitry Andric     GlobalMetadata =
59550b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
59560b57cec5SDimitry Andric 
59570b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
59580b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
59590b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
59600b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
59610b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
59620b57cec5SDimitry Andric }
59630b57cec5SDimitry Andric 
59640b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
59650b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
59660b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
59670b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
59680b57cec5SDimitry Andric /// same translation unit.
59690b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
59700b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
59710b57cec5SDimitry Andric     return;
59720b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
59730b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
59740b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
59750b57cec5SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
59760b57cec5SDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
59770b57cec5SDimitry Andric   }
59780b57cec5SDimitry Andric }
59790b57cec5SDimitry Andric 
59800b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
59810b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
59820b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
59830b57cec5SDimitry Andric   if (Res == Manglings.end())
59840b57cec5SDimitry Andric     return false;
59850b57cec5SDimitry Andric   Result = Res->getValue();
59860b57cec5SDimitry Andric   return true;
59870b57cec5SDimitry Andric }
59880b57cec5SDimitry Andric 
59890b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
59900b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
59910b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
59920b57cec5SDimitry Andric ///
59930b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
59940b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
59950b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
59960b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
59970b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
59980b57cec5SDimitry Andric 
59990b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
60000b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
60010b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
60020b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
60030b57cec5SDimitry Andric     if (Addr)
60040b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
60050b57cec5SDimitry Andric   }
60060b57cec5SDimitry Andric }
60070b57cec5SDimitry Andric 
60080b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
60090b57cec5SDimitry Andric /// function.
60100b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
60110b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
60120b57cec5SDimitry Andric 
60130b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
60140b57cec5SDimitry Andric 
60150b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
60160b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
60170b57cec5SDimitry Andric 
60180b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
60190b57cec5SDimitry Andric 
60200b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
60210b57cec5SDimitry Andric     const Decl *D = I.first;
60220b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
60230b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
60240b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
60250b57cec5SDimitry Andric       Alloca->setMetadata(
60260b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
60270b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
60280b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
60290b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
60300b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
60310b57cec5SDimitry Andric     }
60320b57cec5SDimitry Andric   }
60330b57cec5SDimitry Andric }
60340b57cec5SDimitry Andric 
60350b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
60360b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
60370b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
60380b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
60390b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
60400b57cec5SDimitry Andric 
60410b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
60420b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
60430b57cec5SDimitry Andric }
60440b57cec5SDimitry Andric 
60450b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
60460b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
60470b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
60480b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
60490b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
60500b57cec5SDimitry Andric 
60510b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
60520b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
60530b57cec5SDimitry Andric }
60540b57cec5SDimitry Andric 
60550b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
60560b57cec5SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
60570b57cec5SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
60580b57cec5SDimitry Andric     return;
60590b57cec5SDimitry Andric 
60600b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
60610b57cec5SDimitry Andric   if (!CUNode)
60620b57cec5SDimitry Andric     return;
60630b57cec5SDimitry Andric 
60640b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
60650b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
60660b57cec5SDimitry Andric   auto *CoverageDataFile =
60670b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
60680b57cec5SDimitry Andric   auto *CoverageNotesFile =
60690b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
60700b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
60710b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
60720b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
60730b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
60740b57cec5SDimitry Andric   }
60750b57cec5SDimitry Andric }
60760b57cec5SDimitry Andric 
60770b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
60780b57cec5SDimitry Andric                                                        bool ForEH) {
60790b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
60800b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
60810b57cec5SDimitry Andric   // and it's not for EH?
60825ffd83dbSDimitry Andric   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
60835ffd83dbSDimitry Andric       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
60845ffd83dbSDimitry Andric        getTriple().isNVPTX()))
60850b57cec5SDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
60860b57cec5SDimitry Andric 
60870b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
60880b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
60890b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
60900b57cec5SDimitry Andric 
60910b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
60920b57cec5SDimitry Andric }
60930b57cec5SDimitry Andric 
60940b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
60950b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
60960b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
60970b57cec5SDimitry Andric     return;
60980b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
60990b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
61000b57cec5SDimitry Andric     bool PerformInit =
61010b57cec5SDimitry Andric         VD->getAnyInitializer() &&
61020b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
61030b57cec5SDimitry Andric                                                         /*ForRef=*/false);
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
61060b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
61070b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
61080b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
61090b57cec5SDimitry Andric   }
61100b57cec5SDimitry Andric }
61110b57cec5SDimitry Andric 
61120b57cec5SDimitry Andric llvm::Metadata *
61130b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
61140b57cec5SDimitry Andric                                             StringRef Suffix) {
61150b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
61160b57cec5SDimitry Andric   if (InternalId)
61170b57cec5SDimitry Andric     return InternalId;
61180b57cec5SDimitry Andric 
61190b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
61200b57cec5SDimitry Andric     std::string OutName;
61210b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
61220b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
61230b57cec5SDimitry Andric     Out << Suffix;
61240b57cec5SDimitry Andric 
61250b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
61260b57cec5SDimitry Andric   } else {
61270b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
61280b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
61290b57cec5SDimitry Andric   }
61300b57cec5SDimitry Andric 
61310b57cec5SDimitry Andric   return InternalId;
61320b57cec5SDimitry Andric }
61330b57cec5SDimitry Andric 
61340b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
61350b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
61360b57cec5SDimitry Andric }
61370b57cec5SDimitry Andric 
61380b57cec5SDimitry Andric llvm::Metadata *
61390b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
61400b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
61410b57cec5SDimitry Andric }
61420b57cec5SDimitry Andric 
61430b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
61440b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
61450b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
61460b57cec5SDimitry Andric // 'void *'.
61470b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
61480b57cec5SDimitry Andric   if (!Ty->isPointerType())
61490b57cec5SDimitry Andric     return Ty;
61500b57cec5SDimitry Andric 
61510b57cec5SDimitry Andric   return Ctx.getPointerType(
61520b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
61530b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
61540b57cec5SDimitry Andric }
61550b57cec5SDimitry Andric 
61560b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
61570b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
61580b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
61590b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
61600b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
61610b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
61620b57cec5SDimitry Andric 
61630b57cec5SDimitry Andric     return Ctx.getFunctionType(
61640b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
61650b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
61660b57cec5SDimitry Andric   }
61670b57cec5SDimitry Andric 
61680b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
61690b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
61700b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
61710b57cec5SDimitry Andric 
61720b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
61730b57cec5SDimitry Andric }
61740b57cec5SDimitry Andric 
61750b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
61760b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
61770b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
61780b57cec5SDimitry Andric }
61790b57cec5SDimitry Andric 
61800b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
61810b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
61820b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
61830b57cec5SDimitry Andric   // is not in the trapping mode.
61840b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
61850b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
61860b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
61870b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
61880b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
61890b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
61900b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
61910b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
61920b57cec5SDimitry Andric }
61930b57cec5SDimitry Andric 
61940b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
61950b57cec5SDimitry Andric                                           CharUnits Offset,
61960b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
61970b57cec5SDimitry Andric   llvm::Metadata *MD =
61980b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
61990b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
62000b57cec5SDimitry Andric 
62010b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
62020b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
62030b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
62040b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
62050b57cec5SDimitry Andric 
62060b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
62070b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
62080b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
62090b57cec5SDimitry Andric   }
62100b57cec5SDimitry Andric }
62110b57cec5SDimitry Andric 
62120b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
62130b57cec5SDimitry Andric   if (!SanStats)
6214a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
62150b57cec5SDimitry Andric 
62160b57cec5SDimitry Andric   return *SanStats;
62170b57cec5SDimitry Andric }
6218*23408297SDimitry Andric 
62190b57cec5SDimitry Andric llvm::Value *
62200b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
62210b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
62220b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6223*23408297SDimitry Andric   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6224*23408297SDimitry Andric   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6225*23408297SDimitry Andric   auto *Call = CGF.Builder.CreateCall(
6226*23408297SDimitry Andric       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6227*23408297SDimitry Andric   Call->setCallingConv(Call->getCalledFunction()->getCallingConv());
6228*23408297SDimitry Andric   return Call;
62290b57cec5SDimitry Andric }
62305ffd83dbSDimitry Andric 
62315ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
62325ffd83dbSDimitry Andric     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
62335ffd83dbSDimitry Andric   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
62345ffd83dbSDimitry Andric                                  /* forPointeeType= */ true);
62355ffd83dbSDimitry Andric }
62365ffd83dbSDimitry Andric 
62375ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
62385ffd83dbSDimitry Andric                                                  LValueBaseInfo *BaseInfo,
62395ffd83dbSDimitry Andric                                                  TBAAAccessInfo *TBAAInfo,
62405ffd83dbSDimitry Andric                                                  bool forPointeeType) {
62415ffd83dbSDimitry Andric   if (TBAAInfo)
62425ffd83dbSDimitry Andric     *TBAAInfo = getTBAAAccessInfo(T);
62435ffd83dbSDimitry Andric 
62445ffd83dbSDimitry Andric   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
62455ffd83dbSDimitry Andric   // that doesn't return the information we need to compute BaseInfo.
62465ffd83dbSDimitry Andric 
62475ffd83dbSDimitry Andric   // Honor alignment typedef attributes even on incomplete types.
62485ffd83dbSDimitry Andric   // We also honor them straight for C++ class types, even as pointees;
62495ffd83dbSDimitry Andric   // there's an expressivity gap here.
62505ffd83dbSDimitry Andric   if (auto TT = T->getAs<TypedefType>()) {
62515ffd83dbSDimitry Andric     if (auto Align = TT->getDecl()->getMaxAlignment()) {
62525ffd83dbSDimitry Andric       if (BaseInfo)
62535ffd83dbSDimitry Andric         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
62545ffd83dbSDimitry Andric       return getContext().toCharUnitsFromBits(Align);
62555ffd83dbSDimitry Andric     }
62565ffd83dbSDimitry Andric   }
62575ffd83dbSDimitry Andric 
62585ffd83dbSDimitry Andric   bool AlignForArray = T->isArrayType();
62595ffd83dbSDimitry Andric 
62605ffd83dbSDimitry Andric   // Analyze the base element type, so we don't get confused by incomplete
62615ffd83dbSDimitry Andric   // array types.
62625ffd83dbSDimitry Andric   T = getContext().getBaseElementType(T);
62635ffd83dbSDimitry Andric 
62645ffd83dbSDimitry Andric   if (T->isIncompleteType()) {
62655ffd83dbSDimitry Andric     // We could try to replicate the logic from
62665ffd83dbSDimitry Andric     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
62675ffd83dbSDimitry Andric     // type is incomplete, so it's impossible to test. We could try to reuse
62685ffd83dbSDimitry Andric     // getTypeAlignIfKnown, but that doesn't return the information we need
62695ffd83dbSDimitry Andric     // to set BaseInfo.  So just ignore the possibility that the alignment is
62705ffd83dbSDimitry Andric     // greater than one.
62715ffd83dbSDimitry Andric     if (BaseInfo)
62725ffd83dbSDimitry Andric       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
62735ffd83dbSDimitry Andric     return CharUnits::One();
62745ffd83dbSDimitry Andric   }
62755ffd83dbSDimitry Andric 
62765ffd83dbSDimitry Andric   if (BaseInfo)
62775ffd83dbSDimitry Andric     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
62785ffd83dbSDimitry Andric 
62795ffd83dbSDimitry Andric   CharUnits Alignment;
6280e8d8bef9SDimitry Andric   const CXXRecordDecl *RD;
6281e8d8bef9SDimitry Andric   if (T.getQualifiers().hasUnaligned()) {
6282e8d8bef9SDimitry Andric     Alignment = CharUnits::One();
6283e8d8bef9SDimitry Andric   } else if (forPointeeType && !AlignForArray &&
6284e8d8bef9SDimitry Andric              (RD = T->getAsCXXRecordDecl())) {
62855ffd83dbSDimitry Andric     // For C++ class pointees, we don't know whether we're pointing at a
62865ffd83dbSDimitry Andric     // base or a complete object, so we generally need to use the
62875ffd83dbSDimitry Andric     // non-virtual alignment.
62885ffd83dbSDimitry Andric     Alignment = getClassPointerAlignment(RD);
62895ffd83dbSDimitry Andric   } else {
62905ffd83dbSDimitry Andric     Alignment = getContext().getTypeAlignInChars(T);
62915ffd83dbSDimitry Andric   }
62925ffd83dbSDimitry Andric 
62935ffd83dbSDimitry Andric   // Cap to the global maximum type alignment unless the alignment
62945ffd83dbSDimitry Andric   // was somehow explicit on the type.
62955ffd83dbSDimitry Andric   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
62965ffd83dbSDimitry Andric     if (Alignment.getQuantity() > MaxAlign &&
62975ffd83dbSDimitry Andric         !getContext().isAlignmentRequired(T))
62985ffd83dbSDimitry Andric       Alignment = CharUnits::fromQuantity(MaxAlign);
62995ffd83dbSDimitry Andric   }
63005ffd83dbSDimitry Andric   return Alignment;
63015ffd83dbSDimitry Andric }
63025ffd83dbSDimitry Andric 
63035ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() {
63045ffd83dbSDimitry Andric   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
63055ffd83dbSDimitry Andric   if (StopAfter) {
63065ffd83dbSDimitry Andric     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
63075ffd83dbSDimitry Andric     // used
63085ffd83dbSDimitry Andric     if (NumAutoVarInit >= StopAfter) {
63095ffd83dbSDimitry Andric       return true;
63105ffd83dbSDimitry Andric     }
63115ffd83dbSDimitry Andric     if (!NumAutoVarInit) {
63125ffd83dbSDimitry Andric       unsigned DiagID = getDiags().getCustomDiagID(
63135ffd83dbSDimitry Andric           DiagnosticsEngine::Warning,
63145ffd83dbSDimitry Andric           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
63155ffd83dbSDimitry Andric           "number of times ftrivial-auto-var-init=%1 gets applied.");
63165ffd83dbSDimitry Andric       getDiags().Report(DiagID)
63175ffd83dbSDimitry Andric           << StopAfter
63185ffd83dbSDimitry Andric           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
63195ffd83dbSDimitry Andric                       LangOptions::TrivialAutoVarInitKind::Zero
63205ffd83dbSDimitry Andric                   ? "zero"
63215ffd83dbSDimitry Andric                   : "pattern");
63225ffd83dbSDimitry Andric     }
63235ffd83dbSDimitry Andric     ++NumAutoVarInit;
63245ffd83dbSDimitry Andric   }
63255ffd83dbSDimitry Andric   return false;
63265ffd83dbSDimitry Andric }
6327