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" 22349cc55cSDimitry Andric #include "CGOpenMPRuntimeGPU.h" 230b57cec5SDimitry Andric #include "CodeGenFunction.h" 240b57cec5SDimitry Andric #include "CodeGenPGO.h" 250b57cec5SDimitry Andric #include "ConstantEmitter.h" 260b57cec5SDimitry Andric #include "CoverageMappingGen.h" 270b57cec5SDimitry Andric #include "TargetInfo.h" 280b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 290b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 300b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 310b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 320b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h" 330b57cec5SDimitry Andric #include "clang/AST/Mangle.h" 340b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h" 350b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 360b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h" 370b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 380b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h" 390b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 400b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h" 415ffd83dbSDimitry Andric #include "clang/Basic/FileManager.h" 420b57cec5SDimitry Andric #include "clang/Basic/Module.h" 430b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h" 440b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 450b57cec5SDimitry Andric #include "clang/Basic/Version.h" 460b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 470b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h" 480b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 490b57cec5SDimitry Andric #include "llvm/ADT/Triple.h" 500b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 51480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 520b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h" 530b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 540b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 550b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 560b57cec5SDimitry Andric #include "llvm/IR/Module.h" 570b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h" 580b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 590b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h" 60480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 610b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h" 620b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 630b57cec5SDimitry Andric #include "llvm/Support/MD5.h" 640b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h" 65349cc55cSDimitry Andric #include "llvm/Support/X86TargetParser.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) { 78fe6060f1SDimitry Andric switch (CGM.getContext().getCXXABIKind()) { 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); 133349cc55cSDimitry Andric const llvm::DataLayout &DL = M.getDataLayout(); 134349cc55cSDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo(DL.getAllocaAddrSpace()); 135349cc55cSDimitry Andric GlobalsInt8PtrTy = Int8Ty->getPointerTo(DL.getDefaultGlobalsAddressSpace()); 1360b57cec5SDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 1370b57cec5SDimitry Andric 1380b57cec5SDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 1390b57cec5SDimitry Andric 1400b57cec5SDimitry Andric if (LangOpts.ObjC) 1410b57cec5SDimitry Andric createObjCRuntime(); 1420b57cec5SDimitry Andric if (LangOpts.OpenCL) 1430b57cec5SDimitry Andric createOpenCLRuntime(); 1440b57cec5SDimitry Andric if (LangOpts.OpenMP) 1450b57cec5SDimitry Andric createOpenMPRuntime(); 1460b57cec5SDimitry Andric if (LangOpts.CUDA) 1470b57cec5SDimitry Andric createCUDARuntime(); 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 1500b57cec5SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1510b57cec5SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 1520b57cec5SDimitry Andric TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 1530b57cec5SDimitry Andric getCXXABI().getMangleContext())); 1540b57cec5SDimitry Andric 1550b57cec5SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1560b57cec5SDimitry Andric // object. 1570b57cec5SDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 1580b57cec5SDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 1590b57cec5SDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1600b57cec5SDimitry Andric 1610b57cec5SDimitry Andric Block.GlobalUniqueCount = 0; 1620b57cec5SDimitry Andric 1630b57cec5SDimitry Andric if (C.getLangOpts().ObjC) 1640b57cec5SDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 1670b57cec5SDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 1680b57cec5SDimitry Andric CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 1690b57cec5SDimitry Andric if (auto E = ReaderOrErr.takeError()) { 1700b57cec5SDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1710b57cec5SDimitry Andric "Could not read profile %0: %1"); 1720b57cec5SDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 1730b57cec5SDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 1740b57cec5SDimitry Andric << EI.message(); 1750b57cec5SDimitry Andric }); 1760b57cec5SDimitry Andric } else 1770b57cec5SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 1780b57cec5SDimitry Andric } 1790b57cec5SDimitry Andric 1800b57cec5SDimitry Andric // If coverage mapping generation is enabled, create the 1810b57cec5SDimitry Andric // CoverageMappingModuleGen object. 1820b57cec5SDimitry Andric if (CodeGenOpts.CoverageMapping) 1830b57cec5SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 184fe6060f1SDimitry Andric 185fe6060f1SDimitry Andric // Generate the module name hash here if needed. 186fe6060f1SDimitry Andric if (CodeGenOpts.UniqueInternalLinkageNames && 187fe6060f1SDimitry Andric !getModule().getSourceFileName().empty()) { 188fe6060f1SDimitry Andric std::string Path = getModule().getSourceFileName(); 189fe6060f1SDimitry Andric // Check if a path substitution is needed from the MacroPrefixMap. 1906e75b2fbSDimitry Andric for (const auto &Entry : LangOpts.MacroPrefixMap) 191fe6060f1SDimitry Andric if (Path.rfind(Entry.first, 0) != std::string::npos) { 192fe6060f1SDimitry Andric Path = Entry.second + Path.substr(Entry.first.size()); 193fe6060f1SDimitry Andric break; 194fe6060f1SDimitry Andric } 195fe6060f1SDimitry Andric llvm::MD5 Md5; 196fe6060f1SDimitry Andric Md5.update(Path); 197fe6060f1SDimitry Andric llvm::MD5::MD5Result R; 198fe6060f1SDimitry Andric Md5.final(R); 199fe6060f1SDimitry Andric SmallString<32> Str; 200fe6060f1SDimitry Andric llvm::MD5::stringifyResult(R, Str); 201fe6060f1SDimitry Andric // Convert MD5hash to Decimal. Demangler suffixes can either contain 202fe6060f1SDimitry Andric // numbers or characters but not both. 203fe6060f1SDimitry Andric llvm::APInt IntHash(128, Str.str(), 16); 204fe6060f1SDimitry Andric // Prepend "__uniq" before the hash for tools like profilers to understand 205fe6060f1SDimitry Andric // that this symbol is of internal linkage type. The "__uniq" is the 206fe6060f1SDimitry Andric // pre-determined prefix that is used to tell tools that this symbol was 207fe6060f1SDimitry Andric // created with -funique-internal-linakge-symbols and the tools can strip or 208fe6060f1SDimitry Andric // keep the prefix as needed. 209fe6060f1SDimitry Andric ModuleNameHash = (Twine(".__uniq.") + 210fe6060f1SDimitry Andric Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str(); 211fe6060f1SDimitry Andric } 2120b57cec5SDimitry Andric } 2130b57cec5SDimitry Andric 2140b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {} 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() { 2170b57cec5SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 2180b57cec5SDimitry Andric // new ABIs to decide how best to do this. 2190b57cec5SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 2200b57cec5SDimitry Andric case ObjCRuntime::GNUstep: 2210b57cec5SDimitry Andric case ObjCRuntime::GCC: 2220b57cec5SDimitry Andric case ObjCRuntime::ObjFW: 2230b57cec5SDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 2240b57cec5SDimitry Andric return; 2250b57cec5SDimitry Andric 2260b57cec5SDimitry Andric case ObjCRuntime::FragileMacOSX: 2270b57cec5SDimitry Andric case ObjCRuntime::MacOSX: 2280b57cec5SDimitry Andric case ObjCRuntime::iOS: 2290b57cec5SDimitry Andric case ObjCRuntime::WatchOS: 2300b57cec5SDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 2310b57cec5SDimitry Andric return; 2320b57cec5SDimitry Andric } 2330b57cec5SDimitry Andric llvm_unreachable("bad runtime kind"); 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 2370b57cec5SDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 2380b57cec5SDimitry Andric } 2390b57cec5SDimitry Andric 2400b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() { 2410b57cec5SDimitry Andric // Select a specialized code generation class based on the target, if any. 2420b57cec5SDimitry Andric // If it does not exist use the default implementation. 2430b57cec5SDimitry Andric switch (getTriple().getArch()) { 2440b57cec5SDimitry Andric case llvm::Triple::nvptx: 2450b57cec5SDimitry Andric case llvm::Triple::nvptx64: 246e8d8bef9SDimitry Andric case llvm::Triple::amdgcn: 247e8d8bef9SDimitry Andric assert(getLangOpts().OpenMPIsDevice && 248349cc55cSDimitry Andric "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 249349cc55cSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 250e8d8bef9SDimitry Andric break; 2510b57cec5SDimitry Andric default: 2520b57cec5SDimitry Andric if (LangOpts.OpenMPSimd) 2530b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 2540b57cec5SDimitry Andric else 2550b57cec5SDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 2560b57cec5SDimitry Andric break; 2570b57cec5SDimitry Andric } 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() { 2610b57cec5SDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 2620b57cec5SDimitry Andric } 2630b57cec5SDimitry Andric 2640b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 2650b57cec5SDimitry Andric Replacements[Name] = C; 2660b57cec5SDimitry Andric } 2670b57cec5SDimitry Andric 2680b57cec5SDimitry Andric void CodeGenModule::applyReplacements() { 2690b57cec5SDimitry Andric for (auto &I : Replacements) { 2700b57cec5SDimitry Andric StringRef MangledName = I.first(); 2710b57cec5SDimitry Andric llvm::Constant *Replacement = I.second; 2720b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2730b57cec5SDimitry Andric if (!Entry) 2740b57cec5SDimitry Andric continue; 2750b57cec5SDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 2760b57cec5SDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 2770b57cec5SDimitry Andric if (!NewF) { 2780b57cec5SDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 2790b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 2800b57cec5SDimitry Andric } else { 2810b57cec5SDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 2820b57cec5SDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 2830b57cec5SDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 2840b57cec5SDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 2850b57cec5SDimitry Andric } 2860b57cec5SDimitry Andric } 2870b57cec5SDimitry Andric 2880b57cec5SDimitry Andric // Replace old with new, but keep the old order. 2890b57cec5SDimitry Andric OldF->replaceAllUsesWith(Replacement); 2900b57cec5SDimitry Andric if (NewF) { 2910b57cec5SDimitry Andric NewF->removeFromParent(); 2920b57cec5SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2930b57cec5SDimitry Andric NewF); 2940b57cec5SDimitry Andric } 2950b57cec5SDimitry Andric OldF->eraseFromParent(); 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric } 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 3000b57cec5SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 3010b57cec5SDimitry Andric } 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 3040b57cec5SDimitry Andric for (auto &I : GlobalValReplacements) { 3050b57cec5SDimitry Andric llvm::GlobalValue *GV = I.first; 3060b57cec5SDimitry Andric llvm::Constant *C = I.second; 3070b57cec5SDimitry Andric 3080b57cec5SDimitry Andric GV->replaceAllUsesWith(C); 3090b57cec5SDimitry Andric GV->eraseFromParent(); 3100b57cec5SDimitry Andric } 3110b57cec5SDimitry Andric } 3120b57cec5SDimitry Andric 3130b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a 3140b57cec5SDimitry Andric // linear structure. 315349cc55cSDimitry Andric static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 316349cc55cSDimitry Andric const llvm::Constant *C; 317349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 318349cc55cSDimitry Andric C = GA->getAliasee(); 319349cc55cSDimitry Andric else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 320349cc55cSDimitry Andric C = GI->getResolver(); 321349cc55cSDimitry Andric else 322349cc55cSDimitry Andric return GV; 323349cc55cSDimitry Andric 324349cc55cSDimitry Andric const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 325349cc55cSDimitry Andric if (!AliaseeGV) 3260b57cec5SDimitry Andric return nullptr; 327349cc55cSDimitry Andric 328349cc55cSDimitry Andric const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 329349cc55cSDimitry Andric if (FinalGV == GV) 3300b57cec5SDimitry Andric return nullptr; 331349cc55cSDimitry Andric 332349cc55cSDimitry Andric return FinalGV; 3330b57cec5SDimitry Andric } 334349cc55cSDimitry Andric 335349cc55cSDimitry Andric static bool checkAliasedGlobal(DiagnosticsEngine &Diags, 336349cc55cSDimitry Andric SourceLocation Location, bool IsIFunc, 337349cc55cSDimitry Andric const llvm::GlobalValue *Alias, 338349cc55cSDimitry Andric const llvm::GlobalValue *&GV) { 339349cc55cSDimitry Andric GV = getAliasedGlobal(Alias); 340349cc55cSDimitry Andric if (!GV) { 341349cc55cSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 342349cc55cSDimitry Andric return false; 343349cc55cSDimitry Andric } 344349cc55cSDimitry Andric 345349cc55cSDimitry Andric if (GV->isDeclaration()) { 346349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 347349cc55cSDimitry Andric return false; 348349cc55cSDimitry Andric } 349349cc55cSDimitry Andric 350349cc55cSDimitry Andric if (IsIFunc) { 351349cc55cSDimitry Andric // Check resolver function type. 352349cc55cSDimitry Andric const auto *F = dyn_cast<llvm::Function>(GV); 353349cc55cSDimitry Andric if (!F) { 354349cc55cSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 355349cc55cSDimitry Andric << IsIFunc << IsIFunc; 356349cc55cSDimitry Andric return false; 357349cc55cSDimitry Andric } 358349cc55cSDimitry Andric 359349cc55cSDimitry Andric llvm::FunctionType *FTy = F->getFunctionType(); 360349cc55cSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) { 361349cc55cSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 362349cc55cSDimitry Andric return false; 363349cc55cSDimitry Andric } 364349cc55cSDimitry Andric } 365349cc55cSDimitry Andric 366349cc55cSDimitry Andric return true; 3670b57cec5SDimitry Andric } 3680b57cec5SDimitry Andric 3690b57cec5SDimitry Andric void CodeGenModule::checkAliases() { 3700b57cec5SDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 3710b57cec5SDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 3720b57cec5SDimitry Andric // and aliases during codegen. 3730b57cec5SDimitry Andric bool Error = false; 3740b57cec5SDimitry Andric DiagnosticsEngine &Diags = getDiags(); 3750b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 3760b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3770b57cec5SDimitry Andric SourceLocation Location; 3780b57cec5SDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 3790b57cec5SDimitry Andric if (const Attr *A = D->getDefiningAttr()) 3800b57cec5SDimitry Andric Location = A->getLocation(); 3810b57cec5SDimitry Andric else 3820b57cec5SDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 383349cc55cSDimitry Andric 3840b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 385349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 386349cc55cSDimitry Andric const llvm::GlobalValue *GV = nullptr; 387349cc55cSDimitry Andric if (!checkAliasedGlobal(Diags, Location, IsIFunc, Alias, GV)) { 3880b57cec5SDimitry Andric Error = true; 389349cc55cSDimitry Andric continue; 3900b57cec5SDimitry Andric } 3910b57cec5SDimitry Andric 392349cc55cSDimitry Andric llvm::Constant *Aliasee = 393349cc55cSDimitry Andric IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 394349cc55cSDimitry Andric : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 395349cc55cSDimitry Andric 3960b57cec5SDimitry Andric llvm::GlobalValue *AliaseeGV; 3970b57cec5SDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 3980b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 3990b57cec5SDimitry Andric else 4000b57cec5SDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4030b57cec5SDimitry Andric StringRef AliasSection = SA->getName(); 4040b57cec5SDimitry Andric if (AliasSection != AliaseeGV->getSection()) 4050b57cec5SDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 4060b57cec5SDimitry Andric << AliasSection << IsIFunc << IsIFunc; 4070b57cec5SDimitry Andric } 4080b57cec5SDimitry Andric 4090b57cec5SDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 4100b57cec5SDimitry Andric // this since the object semantics would not match the IL one. For 4110b57cec5SDimitry Andric // compatibility with gcc we implement it by just pointing the alias 4120b57cec5SDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 4130b57cec5SDimitry Andric // expecting the link to be weak. 414349cc55cSDimitry Andric if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 4150b57cec5SDimitry Andric if (GA->isInterposable()) { 4160b57cec5SDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 4170b57cec5SDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 4180b57cec5SDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 419349cc55cSDimitry Andric GA->getAliasee(), Alias->getType()); 420349cc55cSDimitry Andric 421349cc55cSDimitry Andric if (IsIFunc) 422349cc55cSDimitry Andric cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 423349cc55cSDimitry Andric else 424349cc55cSDimitry Andric cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 4250b57cec5SDimitry Andric } 4260b57cec5SDimitry Andric } 4270b57cec5SDimitry Andric } 4280b57cec5SDimitry Andric if (!Error) 4290b57cec5SDimitry Andric return; 4300b57cec5SDimitry Andric 4310b57cec5SDimitry Andric for (const GlobalDecl &GD : Aliases) { 4320b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 433349cc55cSDimitry Andric llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 4340b57cec5SDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 4350b57cec5SDimitry Andric Alias->eraseFromParent(); 4360b57cec5SDimitry Andric } 4370b57cec5SDimitry Andric } 4380b57cec5SDimitry Andric 4390b57cec5SDimitry Andric void CodeGenModule::clear() { 4400b57cec5SDimitry Andric DeferredDeclsToEmit.clear(); 4410b57cec5SDimitry Andric if (OpenMPRuntime) 4420b57cec5SDimitry Andric OpenMPRuntime->clear(); 4430b57cec5SDimitry Andric } 4440b57cec5SDimitry Andric 4450b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 4460b57cec5SDimitry Andric StringRef MainFile) { 4470b57cec5SDimitry Andric if (!hasDiagnostics()) 4480b57cec5SDimitry Andric return; 4490b57cec5SDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 4500b57cec5SDimitry Andric if (MainFile.empty()) 4510b57cec5SDimitry Andric MainFile = "<stdin>"; 4520b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 4530b57cec5SDimitry Andric } else { 4540b57cec5SDimitry Andric if (Mismatched > 0) 4550b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 4560b57cec5SDimitry Andric 4570b57cec5SDimitry Andric if (Missing > 0) 4580b57cec5SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 4590b57cec5SDimitry Andric } 4600b57cec5SDimitry Andric } 4610b57cec5SDimitry Andric 462e8d8bef9SDimitry Andric static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 463e8d8bef9SDimitry Andric llvm::Module &M) { 464e8d8bef9SDimitry Andric if (!LO.VisibilityFromDLLStorageClass) 465e8d8bef9SDimitry Andric return; 466e8d8bef9SDimitry Andric 467e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 468e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 469e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 470e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 471e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 472e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 473e8d8bef9SDimitry Andric llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 474e8d8bef9SDimitry Andric CodeGenModule::GetLLVMVisibility( 475e8d8bef9SDimitry Andric LO.getExternDeclNoDLLStorageClassVisibility()); 476e8d8bef9SDimitry Andric 477e8d8bef9SDimitry Andric for (llvm::GlobalValue &GV : M.global_values()) { 478e8d8bef9SDimitry Andric if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 479e8d8bef9SDimitry Andric continue; 480e8d8bef9SDimitry Andric 481e8d8bef9SDimitry Andric // Reset DSO locality before setting the visibility. This removes 482e8d8bef9SDimitry Andric // any effects that visibility options and annotations may have 483e8d8bef9SDimitry Andric // had on the DSO locality. Setting the visibility will implicitly set 484e8d8bef9SDimitry Andric // appropriate globals to DSO Local; however, this will be pessimistic 485e8d8bef9SDimitry Andric // w.r.t. to the normal compiler IRGen. 486e8d8bef9SDimitry Andric GV.setDSOLocal(false); 487e8d8bef9SDimitry Andric 488e8d8bef9SDimitry Andric if (GV.isDeclarationForLinker()) { 489e8d8bef9SDimitry Andric GV.setVisibility(GV.getDLLStorageClass() == 490e8d8bef9SDimitry Andric llvm::GlobalValue::DLLImportStorageClass 491e8d8bef9SDimitry Andric ? ExternDeclDLLImportVisibility 492e8d8bef9SDimitry Andric : ExternDeclNoDLLStorageClassVisibility); 493e8d8bef9SDimitry Andric } else { 494e8d8bef9SDimitry Andric GV.setVisibility(GV.getDLLStorageClass() == 495e8d8bef9SDimitry Andric llvm::GlobalValue::DLLExportStorageClass 496e8d8bef9SDimitry Andric ? DLLExportVisibility 497e8d8bef9SDimitry Andric : NoDLLStorageClassVisibility); 498e8d8bef9SDimitry Andric } 499e8d8bef9SDimitry Andric 500e8d8bef9SDimitry Andric GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 501e8d8bef9SDimitry Andric } 502e8d8bef9SDimitry Andric } 503e8d8bef9SDimitry Andric 5040b57cec5SDimitry Andric void CodeGenModule::Release() { 5050b57cec5SDimitry Andric EmitDeferred(); 5060b57cec5SDimitry Andric EmitVTablesOpportunistically(); 5070b57cec5SDimitry Andric applyGlobalValReplacements(); 5080b57cec5SDimitry Andric applyReplacements(); 5090b57cec5SDimitry Andric checkAliases(); 5100b57cec5SDimitry Andric emitMultiVersionFunctions(); 5110b57cec5SDimitry Andric EmitCXXGlobalInitFunc(); 5125ffd83dbSDimitry Andric EmitCXXGlobalCleanUpFunc(); 5130b57cec5SDimitry Andric registerGlobalDtorsWithAtExit(); 5140b57cec5SDimitry Andric EmitCXXThreadLocalInitFunc(); 5150b57cec5SDimitry Andric if (ObjCRuntime) 5160b57cec5SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 5170b57cec5SDimitry Andric AddGlobalCtor(ObjCInitFunction); 518fe6060f1SDimitry Andric if (Context.getLangOpts().CUDA && CUDARuntime) { 519fe6060f1SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 5200b57cec5SDimitry Andric AddGlobalCtor(CudaCtorFunction); 5210b57cec5SDimitry Andric } 5220b57cec5SDimitry Andric if (OpenMPRuntime) { 5230b57cec5SDimitry Andric if (llvm::Function *OpenMPRequiresDirectiveRegFun = 5240b57cec5SDimitry Andric OpenMPRuntime->emitRequiresDirectiveRegFun()) { 5250b57cec5SDimitry Andric AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 5260b57cec5SDimitry Andric } 527a7dea167SDimitry Andric OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 5280b57cec5SDimitry Andric OpenMPRuntime->clear(); 5290b57cec5SDimitry Andric } 5300b57cec5SDimitry Andric if (PGOReader) { 5310b57cec5SDimitry Andric getModule().setProfileSummary( 5320b57cec5SDimitry Andric PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 5330b57cec5SDimitry Andric llvm::ProfileSummary::PSK_Instr); 5340b57cec5SDimitry Andric if (PGOStats.hasDiagnostics()) 5350b57cec5SDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 5360b57cec5SDimitry Andric } 5370b57cec5SDimitry Andric EmitCtorList(GlobalCtors, "llvm.global_ctors"); 5380b57cec5SDimitry Andric EmitCtorList(GlobalDtors, "llvm.global_dtors"); 5390b57cec5SDimitry Andric EmitGlobalAnnotations(); 5400b57cec5SDimitry Andric EmitStaticExternCAliases(); 5410b57cec5SDimitry Andric EmitDeferredUnusedCoverageMappings(); 542fe6060f1SDimitry Andric CodeGenPGO(*this).setValueProfilingFlag(getModule()); 5430b57cec5SDimitry Andric if (CoverageMapping) 5440b57cec5SDimitry Andric CoverageMapping->emit(); 5450b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 5460b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 5470b57cec5SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 5480b57cec5SDimitry Andric } 5490b57cec5SDimitry Andric emitAtAvailableLinkGuard(); 5505ffd83dbSDimitry Andric if (Context.getTargetInfo().getTriple().isWasm() && 5515ffd83dbSDimitry Andric !Context.getTargetInfo().getTriple().isOSEmscripten()) { 5525ffd83dbSDimitry Andric EmitMainVoidAlias(); 5535ffd83dbSDimitry Andric } 554fe6060f1SDimitry Andric 555fe6060f1SDimitry Andric // Emit reference of __amdgpu_device_library_preserve_asan_functions to 556fe6060f1SDimitry Andric // preserve ASAN functions in bitcode libraries. 557fe6060f1SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Address) && getTriple().isAMDGPU()) { 558fe6060f1SDimitry Andric auto *FT = llvm::FunctionType::get(VoidTy, {}); 559fe6060f1SDimitry Andric auto *F = llvm::Function::Create( 560fe6060f1SDimitry Andric FT, llvm::GlobalValue::ExternalLinkage, 561fe6060f1SDimitry Andric "__amdgpu_device_library_preserve_asan_functions", &getModule()); 562fe6060f1SDimitry Andric auto *Var = new llvm::GlobalVariable( 563fe6060f1SDimitry Andric getModule(), FT->getPointerTo(), 564fe6060f1SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, F, 565fe6060f1SDimitry Andric "__amdgpu_device_library_preserve_asan_functions_ptr", nullptr, 566fe6060f1SDimitry Andric llvm::GlobalVariable::NotThreadLocal); 567fe6060f1SDimitry Andric addCompilerUsedGlobal(Var); 56804eeddc0SDimitry Andric if (!getModule().getModuleFlag("amdgpu_hostcall")) { 569349cc55cSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "amdgpu_hostcall", 1); 570fe6060f1SDimitry Andric } 57104eeddc0SDimitry Andric } 572fe6060f1SDimitry Andric 5730b57cec5SDimitry Andric emitLLVMUsed(); 5740b57cec5SDimitry Andric if (SanStats) 5750b57cec5SDimitry Andric SanStats->finish(); 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric if (CodeGenOpts.Autolink && 5780b57cec5SDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 5790b57cec5SDimitry Andric EmitModuleLinkOptions(); 5800b57cec5SDimitry Andric } 5810b57cec5SDimitry Andric 5820b57cec5SDimitry Andric // On ELF we pass the dependent library specifiers directly to the linker 5830b57cec5SDimitry Andric // without manipulating them. This is in contrast to other platforms where 5840b57cec5SDimitry Andric // they are mapped to a specific linker option by the compiler. This 5850b57cec5SDimitry Andric // difference is a result of the greater variety of ELF linkers and the fact 5860b57cec5SDimitry Andric // that ELF linkers tend to handle libraries in a more complicated fashion 5870b57cec5SDimitry Andric // than on other platforms. This forces us to defer handling the dependent 5880b57cec5SDimitry Andric // libs to the linker. 5890b57cec5SDimitry Andric // 5900b57cec5SDimitry Andric // CUDA/HIP device and host libraries are different. Currently there is no 5910b57cec5SDimitry Andric // way to differentiate dependent libraries for host or device. Existing 5920b57cec5SDimitry Andric // usage of #pragma comment(lib, *) is intended for host libraries on 5930b57cec5SDimitry Andric // Windows. Therefore emit llvm.dependent-libraries only for host. 5940b57cec5SDimitry Andric if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 5950b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 5960b57cec5SDimitry Andric for (auto *MD : ELFDependentLibraries) 5970b57cec5SDimitry Andric NMD->addOperand(MD); 5980b57cec5SDimitry Andric } 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 6010b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 6020b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 6030b57cec5SDimitry Andric CodeGenOpts.NumRegisterParameters); 6040b57cec5SDimitry Andric 6050b57cec5SDimitry Andric if (CodeGenOpts.DwarfVersion) { 606480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 6070b57cec5SDimitry Andric CodeGenOpts.DwarfVersion); 6080b57cec5SDimitry Andric } 6095ffd83dbSDimitry Andric 610fe6060f1SDimitry Andric if (CodeGenOpts.Dwarf64) 611fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 612fe6060f1SDimitry Andric 6135ffd83dbSDimitry Andric if (Context.getLangOpts().SemanticInterposition) 6145ffd83dbSDimitry Andric // Require various optimization to respect semantic interposition. 61504eeddc0SDimitry Andric getModule().setSemanticInterposition(true); 6165ffd83dbSDimitry Andric 6170b57cec5SDimitry Andric if (CodeGenOpts.EmitCodeView) { 6180b57cec5SDimitry Andric // Indicate that we want CodeView in the metadata. 6190b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric if (CodeGenOpts.CodeViewGHash) { 6220b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 6230b57cec5SDimitry Andric } 6240b57cec5SDimitry Andric if (CodeGenOpts.ControlFlowGuard) { 625480093f4SDimitry Andric // Function ID tables and checks for Control Flow Guard (cfguard=2). 626480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 627480093f4SDimitry Andric } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 628480093f4SDimitry Andric // Function ID tables for Control Flow Guard (cfguard=1). 629480093f4SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 6300b57cec5SDimitry Andric } 631fe6060f1SDimitry Andric if (CodeGenOpts.EHContGuard) { 632fe6060f1SDimitry Andric // Function ID tables for EH Continuation Guard. 633fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 634fe6060f1SDimitry Andric } 6350b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 6360b57cec5SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 6370b57cec5SDimitry Andric // FIXME: we could support it by stripping all the information introduced 6380b57cec5SDimitry Andric // by StrictVTablePointers. 6390b57cec5SDimitry Andric 6400b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 6410b57cec5SDimitry Andric 6420b57cec5SDimitry Andric llvm::Metadata *Ops[2] = { 6430b57cec5SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 6440b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 6450b57cec5SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 6480b57cec5SDimitry Andric "StrictVTablePointersRequirement", 6490b57cec5SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 6500b57cec5SDimitry Andric } 6515ffd83dbSDimitry Andric if (getModuleDebugInfo()) 6520b57cec5SDimitry Andric // We support a single version in the linked module. The LLVM 6530b57cec5SDimitry Andric // parser will drop debug info with a different version number 6540b57cec5SDimitry Andric // (and warn about it, too). 6550b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 6560b57cec5SDimitry Andric llvm::DEBUG_METADATA_VERSION); 6570b57cec5SDimitry Andric 6580b57cec5SDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 6590b57cec5SDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 6600b57cec5SDimitry Andric // TargetLibraryInfo. 6610b57cec5SDimitry Andric uint64_t WCharWidth = 6620b57cec5SDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 6630b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 6640b57cec5SDimitry Andric 6650b57cec5SDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 6660b57cec5SDimitry Andric if ( Arch == llvm::Triple::arm 6670b57cec5SDimitry Andric || Arch == llvm::Triple::armeb 6680b57cec5SDimitry Andric || Arch == llvm::Triple::thumb 6690b57cec5SDimitry Andric || Arch == llvm::Triple::thumbeb) { 6700b57cec5SDimitry Andric // The minimum width of an enum in bytes 6710b57cec5SDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 6720b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 6730b57cec5SDimitry Andric } 6740b57cec5SDimitry Andric 67513138422SDimitry Andric if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 67613138422SDimitry Andric StringRef ABIStr = Target.getABI(); 67713138422SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 67813138422SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "target-abi", 67913138422SDimitry Andric llvm::MDString::get(Ctx, ABIStr)); 68013138422SDimitry Andric } 68113138422SDimitry Andric 6820b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 6830b57cec5SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 6840b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 6850b57cec5SDimitry Andric } 6860b57cec5SDimitry Andric 6875ffd83dbSDimitry Andric if (CodeGenOpts.WholeProgramVTables) { 6885ffd83dbSDimitry Andric // Indicate whether VFE was enabled for this module, so that the 6895ffd83dbSDimitry Andric // vcall_visibility metadata added under whole program vtables is handled 6905ffd83dbSDimitry Andric // appropriately in the optimizer. 6915ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 6925ffd83dbSDimitry Andric CodeGenOpts.VirtualFunctionElimination); 6935ffd83dbSDimitry Andric } 6945ffd83dbSDimitry Andric 695a7dea167SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 696a7dea167SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 697a7dea167SDimitry Andric "CFI Canonical Jump Tables", 698a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables); 699a7dea167SDimitry Andric } 700a7dea167SDimitry Andric 7010b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionReturn && 7020b57cec5SDimitry Andric Target.checkCFProtectionReturnSupported(getDiags())) { 7030b57cec5SDimitry Andric // Indicate that we want to instrument return control flow protection. 7040b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 7050b57cec5SDimitry Andric 1); 7060b57cec5SDimitry Andric } 7070b57cec5SDimitry Andric 7080b57cec5SDimitry Andric if (CodeGenOpts.CFProtectionBranch && 7090b57cec5SDimitry Andric Target.checkCFProtectionBranchSupported(getDiags())) { 7100b57cec5SDimitry Andric // Indicate that we want to instrument branch control flow protection. 7110b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 7120b57cec5SDimitry Andric 1); 7130b57cec5SDimitry Andric } 7140b57cec5SDimitry Andric 71504eeddc0SDimitry Andric if (CodeGenOpts.IBTSeal) 71604eeddc0SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "ibt-seal", 1); 71704eeddc0SDimitry Andric 7184824e7fdSDimitry Andric // Add module metadata for return address signing (ignoring 7194824e7fdSDimitry Andric // non-leaf/all) and stack tagging. These are actually turned on by function 7204824e7fdSDimitry Andric // attributes, but we use module metadata to emit build attributes. This is 7214824e7fdSDimitry Andric // needed for LTO, where the function attributes are inside bitcode 7224824e7fdSDimitry Andric // serialised into a global variable by the time build attributes are 7234824e7fdSDimitry Andric // emitted, so we can't access them. 7244824e7fdSDimitry Andric if (Context.getTargetInfo().hasFeature("ptrauth") && 7254824e7fdSDimitry Andric LangOpts.getSignReturnAddressScope() != 7264824e7fdSDimitry Andric LangOptions::SignReturnAddressScopeKind::None) 7274824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 7284824e7fdSDimitry Andric "sign-return-address-buildattr", 1); 7294824e7fdSDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) 7304824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, 7314824e7fdSDimitry Andric "tag-stack-memory-buildattr", 1); 7324824e7fdSDimitry Andric 7334824e7fdSDimitry Andric if (Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb || 7341fd87a68SDimitry Andric Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb || 7354824e7fdSDimitry Andric Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 736e8d8bef9SDimitry Andric Arch == llvm::Triple::aarch64_be) { 7374824e7fdSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "branch-target-enforcement", 738e8d8bef9SDimitry Andric LangOpts.BranchTargetEnforcement); 739e8d8bef9SDimitry Andric 740e8d8bef9SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "sign-return-address", 741e8d8bef9SDimitry Andric LangOpts.hasSignReturnAddress()); 742e8d8bef9SDimitry Andric 743e8d8bef9SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all", 744e8d8bef9SDimitry Andric LangOpts.isSignReturnAddressScopeAll()); 745e8d8bef9SDimitry Andric 746e8d8bef9SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, 747e8d8bef9SDimitry Andric "sign-return-address-with-bkey", 748e8d8bef9SDimitry Andric !LangOpts.isSignReturnAddressWithAKey()); 749e8d8bef9SDimitry Andric } 750e8d8bef9SDimitry Andric 751e8d8bef9SDimitry Andric if (!CodeGenOpts.MemoryProfileOutput.empty()) { 752e8d8bef9SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 753e8d8bef9SDimitry Andric getModule().addModuleFlag( 754e8d8bef9SDimitry Andric llvm::Module::Error, "MemProfProfileFilename", 755e8d8bef9SDimitry Andric llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 756e8d8bef9SDimitry Andric } 757e8d8bef9SDimitry Andric 7580b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 7590b57cec5SDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 7600b57cec5SDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 7610b57cec5SDimitry Andric // property.) 7620b57cec5SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 7635ffd83dbSDimitry Andric CodeGenOpts.FP32DenormalMode.Output != 7645ffd83dbSDimitry Andric llvm::DenormalMode::IEEE); 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 767fe6060f1SDimitry Andric if (LangOpts.EHAsynch) 768fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 769fe6060f1SDimitry Andric 770fe6060f1SDimitry Andric // Indicate whether this Module was compiled with -fopenmp 771fe6060f1SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 772fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 773fe6060f1SDimitry Andric if (getLangOpts().OpenMPIsDevice) 774fe6060f1SDimitry Andric getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 775fe6060f1SDimitry Andric LangOpts.OpenMP); 776fe6060f1SDimitry Andric 7770b57cec5SDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 7780b57cec5SDimitry Andric if (LangOpts.OpenCL) { 7790b57cec5SDimitry Andric EmitOpenCLMetadata(); 7800b57cec5SDimitry Andric // Emit SPIR version. 7810b57cec5SDimitry Andric if (getTriple().isSPIR()) { 7820b57cec5SDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 7830b57cec5SDimitry Andric // opencl.spir.version named metadata. 784349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for version compatibility with 785349cc55cSDimitry Andric // OpenCL. 786349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 7870b57cec5SDimitry Andric llvm::Metadata *SPIRVerElts[] = { 7880b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 7890b57cec5SDimitry Andric Int32Ty, Version / 100)), 7900b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 7910b57cec5SDimitry Andric Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 7920b57cec5SDimitry Andric llvm::NamedMDNode *SPIRVerMD = 7930b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 7940b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 7950b57cec5SDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 7960b57cec5SDimitry Andric } 7970b57cec5SDimitry Andric } 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 8000b57cec5SDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 8010b57cec5SDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 8020b57cec5SDimitry Andric if (Context.getLangOpts().PIE) 8030b57cec5SDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 8040b57cec5SDimitry Andric } 8050b57cec5SDimitry Andric 8060b57cec5SDimitry Andric if (getCodeGenOpts().CodeModel.size() > 0) { 8070b57cec5SDimitry Andric unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 8080b57cec5SDimitry Andric .Case("tiny", llvm::CodeModel::Tiny) 8090b57cec5SDimitry Andric .Case("small", llvm::CodeModel::Small) 8100b57cec5SDimitry Andric .Case("kernel", llvm::CodeModel::Kernel) 8110b57cec5SDimitry Andric .Case("medium", llvm::CodeModel::Medium) 8120b57cec5SDimitry Andric .Case("large", llvm::CodeModel::Large) 8130b57cec5SDimitry Andric .Default(~0u); 8140b57cec5SDimitry Andric if (CM != ~0u) { 8150b57cec5SDimitry Andric llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 8160b57cec5SDimitry Andric getModule().setCodeModel(codeModel); 8170b57cec5SDimitry Andric } 8180b57cec5SDimitry Andric } 8190b57cec5SDimitry Andric 8200b57cec5SDimitry Andric if (CodeGenOpts.NoPLT) 8210b57cec5SDimitry Andric getModule().setRtLibUseGOT(); 822fe6060f1SDimitry Andric if (CodeGenOpts.UnwindTables) 823fe6060f1SDimitry Andric getModule().setUwtable(); 824fe6060f1SDimitry Andric 825fe6060f1SDimitry Andric switch (CodeGenOpts.getFramePointer()) { 826fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::None: 827fe6060f1SDimitry Andric // 0 ("none") is the default. 828fe6060f1SDimitry Andric break; 829fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::NonLeaf: 830fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 831fe6060f1SDimitry Andric break; 832fe6060f1SDimitry Andric case CodeGenOptions::FramePointerKind::All: 833fe6060f1SDimitry Andric getModule().setFramePointer(llvm::FramePointerKind::All); 834fe6060f1SDimitry Andric break; 835fe6060f1SDimitry Andric } 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric SimplifyPersonality(); 8380b57cec5SDimitry Andric 8390b57cec5SDimitry Andric if (getCodeGenOpts().EmitDeclMetadata) 8400b57cec5SDimitry Andric EmitDeclMetadata(); 8410b57cec5SDimitry Andric 8420b57cec5SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 8430b57cec5SDimitry Andric EmitCoverageFile(); 8440b57cec5SDimitry Andric 8455ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 8465ffd83dbSDimitry Andric DI->finalize(); 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric if (getCodeGenOpts().EmitVersionIdentMetadata) 8490b57cec5SDimitry Andric EmitVersionIdentMetadata(); 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric if (!getCodeGenOpts().RecordCommandLine.empty()) 8520b57cec5SDimitry Andric EmitCommandLineMetadata(); 8530b57cec5SDimitry Andric 854fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuard.empty()) 855fe6060f1SDimitry Andric getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 856fe6060f1SDimitry Andric if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 857fe6060f1SDimitry Andric getModule().setStackProtectorGuardReg( 858fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardReg); 859fe6060f1SDimitry Andric if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 860fe6060f1SDimitry Andric getModule().setStackProtectorGuardOffset( 861fe6060f1SDimitry Andric getCodeGenOpts().StackProtectorGuardOffset); 862fe6060f1SDimitry Andric if (getCodeGenOpts().StackAlignment) 863fe6060f1SDimitry Andric getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 864349cc55cSDimitry Andric if (getCodeGenOpts().SkipRaxSetup) 865349cc55cSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 866fe6060f1SDimitry Andric 8675ffd83dbSDimitry Andric getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 8685ffd83dbSDimitry Andric 8695ffd83dbSDimitry Andric EmitBackendOptionsMetadata(getCodeGenOpts()); 870e8d8bef9SDimitry Andric 871e8d8bef9SDimitry Andric // Set visibility from DLL storage class 872e8d8bef9SDimitry Andric // We do this at the end of LLVM IR generation; after any operation 873e8d8bef9SDimitry Andric // that might affect the DLL storage class or the visibility, and 874e8d8bef9SDimitry Andric // before anything that might act on these. 875e8d8bef9SDimitry Andric setVisibilityFromDLLStorageClass(LangOpts, getModule()); 8760b57cec5SDimitry Andric } 8770b57cec5SDimitry Andric 8780b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 8790b57cec5SDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 8800b57cec5SDimitry Andric // opencl.ocl.version named metadata node. 881349cc55cSDimitry Andric // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 882349cc55cSDimitry Andric auto Version = LangOpts.getOpenCLCompatibleVersion(); 8830b57cec5SDimitry Andric llvm::Metadata *OCLVerElts[] = { 8840b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 8850b57cec5SDimitry Andric Int32Ty, Version / 100)), 8860b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 8870b57cec5SDimitry Andric Int32Ty, (Version % 100) / 10))}; 8880b57cec5SDimitry Andric llvm::NamedMDNode *OCLVerMD = 8890b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 8900b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 8910b57cec5SDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 8920b57cec5SDimitry Andric } 8930b57cec5SDimitry Andric 8945ffd83dbSDimitry Andric void CodeGenModule::EmitBackendOptionsMetadata( 8955ffd83dbSDimitry Andric const CodeGenOptions CodeGenOpts) { 8965ffd83dbSDimitry Andric switch (getTriple().getArch()) { 8975ffd83dbSDimitry Andric default: 8985ffd83dbSDimitry Andric break; 8995ffd83dbSDimitry Andric case llvm::Triple::riscv32: 9005ffd83dbSDimitry Andric case llvm::Triple::riscv64: 9015ffd83dbSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 9025ffd83dbSDimitry Andric CodeGenOpts.SmallDataLimit); 9035ffd83dbSDimitry Andric break; 9045ffd83dbSDimitry Andric } 9055ffd83dbSDimitry Andric } 9065ffd83dbSDimitry Andric 9070b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 9080b57cec5SDimitry Andric // Make sure that this type is translated. 9090b57cec5SDimitry Andric Types.UpdateCompletedType(TD); 9100b57cec5SDimitry Andric } 9110b57cec5SDimitry Andric 9120b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 9130b57cec5SDimitry Andric // Make sure that this type is translated. 9140b57cec5SDimitry Andric Types.RefreshTypeCacheForClass(RD); 9150b57cec5SDimitry Andric } 9160b57cec5SDimitry Andric 9170b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 9180b57cec5SDimitry Andric if (!TBAA) 9190b57cec5SDimitry Andric return nullptr; 9200b57cec5SDimitry Andric return TBAA->getTypeInfo(QTy); 9210b57cec5SDimitry Andric } 9220b57cec5SDimitry Andric 9230b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 9240b57cec5SDimitry Andric if (!TBAA) 9250b57cec5SDimitry Andric return TBAAAccessInfo(); 9265ffd83dbSDimitry Andric if (getLangOpts().CUDAIsDevice) { 9275ffd83dbSDimitry Andric // As CUDA builtin surface/texture types are replaced, skip generating TBAA 9285ffd83dbSDimitry Andric // access info. 9295ffd83dbSDimitry Andric if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 9305ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 9315ffd83dbSDimitry Andric nullptr) 9325ffd83dbSDimitry Andric return TBAAAccessInfo(); 9335ffd83dbSDimitry Andric } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 9345ffd83dbSDimitry Andric if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 9355ffd83dbSDimitry Andric nullptr) 9365ffd83dbSDimitry Andric return TBAAAccessInfo(); 9375ffd83dbSDimitry Andric } 9385ffd83dbSDimitry Andric } 9390b57cec5SDimitry Andric return TBAA->getAccessInfo(AccessType); 9400b57cec5SDimitry Andric } 9410b57cec5SDimitry Andric 9420b57cec5SDimitry Andric TBAAAccessInfo 9430b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 9440b57cec5SDimitry Andric if (!TBAA) 9450b57cec5SDimitry Andric return TBAAAccessInfo(); 9460b57cec5SDimitry Andric return TBAA->getVTablePtrAccessInfo(VTablePtrType); 9470b57cec5SDimitry Andric } 9480b57cec5SDimitry Andric 9490b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 9500b57cec5SDimitry Andric if (!TBAA) 9510b57cec5SDimitry Andric return nullptr; 9520b57cec5SDimitry Andric return TBAA->getTBAAStructInfo(QTy); 9530b57cec5SDimitry Andric } 9540b57cec5SDimitry Andric 9550b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 9560b57cec5SDimitry Andric if (!TBAA) 9570b57cec5SDimitry Andric return nullptr; 9580b57cec5SDimitry Andric return TBAA->getBaseTypeInfo(QTy); 9590b57cec5SDimitry Andric } 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 9620b57cec5SDimitry Andric if (!TBAA) 9630b57cec5SDimitry Andric return nullptr; 9640b57cec5SDimitry Andric return TBAA->getAccessTagInfo(Info); 9650b57cec5SDimitry Andric } 9660b57cec5SDimitry Andric 9670b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 9680b57cec5SDimitry Andric TBAAAccessInfo TargetInfo) { 9690b57cec5SDimitry Andric if (!TBAA) 9700b57cec5SDimitry Andric return TBAAAccessInfo(); 9710b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric 9740b57cec5SDimitry Andric TBAAAccessInfo 9750b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 9760b57cec5SDimitry Andric TBAAAccessInfo InfoB) { 9770b57cec5SDimitry Andric if (!TBAA) 9780b57cec5SDimitry Andric return TBAAAccessInfo(); 9790b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 9800b57cec5SDimitry Andric } 9810b57cec5SDimitry Andric 9820b57cec5SDimitry Andric TBAAAccessInfo 9830b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 9840b57cec5SDimitry Andric TBAAAccessInfo SrcInfo) { 9850b57cec5SDimitry Andric if (!TBAA) 9860b57cec5SDimitry Andric return TBAAAccessInfo(); 9870b57cec5SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 9880b57cec5SDimitry Andric } 9890b57cec5SDimitry Andric 9900b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 9910b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo) { 9920b57cec5SDimitry Andric if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 9930b57cec5SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 9940b57cec5SDimitry Andric } 9950b57cec5SDimitry Andric 9960b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 9970b57cec5SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 9980b57cec5SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 9990b57cec5SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 10000b57cec5SDimitry Andric } 10010b57cec5SDimitry Andric 10020b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 10030b57cec5SDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 10040b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 10050b57cec5SDimitry Andric } 10060b57cec5SDimitry Andric 10070b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 10080b57cec5SDimitry Andric /// specified stmt yet. 10090b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 10100b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 10110b57cec5SDimitry Andric "cannot compile this %0 yet"); 10120b57cec5SDimitry Andric std::string Msg = Type; 10130b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 10140b57cec5SDimitry Andric << Msg << S->getSourceRange(); 10150b57cec5SDimitry Andric } 10160b57cec5SDimitry Andric 10170b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 10180b57cec5SDimitry Andric /// specified decl yet. 10190b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 10200b57cec5SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 10210b57cec5SDimitry Andric "cannot compile this %0 yet"); 10220b57cec5SDimitry Andric std::string Msg = Type; 10230b57cec5SDimitry Andric getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 10240b57cec5SDimitry Andric } 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 10270b57cec5SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 10280b57cec5SDimitry Andric } 10290b57cec5SDimitry Andric 10300b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 10310b57cec5SDimitry Andric const NamedDecl *D) const { 10320b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 10330b57cec5SDimitry Andric return; 10340b57cec5SDimitry Andric // Internal definitions always have default visibility. 10350b57cec5SDimitry Andric if (GV->hasLocalLinkage()) { 10360b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 10370b57cec5SDimitry Andric return; 10380b57cec5SDimitry Andric } 10390b57cec5SDimitry Andric if (!D) 10400b57cec5SDimitry Andric return; 10410b57cec5SDimitry Andric // Set visibility for definitions, and for declarations if requested globally 10420b57cec5SDimitry Andric // or set explicitly. 10430b57cec5SDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 10440b57cec5SDimitry Andric if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 10450b57cec5SDimitry Andric !GV->isDeclarationForLinker()) 10460b57cec5SDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 10470b57cec5SDimitry Andric } 10480b57cec5SDimitry Andric 10490b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 10500b57cec5SDimitry Andric llvm::GlobalValue *GV) { 10510b57cec5SDimitry Andric if (GV->hasLocalLinkage()) 10520b57cec5SDimitry Andric return true; 10530b57cec5SDimitry Andric 10540b57cec5SDimitry Andric if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 10550b57cec5SDimitry Andric return true; 10560b57cec5SDimitry Andric 10570b57cec5SDimitry Andric // DLLImport explicitly marks the GV as external. 10580b57cec5SDimitry Andric if (GV->hasDLLImportStorageClass()) 10590b57cec5SDimitry Andric return false; 10600b57cec5SDimitry Andric 10610b57cec5SDimitry Andric const llvm::Triple &TT = CGM.getTriple(); 10620b57cec5SDimitry Andric if (TT.isWindowsGNUEnvironment()) { 10630b57cec5SDimitry Andric // In MinGW, variables without DLLImport can still be automatically 10640b57cec5SDimitry Andric // imported from a DLL by the linker; don't mark variables that 10650b57cec5SDimitry Andric // potentially could come from another DLL as DSO local. 1066fe6060f1SDimitry Andric 1067fe6060f1SDimitry Andric // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1068fe6060f1SDimitry Andric // (and this actually happens in the public interface of libstdc++), so 1069fe6060f1SDimitry Andric // such variables can't be marked as DSO local. (Native TLS variables 1070fe6060f1SDimitry Andric // can't be dllimported at all, though.) 10710b57cec5SDimitry Andric if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1072fe6060f1SDimitry Andric (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS)) 10730b57cec5SDimitry Andric return false; 10740b57cec5SDimitry Andric } 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 10770b57cec5SDimitry Andric // remain unresolved in the link, they can be resolved to zero, which is 10780b57cec5SDimitry Andric // outside the current DSO. 10790b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 10800b57cec5SDimitry Andric return false; 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric // Every other GV is local on COFF. 10830b57cec5SDimitry Andric // Make an exception for windows OS in the triple: Some firmware builds use 10840b57cec5SDimitry Andric // *-win32-macho triples. This (accidentally?) produced windows relocations 10850b57cec5SDimitry Andric // without GOT tables in older clang versions; Keep this behaviour. 10860b57cec5SDimitry Andric // FIXME: even thread local variables? 10870b57cec5SDimitry Andric if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 10880b57cec5SDimitry Andric return true; 10890b57cec5SDimitry Andric 10900b57cec5SDimitry Andric // Only handle COFF and ELF for now. 10910b57cec5SDimitry Andric if (!TT.isOSBinFormatELF()) 10920b57cec5SDimitry Andric return false; 10930b57cec5SDimitry Andric 1094fe6060f1SDimitry Andric // If this is not an executable, don't assume anything is local. 1095fe6060f1SDimitry Andric const auto &CGOpts = CGM.getCodeGenOpts(); 1096fe6060f1SDimitry Andric llvm::Reloc::Model RM = CGOpts.RelocationModel; 1097fe6060f1SDimitry Andric const auto &LOpts = CGM.getLangOpts(); 1098e8d8bef9SDimitry Andric if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1099e8d8bef9SDimitry Andric // On ELF, if -fno-semantic-interposition is specified and the target 1100e8d8bef9SDimitry Andric // supports local aliases, there will be neither CC1 1101e8d8bef9SDimitry Andric // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1102fe6060f1SDimitry Andric // dso_local on the function if using a local alias is preferable (can avoid 1103fe6060f1SDimitry Andric // PLT indirection). 1104fe6060f1SDimitry Andric if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 11050b57cec5SDimitry Andric return false; 1106e8d8bef9SDimitry Andric return !(CGM.getLangOpts().SemanticInterposition || 1107e8d8bef9SDimitry Andric CGM.getLangOpts().HalfNoSemanticInterposition); 1108e8d8bef9SDimitry Andric } 11090b57cec5SDimitry Andric 11100b57cec5SDimitry Andric // A definition cannot be preempted from an executable. 11110b57cec5SDimitry Andric if (!GV->isDeclarationForLinker()) 11120b57cec5SDimitry Andric return true; 11130b57cec5SDimitry Andric 11140b57cec5SDimitry Andric // Most PIC code sequences that assume that a symbol is local cannot produce a 11150b57cec5SDimitry Andric // 0 if it turns out the symbol is undefined. While this is ABI and relocation 11160b57cec5SDimitry Andric // depended, it seems worth it to handle it here. 11170b57cec5SDimitry Andric if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 11180b57cec5SDimitry Andric return false; 11190b57cec5SDimitry Andric 1120e8d8bef9SDimitry Andric // PowerPC64 prefers TOC indirection to avoid copy relocations. 1121e8d8bef9SDimitry Andric if (TT.isPPC64()) 11220b57cec5SDimitry Andric return false; 11230b57cec5SDimitry Andric 1124e8d8bef9SDimitry Andric if (CGOpts.DirectAccessExternalData) { 1125e8d8bef9SDimitry Andric // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1126e8d8bef9SDimitry Andric // for non-thread-local variables. If the symbol is not defined in the 1127e8d8bef9SDimitry Andric // executable, a copy relocation will be needed at link time. dso_local is 1128e8d8bef9SDimitry Andric // excluded for thread-local variables because they generally don't support 1129e8d8bef9SDimitry Andric // copy relocations. 11300b57cec5SDimitry Andric if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1131e8d8bef9SDimitry Andric if (!Var->isThreadLocal()) 11320b57cec5SDimitry Andric return true; 11330b57cec5SDimitry Andric 1134e8d8bef9SDimitry Andric // -fno-pic sets dso_local on a function declaration to allow direct 1135e8d8bef9SDimitry Andric // accesses when taking its address (similar to a data symbol). If the 1136e8d8bef9SDimitry Andric // function is not defined in the executable, a canonical PLT entry will be 1137e8d8bef9SDimitry Andric // needed at link time. -fno-direct-access-external-data can avoid the 1138e8d8bef9SDimitry Andric // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1139e8d8bef9SDimitry Andric // it could just cause trouble without providing perceptible benefits. 11400b57cec5SDimitry Andric if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 11410b57cec5SDimitry Andric return true; 1142e8d8bef9SDimitry Andric } 1143e8d8bef9SDimitry Andric 1144e8d8bef9SDimitry Andric // If we can use copy relocations we can assume it is local. 11450b57cec5SDimitry Andric 11465ffd83dbSDimitry Andric // Otherwise don't assume it is local. 11470b57cec5SDimitry Andric return false; 11480b57cec5SDimitry Andric } 11490b57cec5SDimitry Andric 11500b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 11510b57cec5SDimitry Andric GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 11520b57cec5SDimitry Andric } 11530b57cec5SDimitry Andric 11540b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 11550b57cec5SDimitry Andric GlobalDecl GD) const { 11560b57cec5SDimitry Andric const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 11570b57cec5SDimitry Andric // C++ destructors have a few C++ ABI specific special cases. 11580b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 11590b57cec5SDimitry Andric getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 11600b57cec5SDimitry Andric return; 11610b57cec5SDimitry Andric } 11620b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 11630b57cec5SDimitry Andric } 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 11660b57cec5SDimitry Andric const NamedDecl *D) const { 11670b57cec5SDimitry Andric if (D && D->isExternallyVisible()) { 11680b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 11690b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 11700b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 11710b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 11720b57cec5SDimitry Andric } 11730b57cec5SDimitry Andric } 11740b57cec5SDimitry Andric 11750b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 11760b57cec5SDimitry Andric GlobalDecl GD) const { 11770b57cec5SDimitry Andric setDLLImportDLLExport(GV, GD); 11780b57cec5SDimitry Andric setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 11790b57cec5SDimitry Andric } 11800b57cec5SDimitry Andric 11810b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 11820b57cec5SDimitry Andric const NamedDecl *D) const { 11830b57cec5SDimitry Andric setDLLImportDLLExport(GV, D); 11840b57cec5SDimitry Andric setGVPropertiesAux(GV, D); 11850b57cec5SDimitry Andric } 11860b57cec5SDimitry Andric 11870b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 11880b57cec5SDimitry Andric const NamedDecl *D) const { 11890b57cec5SDimitry Andric setGlobalVisibility(GV, D); 11900b57cec5SDimitry Andric setDSOLocal(GV); 11910b57cec5SDimitry Andric GV->setPartition(CodeGenOpts.SymbolPartition); 11920b57cec5SDimitry Andric } 11930b57cec5SDimitry Andric 11940b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 11950b57cec5SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 11960b57cec5SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 11970b57cec5SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 11980b57cec5SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 11990b57cec5SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 12000b57cec5SDimitry Andric } 12010b57cec5SDimitry Andric 12025ffd83dbSDimitry Andric llvm::GlobalVariable::ThreadLocalMode 12035ffd83dbSDimitry Andric CodeGenModule::GetDefaultLLVMTLSModel() const { 12045ffd83dbSDimitry Andric switch (CodeGenOpts.getDefaultTLSModel()) { 12050b57cec5SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 12060b57cec5SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 12070b57cec5SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 12080b57cec5SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 12090b57cec5SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 12100b57cec5SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 12110b57cec5SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 12120b57cec5SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 12130b57cec5SDimitry Andric } 12140b57cec5SDimitry Andric llvm_unreachable("Invalid TLS model!"); 12150b57cec5SDimitry Andric } 12160b57cec5SDimitry Andric 12170b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 12180b57cec5SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 12190b57cec5SDimitry Andric 12200b57cec5SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 12215ffd83dbSDimitry Andric TLM = GetDefaultLLVMTLSModel(); 12220b57cec5SDimitry Andric 12230b57cec5SDimitry Andric // Override the TLS model if it is explicitly specified. 12240b57cec5SDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 12250b57cec5SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 12260b57cec5SDimitry Andric } 12270b57cec5SDimitry Andric 12280b57cec5SDimitry Andric GV->setThreadLocalMode(TLM); 12290b57cec5SDimitry Andric } 12300b57cec5SDimitry Andric 12310b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 12320b57cec5SDimitry Andric StringRef Name) { 12330b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 12340b57cec5SDimitry Andric return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 12350b57cec5SDimitry Andric } 12360b57cec5SDimitry Andric 12370b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 12380b57cec5SDimitry Andric const CPUSpecificAttr *Attr, 12390b57cec5SDimitry Andric unsigned CPUIndex, 12400b57cec5SDimitry Andric raw_ostream &Out) { 12410b57cec5SDimitry Andric // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 12420b57cec5SDimitry Andric // supported. 12430b57cec5SDimitry Andric if (Attr) 12440b57cec5SDimitry Andric Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 12450b57cec5SDimitry Andric else if (CGM.getTarget().supportsIFunc()) 12460b57cec5SDimitry Andric Out << ".resolver"; 12470b57cec5SDimitry Andric } 12480b57cec5SDimitry Andric 12490b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM, 12500b57cec5SDimitry Andric const TargetAttr *Attr, raw_ostream &Out) { 12510b57cec5SDimitry Andric if (Attr->isDefaultVersion()) 12520b57cec5SDimitry Andric return; 12530b57cec5SDimitry Andric 12540b57cec5SDimitry Andric Out << '.'; 12550b57cec5SDimitry Andric const TargetInfo &Target = CGM.getTarget(); 1256480093f4SDimitry Andric ParsedTargetAttr Info = 12570b57cec5SDimitry Andric Attr->parse([&Target](StringRef LHS, StringRef RHS) { 12580b57cec5SDimitry Andric // Multiversioning doesn't allow "no-${feature}", so we can 12590b57cec5SDimitry Andric // only have "+" prefixes here. 12600b57cec5SDimitry Andric assert(LHS.startswith("+") && RHS.startswith("+") && 12610b57cec5SDimitry Andric "Features should always have a prefix."); 12620b57cec5SDimitry Andric return Target.multiVersionSortPriority(LHS.substr(1)) > 12630b57cec5SDimitry Andric Target.multiVersionSortPriority(RHS.substr(1)); 12640b57cec5SDimitry Andric }); 12650b57cec5SDimitry Andric 12660b57cec5SDimitry Andric bool IsFirst = true; 12670b57cec5SDimitry Andric 12680b57cec5SDimitry Andric if (!Info.Architecture.empty()) { 12690b57cec5SDimitry Andric IsFirst = false; 12700b57cec5SDimitry Andric Out << "arch_" << Info.Architecture; 12710b57cec5SDimitry Andric } 12720b57cec5SDimitry Andric 12730b57cec5SDimitry Andric for (StringRef Feat : Info.Features) { 12740b57cec5SDimitry Andric if (!IsFirst) 12750b57cec5SDimitry Andric Out << '_'; 12760b57cec5SDimitry Andric IsFirst = false; 12770b57cec5SDimitry Andric Out << Feat.substr(1); 12780b57cec5SDimitry Andric } 12790b57cec5SDimitry Andric } 12800b57cec5SDimitry Andric 1281fe6060f1SDimitry Andric // Returns true if GD is a function decl with internal linkage and 1282fe6060f1SDimitry Andric // needs a unique suffix after the mangled name. 1283fe6060f1SDimitry Andric static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1284fe6060f1SDimitry Andric CodeGenModule &CGM) { 1285fe6060f1SDimitry Andric const Decl *D = GD.getDecl(); 1286fe6060f1SDimitry Andric return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1287fe6060f1SDimitry Andric (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1288fe6060f1SDimitry Andric } 1289fe6060f1SDimitry Andric 12904824e7fdSDimitry Andric static void AppendTargetClonesMangling(const CodeGenModule &CGM, 12914824e7fdSDimitry Andric const TargetClonesAttr *Attr, 12924824e7fdSDimitry Andric unsigned VersionIndex, 12934824e7fdSDimitry Andric raw_ostream &Out) { 12944824e7fdSDimitry Andric Out << '.'; 12954824e7fdSDimitry Andric StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 12964824e7fdSDimitry Andric if (FeatureStr.startswith("arch=")) 12974824e7fdSDimitry Andric Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 12984824e7fdSDimitry Andric else 12994824e7fdSDimitry Andric Out << FeatureStr; 13004824e7fdSDimitry Andric 13014824e7fdSDimitry Andric Out << '.' << Attr->getMangledIndex(VersionIndex); 13024824e7fdSDimitry Andric } 13034824e7fdSDimitry Andric 1304fe6060f1SDimitry Andric static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 13050b57cec5SDimitry Andric const NamedDecl *ND, 13060b57cec5SDimitry Andric bool OmitMultiVersionMangling = false) { 13070b57cec5SDimitry Andric SmallString<256> Buffer; 13080b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 13090b57cec5SDimitry Andric MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1310fe6060f1SDimitry Andric if (!CGM.getModuleNameHash().empty()) 1311fe6060f1SDimitry Andric MC.needsUniqueInternalLinkageNames(); 1312fe6060f1SDimitry Andric bool ShouldMangle = MC.shouldMangleDeclName(ND); 1313fe6060f1SDimitry Andric if (ShouldMangle) 13145ffd83dbSDimitry Andric MC.mangleName(GD.getWithDecl(ND), Out); 13155ffd83dbSDimitry Andric else { 13160b57cec5SDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 13170b57cec5SDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 13180b57cec5SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 13190b57cec5SDimitry Andric 13200b57cec5SDimitry Andric if (FD && 13210b57cec5SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 13220b57cec5SDimitry Andric Out << "__regcall3__" << II->getName(); 13235ffd83dbSDimitry Andric } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 13245ffd83dbSDimitry Andric GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 13255ffd83dbSDimitry Andric Out << "__device_stub__" << II->getName(); 13260b57cec5SDimitry Andric } else { 13270b57cec5SDimitry Andric Out << II->getName(); 13280b57cec5SDimitry Andric } 13290b57cec5SDimitry Andric } 13300b57cec5SDimitry Andric 1331fe6060f1SDimitry Andric // Check if the module name hash should be appended for internal linkage 1332fe6060f1SDimitry Andric // symbols. This should come before multi-version target suffixes are 1333fe6060f1SDimitry Andric // appended. This is to keep the name and module hash suffix of the 1334fe6060f1SDimitry Andric // internal linkage function together. The unique suffix should only be 1335fe6060f1SDimitry Andric // added when name mangling is done to make sure that the final name can 1336fe6060f1SDimitry Andric // be properly demangled. For example, for C functions without prototypes, 1337fe6060f1SDimitry Andric // name mangling is not done and the unique suffix should not be appeneded 1338fe6060f1SDimitry Andric // then. 1339fe6060f1SDimitry Andric if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1340fe6060f1SDimitry Andric assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1341fe6060f1SDimitry Andric "Hash computed when not explicitly requested"); 1342fe6060f1SDimitry Andric Out << CGM.getModuleNameHash(); 1343fe6060f1SDimitry Andric } 1344fe6060f1SDimitry Andric 13450b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 13460b57cec5SDimitry Andric if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 13470b57cec5SDimitry Andric switch (FD->getMultiVersionKind()) { 13480b57cec5SDimitry Andric case MultiVersionKind::CPUDispatch: 13490b57cec5SDimitry Andric case MultiVersionKind::CPUSpecific: 13500b57cec5SDimitry Andric AppendCPUSpecificCPUDispatchMangling(CGM, 13510b57cec5SDimitry Andric FD->getAttr<CPUSpecificAttr>(), 13520b57cec5SDimitry Andric GD.getMultiVersionIndex(), Out); 13530b57cec5SDimitry Andric break; 13540b57cec5SDimitry Andric case MultiVersionKind::Target: 13550b57cec5SDimitry Andric AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 13560b57cec5SDimitry Andric break; 13574824e7fdSDimitry Andric case MultiVersionKind::TargetClones: 13584824e7fdSDimitry Andric AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 13594824e7fdSDimitry Andric GD.getMultiVersionIndex(), Out); 13604824e7fdSDimitry Andric break; 13610b57cec5SDimitry Andric case MultiVersionKind::None: 13620b57cec5SDimitry Andric llvm_unreachable("None multiversion type isn't valid here"); 13630b57cec5SDimitry Andric } 13640b57cec5SDimitry Andric } 13650b57cec5SDimitry Andric 1366fe6060f1SDimitry Andric // Make unique name for device side static file-scope variable for HIP. 1367fe6060f1SDimitry Andric if (CGM.getContext().shouldExternalizeStaticVar(ND) && 1368fe6060f1SDimitry Andric CGM.getLangOpts().GPURelocatableDeviceCode && 1369fe6060f1SDimitry Andric CGM.getLangOpts().CUDAIsDevice && !CGM.getLangOpts().CUID.empty()) 1370*2a66634dSDimitry Andric CGM.printPostfixForExternalizedDecl(Out, ND); 13715ffd83dbSDimitry Andric return std::string(Out.str()); 13720b57cec5SDimitry Andric } 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 137504eeddc0SDimitry Andric const FunctionDecl *FD, 137604eeddc0SDimitry Andric StringRef &CurName) { 13770b57cec5SDimitry Andric if (!FD->isMultiVersion()) 13780b57cec5SDimitry Andric return; 13790b57cec5SDimitry Andric 13800b57cec5SDimitry Andric // Get the name of what this would be without the 'target' attribute. This 13810b57cec5SDimitry Andric // allows us to lookup the version that was emitted when this wasn't a 13820b57cec5SDimitry Andric // multiversion function. 13830b57cec5SDimitry Andric std::string NonTargetName = 13840b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 13850b57cec5SDimitry Andric GlobalDecl OtherGD; 13860b57cec5SDimitry Andric if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 13870b57cec5SDimitry Andric assert(OtherGD.getCanonicalDecl() 13880b57cec5SDimitry Andric .getDecl() 13890b57cec5SDimitry Andric ->getAsFunction() 13900b57cec5SDimitry Andric ->isMultiVersion() && 13910b57cec5SDimitry Andric "Other GD should now be a multiversioned function"); 13920b57cec5SDimitry Andric // OtherFD is the version of this function that was mangled BEFORE 13930b57cec5SDimitry Andric // becoming a MultiVersion function. It potentially needs to be updated. 13940b57cec5SDimitry Andric const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 13950b57cec5SDimitry Andric .getDecl() 13960b57cec5SDimitry Andric ->getAsFunction() 13970b57cec5SDimitry Andric ->getMostRecentDecl(); 13980b57cec5SDimitry Andric std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 13990b57cec5SDimitry Andric // This is so that if the initial version was already the 'default' 14000b57cec5SDimitry Andric // version, we don't try to update it. 14010b57cec5SDimitry Andric if (OtherName != NonTargetName) { 14020b57cec5SDimitry Andric // Remove instead of erase, since others may have stored the StringRef 14030b57cec5SDimitry Andric // to this. 14040b57cec5SDimitry Andric const auto ExistingRecord = Manglings.find(NonTargetName); 14050b57cec5SDimitry Andric if (ExistingRecord != std::end(Manglings)) 14060b57cec5SDimitry Andric Manglings.remove(&(*ExistingRecord)); 14070b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 140804eeddc0SDimitry Andric StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 140904eeddc0SDimitry Andric Result.first->first(); 141004eeddc0SDimitry Andric // If this is the current decl is being created, make sure we update the name. 141104eeddc0SDimitry Andric if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 141204eeddc0SDimitry Andric CurName = OtherNameRef; 14130b57cec5SDimitry Andric if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 14140b57cec5SDimitry Andric Entry->setName(OtherName); 14150b57cec5SDimitry Andric } 14160b57cec5SDimitry Andric } 14170b57cec5SDimitry Andric } 14180b57cec5SDimitry Andric 14190b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 14200b57cec5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 14210b57cec5SDimitry Andric 14220b57cec5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 14230b57cec5SDimitry Andric // complete constructors get mangled the same. 14240b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 14250b57cec5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 14260b57cec5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 14270b57cec5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 14280b57cec5SDimitry Andric if (OrigCtorType == Ctor_Base) 14290b57cec5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 14300b57cec5SDimitry Andric } 14310b57cec5SDimitry Andric } 14320b57cec5SDimitry Andric 1433fe6060f1SDimitry Andric // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1434fe6060f1SDimitry Andric // static device variable depends on whether the variable is referenced by 1435fe6060f1SDimitry Andric // a host or device host function. Therefore the mangled name cannot be 1436fe6060f1SDimitry Andric // cached. 1437fe6060f1SDimitry Andric if (!LangOpts.CUDAIsDevice || 1438fe6060f1SDimitry Andric !getContext().mayExternalizeStaticVar(GD.getDecl())) { 14390b57cec5SDimitry Andric auto FoundName = MangledDeclNames.find(CanonicalGD); 14400b57cec5SDimitry Andric if (FoundName != MangledDeclNames.end()) 14410b57cec5SDimitry Andric return FoundName->second; 1442fe6060f1SDimitry Andric } 14430b57cec5SDimitry Andric 14440b57cec5SDimitry Andric // Keep the first result in the case of a mangling collision. 14450b57cec5SDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 14460b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, ND); 14470b57cec5SDimitry Andric 14485ffd83dbSDimitry Andric // Ensure either we have different ABIs between host and device compilations, 14495ffd83dbSDimitry Andric // says host compilation following MSVC ABI but device compilation follows 14505ffd83dbSDimitry Andric // Itanium C++ ABI or, if they follow the same ABI, kernel names after 14515ffd83dbSDimitry Andric // mangling should be the same after name stubbing. The later checking is 14525ffd83dbSDimitry Andric // very important as the device kernel name being mangled in host-compilation 14535ffd83dbSDimitry Andric // is used to resolve the device binaries to be executed. Inconsistent naming 14545ffd83dbSDimitry Andric // result in undefined behavior. Even though we cannot check that naming 14555ffd83dbSDimitry Andric // directly between host- and device-compilations, the host- and 14565ffd83dbSDimitry Andric // device-mangling in host compilation could help catching certain ones. 14575ffd83dbSDimitry Andric assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1458*2a66634dSDimitry Andric getContext().shouldExternalizeStaticVar(ND) || getLangOpts().CUDAIsDevice || 14595ffd83dbSDimitry Andric (getContext().getAuxTargetInfo() && 14605ffd83dbSDimitry Andric (getContext().getAuxTargetInfo()->getCXXABI() != 14615ffd83dbSDimitry Andric getContext().getTargetInfo().getCXXABI())) || 14625ffd83dbSDimitry Andric getCUDARuntime().getDeviceSideName(ND) == 14635ffd83dbSDimitry Andric getMangledNameImpl( 14645ffd83dbSDimitry Andric *this, 14655ffd83dbSDimitry Andric GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 14665ffd83dbSDimitry Andric ND)); 14670b57cec5SDimitry Andric 14680b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 14690b57cec5SDimitry Andric return MangledDeclNames[CanonicalGD] = Result.first->first(); 14700b57cec5SDimitry Andric } 14710b57cec5SDimitry Andric 14720b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 14730b57cec5SDimitry Andric const BlockDecl *BD) { 14740b57cec5SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 14750b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 14760b57cec5SDimitry Andric 14770b57cec5SDimitry Andric SmallString<256> Buffer; 14780b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 14790b57cec5SDimitry Andric if (!D) 14800b57cec5SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 14810b57cec5SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 14820b57cec5SDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 14830b57cec5SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 14840b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 14850b57cec5SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 14860b57cec5SDimitry Andric else 14870b57cec5SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 14880b57cec5SDimitry Andric 14890b57cec5SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 14900b57cec5SDimitry Andric return Result.first->first(); 14910b57cec5SDimitry Andric } 14920b57cec5SDimitry Andric 14930b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 14940b57cec5SDimitry Andric return getModule().getNamedValue(Name); 14950b57cec5SDimitry Andric } 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before 14980b57cec5SDimitry Andric /// main() runs. 14990b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 15000b57cec5SDimitry Andric llvm::Constant *AssociatedData) { 15010b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 15020b57cec5SDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 15030b57cec5SDimitry Andric } 15040b57cec5SDimitry Andric 15050b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called 15060b57cec5SDimitry Andric /// when the module is unloaded. 1507e8d8bef9SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1508e8d8bef9SDimitry Andric bool IsDtorAttrFunc) { 1509e8d8bef9SDimitry Andric if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1510e8d8bef9SDimitry Andric (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 15110b57cec5SDimitry Andric DtorsUsingAtExit[Priority].push_back(Dtor); 15120b57cec5SDimitry Andric return; 15130b57cec5SDimitry Andric } 15140b57cec5SDimitry Andric 15150b57cec5SDimitry Andric // FIXME: Type coercion of void()* types. 15160b57cec5SDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 15170b57cec5SDimitry Andric } 15180b57cec5SDimitry Andric 15190b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 15200b57cec5SDimitry Andric if (Fns.empty()) return; 15210b57cec5SDimitry Andric 15220b57cec5SDimitry Andric // Ctor function type is void()*. 15230b57cec5SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 15240b57cec5SDimitry Andric llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 15250b57cec5SDimitry Andric TheModule.getDataLayout().getProgramAddressSpace()); 15260b57cec5SDimitry Andric 15270b57cec5SDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 15280b57cec5SDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 15290b57cec5SDimitry Andric Int32Ty, CtorPFTy, VoidPtrTy); 15300b57cec5SDimitry Andric 15310b57cec5SDimitry Andric // Construct the constructor and destructor arrays. 15320b57cec5SDimitry Andric ConstantInitBuilder builder(*this); 15330b57cec5SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 15340b57cec5SDimitry Andric for (const auto &I : Fns) { 15350b57cec5SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 15360b57cec5SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 15370b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 15380b57cec5SDimitry Andric if (I.AssociatedData) 15390b57cec5SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 15400b57cec5SDimitry Andric else 15410b57cec5SDimitry Andric ctor.addNullPointer(VoidPtrTy); 15420b57cec5SDimitry Andric ctor.finishAndAddTo(ctors); 15430b57cec5SDimitry Andric } 15440b57cec5SDimitry Andric 15450b57cec5SDimitry Andric auto list = 15460b57cec5SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 15470b57cec5SDimitry Andric /*constant*/ false, 15480b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage); 15490b57cec5SDimitry Andric 15500b57cec5SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 15510b57cec5SDimitry Andric // on appending variables. Take it off as a workaround. 1552a7dea167SDimitry Andric list->setAlignment(llvm::None); 15530b57cec5SDimitry Andric 15540b57cec5SDimitry Andric Fns.clear(); 15550b57cec5SDimitry Andric } 15560b57cec5SDimitry Andric 15570b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes 15580b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 15590b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 15600b57cec5SDimitry Andric 15610b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 15620b57cec5SDimitry Andric 15630b57cec5SDimitry Andric if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 15640b57cec5SDimitry Andric return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 15650b57cec5SDimitry Andric 15660b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) && 15670b57cec5SDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 15680b57cec5SDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15690b57cec5SDimitry Andric // Our approach to inheriting constructors is fundamentally different from 15700b57cec5SDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 15710b57cec5SDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 15720b57cec5SDimitry Andric return llvm::GlobalValue::InternalLinkage; 15730b57cec5SDimitry Andric } 15740b57cec5SDimitry Andric 15750b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 15760b57cec5SDimitry Andric } 15770b57cec5SDimitry Andric 15780b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 15790b57cec5SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 15800b57cec5SDimitry Andric if (!MDS) return nullptr; 15810b57cec5SDimitry Andric 15820b57cec5SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 15830b57cec5SDimitry Andric } 15840b57cec5SDimitry Andric 15850b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 15860b57cec5SDimitry Andric const CGFunctionInfo &Info, 1587fe6060f1SDimitry Andric llvm::Function *F, bool IsThunk) { 15880b57cec5SDimitry Andric unsigned CallingConv; 15890b57cec5SDimitry Andric llvm::AttributeList PAL; 1590fe6060f1SDimitry Andric ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 1591fe6060f1SDimitry Andric /*AttrOnCallSite=*/false, IsThunk); 15920b57cec5SDimitry Andric F->setAttributes(PAL); 15930b57cec5SDimitry Andric F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 15940b57cec5SDimitry Andric } 15950b57cec5SDimitry Andric 15960b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) { 15970b57cec5SDimitry Andric std::string ReadOnlyQual("__read_only"); 15980b57cec5SDimitry Andric std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 15990b57cec5SDimitry Andric if (ReadOnlyPos != std::string::npos) 16000b57cec5SDimitry Andric // "+ 1" for the space after access qualifier. 16010b57cec5SDimitry Andric TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 16020b57cec5SDimitry Andric else { 16030b57cec5SDimitry Andric std::string WriteOnlyQual("__write_only"); 16040b57cec5SDimitry Andric std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 16050b57cec5SDimitry Andric if (WriteOnlyPos != std::string::npos) 16060b57cec5SDimitry Andric TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 16070b57cec5SDimitry Andric else { 16080b57cec5SDimitry Andric std::string ReadWriteQual("__read_write"); 16090b57cec5SDimitry Andric std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 16100b57cec5SDimitry Andric if (ReadWritePos != std::string::npos) 16110b57cec5SDimitry Andric TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 16120b57cec5SDimitry Andric } 16130b57cec5SDimitry Andric } 16140b57cec5SDimitry Andric } 16150b57cec5SDimitry Andric 16160b57cec5SDimitry Andric // Returns the address space id that should be produced to the 16170b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids 16180b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate 16190b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address 16200b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces 16210b57cec5SDimitry Andric // (basically all single AS CPUs). 16220b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) { 16230b57cec5SDimitry Andric switch (AS) { 1624e8d8bef9SDimitry Andric case LangAS::opencl_global: 1625e8d8bef9SDimitry Andric return 1; 1626e8d8bef9SDimitry Andric case LangAS::opencl_constant: 1627e8d8bef9SDimitry Andric return 2; 1628e8d8bef9SDimitry Andric case LangAS::opencl_local: 1629e8d8bef9SDimitry Andric return 3; 1630e8d8bef9SDimitry Andric case LangAS::opencl_generic: 1631e8d8bef9SDimitry Andric return 4; // Not in SPIR 2.0 specs. 1632e8d8bef9SDimitry Andric case LangAS::opencl_global_device: 1633e8d8bef9SDimitry Andric return 5; 1634e8d8bef9SDimitry Andric case LangAS::opencl_global_host: 1635e8d8bef9SDimitry Andric return 6; 16360b57cec5SDimitry Andric default: 16370b57cec5SDimitry Andric return 0; // Assume private. 16380b57cec5SDimitry Andric } 16390b57cec5SDimitry Andric } 16400b57cec5SDimitry Andric 16410b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 16420b57cec5SDimitry Andric const FunctionDecl *FD, 16430b57cec5SDimitry Andric CodeGenFunction *CGF) { 16440b57cec5SDimitry Andric assert(((FD && CGF) || (!FD && !CGF)) && 16450b57cec5SDimitry Andric "Incorrect use - FD and CGF should either be both null or not!"); 16460b57cec5SDimitry Andric // Create MDNodes that represent the kernel arg metadata. 16470b57cec5SDimitry Andric // Each MDNode is a list in the form of "key", N number of values which is 16480b57cec5SDimitry Andric // the same number of values as their are kernel arguments. 16490b57cec5SDimitry Andric 16500b57cec5SDimitry Andric const PrintingPolicy &Policy = Context.getPrintingPolicy(); 16510b57cec5SDimitry Andric 16520b57cec5SDimitry Andric // MDNode for the kernel argument address space qualifiers. 16530b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> addressQuals; 16540b57cec5SDimitry Andric 16550b57cec5SDimitry Andric // MDNode for the kernel argument access qualifiers (images only). 16560b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> accessQuals; 16570b57cec5SDimitry Andric 16580b57cec5SDimitry Andric // MDNode for the kernel argument type names. 16590b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeNames; 16600b57cec5SDimitry Andric 16610b57cec5SDimitry Andric // MDNode for the kernel argument base type names. 16620b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric // MDNode for the kernel argument type qualifiers. 16650b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argTypeQuals; 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric // MDNode for the kernel argument names. 16680b57cec5SDimitry Andric SmallVector<llvm::Metadata *, 8> argNames; 16690b57cec5SDimitry Andric 16700b57cec5SDimitry Andric if (FD && CGF) 16710b57cec5SDimitry Andric for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 16720b57cec5SDimitry Andric const ParmVarDecl *parm = FD->getParamDecl(i); 16730b57cec5SDimitry Andric QualType ty = parm->getType(); 16740b57cec5SDimitry Andric std::string typeQuals; 16750b57cec5SDimitry Andric 1676fe6060f1SDimitry Andric // Get image and pipe access qualifier: 1677fe6060f1SDimitry Andric if (ty->isImageType() || ty->isPipeType()) { 1678fe6060f1SDimitry Andric const Decl *PDecl = parm; 1679fe6060f1SDimitry Andric if (auto *TD = dyn_cast<TypedefType>(ty)) 1680fe6060f1SDimitry Andric PDecl = TD->getDecl(); 1681fe6060f1SDimitry Andric const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1682fe6060f1SDimitry Andric if (A && A->isWriteOnly()) 1683fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1684fe6060f1SDimitry Andric else if (A && A->isReadWrite()) 1685fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1686fe6060f1SDimitry Andric else 1687fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1688fe6060f1SDimitry Andric } else 1689fe6060f1SDimitry Andric accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1690fe6060f1SDimitry Andric 1691fe6060f1SDimitry Andric // Get argument name. 1692fe6060f1SDimitry Andric argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1693fe6060f1SDimitry Andric 1694fe6060f1SDimitry Andric auto getTypeSpelling = [&](QualType Ty) { 1695fe6060f1SDimitry Andric auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1696fe6060f1SDimitry Andric 1697fe6060f1SDimitry Andric if (Ty.isCanonical()) { 1698fe6060f1SDimitry Andric StringRef typeNameRef = typeName; 1699fe6060f1SDimitry Andric // Turn "unsigned type" to "utype" 1700fe6060f1SDimitry Andric if (typeNameRef.consume_front("unsigned ")) 1701fe6060f1SDimitry Andric return std::string("u") + typeNameRef.str(); 1702fe6060f1SDimitry Andric if (typeNameRef.consume_front("signed ")) 1703fe6060f1SDimitry Andric return typeNameRef.str(); 1704fe6060f1SDimitry Andric } 1705fe6060f1SDimitry Andric 1706fe6060f1SDimitry Andric return typeName; 1707fe6060f1SDimitry Andric }; 1708fe6060f1SDimitry Andric 17090b57cec5SDimitry Andric if (ty->isPointerType()) { 17100b57cec5SDimitry Andric QualType pointeeTy = ty->getPointeeType(); 17110b57cec5SDimitry Andric 17120b57cec5SDimitry Andric // Get address qualifier. 17130b57cec5SDimitry Andric addressQuals.push_back( 17140b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 17150b57cec5SDimitry Andric ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 17160b57cec5SDimitry Andric 17170b57cec5SDimitry Andric // Get argument type name. 1718fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(pointeeTy) + "*"; 17190b57cec5SDimitry Andric std::string baseTypeName = 1720fe6060f1SDimitry Andric getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1721fe6060f1SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 17220b57cec5SDimitry Andric argBaseTypeNames.push_back( 17230b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 17240b57cec5SDimitry Andric 17250b57cec5SDimitry Andric // Get argument type qualifiers: 17260b57cec5SDimitry Andric if (ty.isRestrictQualified()) 17270b57cec5SDimitry Andric typeQuals = "restrict"; 17280b57cec5SDimitry Andric if (pointeeTy.isConstQualified() || 17290b57cec5SDimitry Andric (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 17300b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "const" : " const"; 17310b57cec5SDimitry Andric if (pointeeTy.isVolatileQualified()) 17320b57cec5SDimitry Andric typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 17330b57cec5SDimitry Andric } else { 17340b57cec5SDimitry Andric uint32_t AddrSpc = 0; 17350b57cec5SDimitry Andric bool isPipe = ty->isPipeType(); 17360b57cec5SDimitry Andric if (ty->isImageType() || isPipe) 17370b57cec5SDimitry Andric AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 17380b57cec5SDimitry Andric 17390b57cec5SDimitry Andric addressQuals.push_back( 17400b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 17410b57cec5SDimitry Andric 17420b57cec5SDimitry Andric // Get argument type name. 1743fe6060f1SDimitry Andric ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1744fe6060f1SDimitry Andric std::string typeName = getTypeSpelling(ty); 1745fe6060f1SDimitry Andric std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 17460b57cec5SDimitry Andric 17470b57cec5SDimitry Andric // Remove access qualifiers on images 17480b57cec5SDimitry Andric // (as they are inseparable from type in clang implementation, 17490b57cec5SDimitry Andric // but OpenCL spec provides a special query to get access qualifier 17500b57cec5SDimitry Andric // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 17510b57cec5SDimitry Andric if (ty->isImageType()) { 17520b57cec5SDimitry Andric removeImageAccessQualifier(typeName); 17530b57cec5SDimitry Andric removeImageAccessQualifier(baseTypeName); 17540b57cec5SDimitry Andric } 17550b57cec5SDimitry Andric 17560b57cec5SDimitry Andric argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 17570b57cec5SDimitry Andric argBaseTypeNames.push_back( 17580b57cec5SDimitry Andric llvm::MDString::get(VMContext, baseTypeName)); 17590b57cec5SDimitry Andric 17600b57cec5SDimitry Andric if (isPipe) 17610b57cec5SDimitry Andric typeQuals = "pipe"; 17620b57cec5SDimitry Andric } 17630b57cec5SDimitry Andric argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 17640b57cec5SDimitry Andric } 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_addr_space", 17670b57cec5SDimitry Andric llvm::MDNode::get(VMContext, addressQuals)); 17680b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_access_qual", 17690b57cec5SDimitry Andric llvm::MDNode::get(VMContext, accessQuals)); 17700b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type", 17710b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeNames)); 17720b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_base_type", 17730b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argBaseTypeNames)); 17740b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_type_qual", 17750b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argTypeQuals)); 17760b57cec5SDimitry Andric if (getCodeGenOpts().EmitOpenCLArgMetadata) 17770b57cec5SDimitry Andric Fn->setMetadata("kernel_arg_name", 17780b57cec5SDimitry Andric llvm::MDNode::get(VMContext, argNames)); 17790b57cec5SDimitry Andric } 17800b57cec5SDimitry Andric 17810b57cec5SDimitry Andric /// Determines whether the language options require us to model 17820b57cec5SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 17830b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 17840b57cec5SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 17850b57cec5SDimitry Andric /// enables this. 17860b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 17870b57cec5SDimitry Andric // If exceptions are completely disabled, obviously this is false. 17880b57cec5SDimitry Andric if (!LangOpts.Exceptions) return false; 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric // If C++ exceptions are enabled, this is true. 17910b57cec5SDimitry Andric if (LangOpts.CXXExceptions) return true; 17920b57cec5SDimitry Andric 17930b57cec5SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 17940b57cec5SDimitry Andric if (LangOpts.ObjCExceptions) { 17950b57cec5SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 17960b57cec5SDimitry Andric } 17970b57cec5SDimitry Andric 17980b57cec5SDimitry Andric return true; 17990b57cec5SDimitry Andric } 18000b57cec5SDimitry Andric 18010b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 18020b57cec5SDimitry Andric const CXXMethodDecl *MD) { 18030b57cec5SDimitry Andric // Check that the type metadata can ever actually be used by a call. 18040b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().LTOUnit || 18050b57cec5SDimitry Andric !CGM.HasHiddenLTOVisibility(MD->getParent())) 18060b57cec5SDimitry Andric return false; 18070b57cec5SDimitry Andric 18080b57cec5SDimitry Andric // Only functions whose address can be taken with a member function pointer 18090b57cec5SDimitry Andric // need this sort of type metadata. 18100b57cec5SDimitry Andric return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 18110b57cec5SDimitry Andric !isa<CXXDestructorDecl>(MD); 18120b57cec5SDimitry Andric } 18130b57cec5SDimitry Andric 18140b57cec5SDimitry Andric std::vector<const CXXRecordDecl *> 18150b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 18160b57cec5SDimitry Andric llvm::SetVector<const CXXRecordDecl *> MostBases; 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric std::function<void (const CXXRecordDecl *)> CollectMostBases; 18190b57cec5SDimitry Andric CollectMostBases = [&](const CXXRecordDecl *RD) { 18200b57cec5SDimitry Andric if (RD->getNumBases() == 0) 18210b57cec5SDimitry Andric MostBases.insert(RD); 18220b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : RD->bases()) 18230b57cec5SDimitry Andric CollectMostBases(B.getType()->getAsCXXRecordDecl()); 18240b57cec5SDimitry Andric }; 18250b57cec5SDimitry Andric CollectMostBases(RD); 18260b57cec5SDimitry Andric return MostBases.takeVector(); 18270b57cec5SDimitry Andric } 18280b57cec5SDimitry Andric 18290b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 18300b57cec5SDimitry Andric llvm::Function *F) { 183104eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext()); 18320b57cec5SDimitry Andric 18330b57cec5SDimitry Andric if (CodeGenOpts.UnwindTables) 18340b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 18350b57cec5SDimitry Andric 18365ffd83dbSDimitry Andric if (CodeGenOpts.StackClashProtector) 18375ffd83dbSDimitry Andric B.addAttribute("probe-stack", "inline-asm"); 18385ffd83dbSDimitry Andric 18390b57cec5SDimitry Andric if (!hasUnwindExceptions(LangOpts)) 18400b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 18410b57cec5SDimitry Andric 18420b57cec5SDimitry Andric if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 18430b57cec5SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 18440b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 18450b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 18460b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 18470b57cec5SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 18480b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 18490b57cec5SDimitry Andric } 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric if (!D) { 18520b57cec5SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 18530b57cec5SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 18540b57cec5SDimitry Andric // disabled, mark the function as noinline. 18550b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 18560b57cec5SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 18570b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 18580b57cec5SDimitry Andric 1859349cc55cSDimitry Andric F->addFnAttrs(B); 18600b57cec5SDimitry Andric return; 18610b57cec5SDimitry Andric } 18620b57cec5SDimitry Andric 18630b57cec5SDimitry Andric // Track whether we need to add the optnone LLVM attribute, 18640b57cec5SDimitry Andric // starting with the default for this optimization level. 18650b57cec5SDimitry Andric bool ShouldAddOptNone = 18660b57cec5SDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 18670b57cec5SDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 18680b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 18690b57cec5SDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 18700b57cec5SDimitry Andric 1871480093f4SDimitry Andric // Add optnone, but do so only if the function isn't always_inline. 1872480093f4SDimitry Andric if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1873480093f4SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 18740b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 18750b57cec5SDimitry Andric 18760b57cec5SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 18770b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 18780b57cec5SDimitry Andric 18790b57cec5SDimitry Andric // We still need to handle naked functions even though optnone subsumes 18800b57cec5SDimitry Andric // much of their semantics. 18810b57cec5SDimitry Andric if (D->hasAttr<NakedAttr>()) 18820b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 18830b57cec5SDimitry Andric 18840b57cec5SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 18850b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 18860b57cec5SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 18870b57cec5SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 18880b57cec5SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 18890b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 18900b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 18910b57cec5SDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 18920b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 1893480093f4SDimitry Andric } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1894480093f4SDimitry Andric // Add noinline if the function isn't always_inline. 18950b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 18960b57cec5SDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 18970b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 18980b57cec5SDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 18990b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 19000b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 19010b57cec5SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 19020b57cec5SDimitry Andric // carry an explicit noinline attribute. 19030b57cec5SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 19040b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 19050b57cec5SDimitry Andric } else { 19060b57cec5SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 19070b57cec5SDimitry Andric // absence to mark things as noinline. 19080b57cec5SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 19090b57cec5SDimitry Andric // Search function and template pattern redeclarations for inline. 19100b57cec5SDimitry Andric auto CheckForInline = [](const FunctionDecl *FD) { 19110b57cec5SDimitry Andric auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 19120b57cec5SDimitry Andric return Redecl->isInlineSpecified(); 19130b57cec5SDimitry Andric }; 19140b57cec5SDimitry Andric if (any_of(FD->redecls(), CheckRedeclForInline)) 19150b57cec5SDimitry Andric return true; 19160b57cec5SDimitry Andric const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 19170b57cec5SDimitry Andric if (!Pattern) 19180b57cec5SDimitry Andric return false; 19190b57cec5SDimitry Andric return any_of(Pattern->redecls(), CheckRedeclForInline); 19200b57cec5SDimitry Andric }; 19210b57cec5SDimitry Andric if (CheckForInline(FD)) { 19220b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 19230b57cec5SDimitry Andric } else if (CodeGenOpts.getInlining() == 19240b57cec5SDimitry Andric CodeGenOptions::OnlyHintInlining && 19250b57cec5SDimitry Andric !FD->isInlined() && 19260b57cec5SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 19270b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 19280b57cec5SDimitry Andric } 19290b57cec5SDimitry Andric } 19300b57cec5SDimitry Andric } 19310b57cec5SDimitry Andric 19320b57cec5SDimitry Andric // Add other optimization related attributes if we are optimizing this 19330b57cec5SDimitry Andric // function. 19340b57cec5SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 19350b57cec5SDimitry Andric if (D->hasAttr<ColdAttr>()) { 19360b57cec5SDimitry Andric if (!ShouldAddOptNone) 19370b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 19380b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::Cold); 19390b57cec5SDimitry Andric } 1940e8d8bef9SDimitry Andric if (D->hasAttr<HotAttr>()) 1941e8d8bef9SDimitry Andric B.addAttribute(llvm::Attribute::Hot); 19420b57cec5SDimitry Andric if (D->hasAttr<MinSizeAttr>()) 19430b57cec5SDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 19440b57cec5SDimitry Andric } 19450b57cec5SDimitry Andric 1946349cc55cSDimitry Andric F->addFnAttrs(B); 19470b57cec5SDimitry Andric 19480b57cec5SDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 19490b57cec5SDimitry Andric if (alignment) 1950a7dea167SDimitry Andric F->setAlignment(llvm::Align(alignment)); 19510b57cec5SDimitry Andric 19520b57cec5SDimitry Andric if (!D->hasAttr<AlignedAttr>()) 19530b57cec5SDimitry Andric if (LangOpts.FunctionAlignment) 1954a7dea167SDimitry Andric F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 19550b57cec5SDimitry Andric 19560b57cec5SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 19570b57cec5SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 19580b57cec5SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 19590b57cec5SDimitry Andric // member function, set its alignment accordingly. 19600b57cec5SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 19610b57cec5SDimitry Andric if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1962a7dea167SDimitry Andric F->setAlignment(llvm::Align(2)); 19630b57cec5SDimitry Andric } 19640b57cec5SDimitry Andric 1965a7dea167SDimitry Andric // In the cross-dso CFI mode with canonical jump tables, we want !type 1966a7dea167SDimitry Andric // attributes on definitions only. 1967a7dea167SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso && 1968a7dea167SDimitry Andric CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 1969a7dea167SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1970a7dea167SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 1971a7dea167SDimitry Andric // current module anyway. 1972a7dea167SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 19730b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 1974a7dea167SDimitry Andric } 1975a7dea167SDimitry Andric } 19760b57cec5SDimitry Andric 19770b57cec5SDimitry Andric // Emit type metadata on member functions for member function pointer checks. 19780b57cec5SDimitry Andric // These are only ever necessary on definitions; we're guaranteed that the 19790b57cec5SDimitry Andric // definition will be present in the LTO unit as a result of LTO visibility. 19800b57cec5SDimitry Andric auto *MD = dyn_cast<CXXMethodDecl>(D); 19810b57cec5SDimitry Andric if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 19820b57cec5SDimitry Andric for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 19830b57cec5SDimitry Andric llvm::Metadata *Id = 19840b57cec5SDimitry Andric CreateMetadataIdentifierForType(Context.getMemberPointerType( 19850b57cec5SDimitry Andric MD->getType(), Context.getRecordType(Base).getTypePtr())); 19860b57cec5SDimitry Andric F->addTypeMetadata(0, Id); 19870b57cec5SDimitry Andric } 19880b57cec5SDimitry Andric } 19890b57cec5SDimitry Andric } 19900b57cec5SDimitry Andric 1991e8d8bef9SDimitry Andric void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 1992e8d8bef9SDimitry Andric llvm::Function *F) { 1993e8d8bef9SDimitry Andric if (D->hasAttr<StrictFPAttr>()) { 199404eeddc0SDimitry Andric llvm::AttrBuilder FuncAttrs(F->getContext()); 1995e8d8bef9SDimitry Andric FuncAttrs.addAttribute("strictfp"); 1996349cc55cSDimitry Andric F->addFnAttrs(FuncAttrs); 1997e8d8bef9SDimitry Andric } 1998e8d8bef9SDimitry Andric } 1999e8d8bef9SDimitry Andric 20000b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 20010b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2002349cc55cSDimitry Andric if (isa_and_nonnull<NamedDecl>(D)) 20030b57cec5SDimitry Andric setGVProperties(GV, GD); 20040b57cec5SDimitry Andric else 20050b57cec5SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 20060b57cec5SDimitry Andric 20070b57cec5SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 2008fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 20090b57cec5SDimitry Andric 20100b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 20110b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(D); 20120b57cec5SDimitry Andric if (VD->getType().isConstQualified() && 20130b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 2014fe6060f1SDimitry Andric addUsedOrCompilerUsedGlobal(GV); 20150b57cec5SDimitry Andric } 20160b57cec5SDimitry Andric } 20170b57cec5SDimitry Andric 20180b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 20190b57cec5SDimitry Andric llvm::AttrBuilder &Attrs) { 20200b57cec5SDimitry Andric // Add target-cpu and target-features attributes to functions. If 20210b57cec5SDimitry Andric // we have a decl for the function and it has a target attribute then 20220b57cec5SDimitry Andric // parse that and add it to the feature set. 20230b57cec5SDimitry Andric StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2024e8d8bef9SDimitry Andric StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 20250b57cec5SDimitry Andric std::vector<std::string> Features; 20260b57cec5SDimitry Andric const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 20270b57cec5SDimitry Andric FD = FD ? FD->getMostRecentDecl() : FD; 20280b57cec5SDimitry Andric const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 20290b57cec5SDimitry Andric const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 20304824e7fdSDimitry Andric const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 20310b57cec5SDimitry Andric bool AddedAttr = false; 20324824e7fdSDimitry Andric if (TD || SD || TC) { 20330b57cec5SDimitry Andric llvm::StringMap<bool> FeatureMap; 2034480093f4SDimitry Andric getContext().getFunctionFeatureMap(FeatureMap, GD); 20350b57cec5SDimitry Andric 20360b57cec5SDimitry Andric // Produce the canonical string for this set of features. 20370b57cec5SDimitry Andric for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 20380b57cec5SDimitry Andric Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 20390b57cec5SDimitry Andric 20400b57cec5SDimitry Andric // Now add the target-cpu and target-features to the function. 20410b57cec5SDimitry Andric // While we populated the feature map above, we still need to 20420b57cec5SDimitry Andric // get and parse the target attribute so we can get the cpu for 20430b57cec5SDimitry Andric // the function. 20440b57cec5SDimitry Andric if (TD) { 2045480093f4SDimitry Andric ParsedTargetAttr ParsedAttr = TD->parse(); 2046e8d8bef9SDimitry Andric if (!ParsedAttr.Architecture.empty() && 2047e8d8bef9SDimitry Andric getTarget().isValidCPUName(ParsedAttr.Architecture)) { 20480b57cec5SDimitry Andric TargetCPU = ParsedAttr.Architecture; 2049e8d8bef9SDimitry Andric TuneCPU = ""; // Clear the tune CPU. 2050e8d8bef9SDimitry Andric } 2051e8d8bef9SDimitry Andric if (!ParsedAttr.Tune.empty() && 2052e8d8bef9SDimitry Andric getTarget().isValidCPUName(ParsedAttr.Tune)) 2053e8d8bef9SDimitry Andric TuneCPU = ParsedAttr.Tune; 20540b57cec5SDimitry Andric } 20550b57cec5SDimitry Andric } else { 20560b57cec5SDimitry Andric // Otherwise just add the existing target cpu and target features to the 20570b57cec5SDimitry Andric // function. 20580b57cec5SDimitry Andric Features = getTarget().getTargetOpts().Features; 20590b57cec5SDimitry Andric } 20600b57cec5SDimitry Andric 2061e8d8bef9SDimitry Andric if (!TargetCPU.empty()) { 20620b57cec5SDimitry Andric Attrs.addAttribute("target-cpu", TargetCPU); 20630b57cec5SDimitry Andric AddedAttr = true; 20640b57cec5SDimitry Andric } 2065e8d8bef9SDimitry Andric if (!TuneCPU.empty()) { 2066e8d8bef9SDimitry Andric Attrs.addAttribute("tune-cpu", TuneCPU); 2067e8d8bef9SDimitry Andric AddedAttr = true; 2068e8d8bef9SDimitry Andric } 20690b57cec5SDimitry Andric if (!Features.empty()) { 20700b57cec5SDimitry Andric llvm::sort(Features); 20710b57cec5SDimitry Andric Attrs.addAttribute("target-features", llvm::join(Features, ",")); 20720b57cec5SDimitry Andric AddedAttr = true; 20730b57cec5SDimitry Andric } 20740b57cec5SDimitry Andric 20750b57cec5SDimitry Andric return AddedAttr; 20760b57cec5SDimitry Andric } 20770b57cec5SDimitry Andric 20780b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 20790b57cec5SDimitry Andric llvm::GlobalObject *GO) { 20800b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 20810b57cec5SDimitry Andric SetCommonAttributes(GD, GO); 20820b57cec5SDimitry Andric 20830b57cec5SDimitry Andric if (D) { 20840b57cec5SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2085fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2086fe6060f1SDimitry Andric addUsedGlobal(GV); 20870b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 20880b57cec5SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 20890b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 20900b57cec5SDimitry Andric GV->addAttribute("data-section", SA->getName()); 20910b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 20920b57cec5SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 2093a7dea167SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2094a7dea167SDimitry Andric GV->addAttribute("relro-section", SA->getName()); 20950b57cec5SDimitry Andric } 20960b57cec5SDimitry Andric 20970b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 2098fe6060f1SDimitry Andric if (D->hasAttr<RetainAttr>()) 2099fe6060f1SDimitry Andric addUsedGlobal(F); 21000b57cec5SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 21010b57cec5SDimitry Andric if (!D->getAttr<SectionAttr>()) 21020b57cec5SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 21030b57cec5SDimitry Andric 210404eeddc0SDimitry Andric llvm::AttrBuilder Attrs(F->getContext()); 21050b57cec5SDimitry Andric if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 21060b57cec5SDimitry Andric // We know that GetCPUAndFeaturesAttributes will always have the 21070b57cec5SDimitry Andric // newest set, since it has the newest possible FunctionDecl, so the 21080b57cec5SDimitry Andric // new ones should replace the old. 210904eeddc0SDimitry Andric llvm::AttributeMask RemoveAttrs; 2110e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-cpu"); 2111e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("target-features"); 2112e8d8bef9SDimitry Andric RemoveAttrs.addAttribute("tune-cpu"); 2113349cc55cSDimitry Andric F->removeFnAttrs(RemoveAttrs); 2114349cc55cSDimitry Andric F->addFnAttrs(Attrs); 21150b57cec5SDimitry Andric } 21160b57cec5SDimitry Andric } 21170b57cec5SDimitry Andric 21180b57cec5SDimitry Andric if (const auto *CSA = D->getAttr<CodeSegAttr>()) 21190b57cec5SDimitry Andric GO->setSection(CSA->getName()); 21200b57cec5SDimitry Andric else if (const auto *SA = D->getAttr<SectionAttr>()) 21210b57cec5SDimitry Andric GO->setSection(SA->getName()); 21220b57cec5SDimitry Andric } 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 21250b57cec5SDimitry Andric } 21260b57cec5SDimitry Andric 21270b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 21280b57cec5SDimitry Andric llvm::Function *F, 21290b57cec5SDimitry Andric const CGFunctionInfo &FI) { 21300b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 2131fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 21320b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, F); 21330b57cec5SDimitry Andric 21340b57cec5SDimitry Andric F->setLinkage(llvm::Function::InternalLinkage); 21350b57cec5SDimitry Andric 21360b57cec5SDimitry Andric setNonAliasAttributes(GD, F); 21370b57cec5SDimitry Andric } 21380b57cec5SDimitry Andric 21390b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 21400b57cec5SDimitry Andric // Set linkage and visibility in case we never see a definition. 21410b57cec5SDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 21420b57cec5SDimitry Andric // Don't set internal linkage on declarations. 21430b57cec5SDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 21440b57cec5SDimitry Andric // separate linkage types for this. 21450b57cec5SDimitry Andric if (isExternallyVisible(LV.getLinkage()) && 21460b57cec5SDimitry Andric (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 21470b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 21480b57cec5SDimitry Andric } 21490b57cec5SDimitry Andric 21500b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 21510b57cec5SDimitry Andric llvm::Function *F) { 21520b57cec5SDimitry Andric // Only if we are checking indirect calls. 21530b57cec5SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 21540b57cec5SDimitry Andric return; 21550b57cec5SDimitry Andric 21560b57cec5SDimitry Andric // Non-static class methods are handled via vtable or member function pointer 21570b57cec5SDimitry Andric // checks elsewhere. 21580b57cec5SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 21590b57cec5SDimitry Andric return; 21600b57cec5SDimitry Andric 21610b57cec5SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 21620b57cec5SDimitry Andric F->addTypeMetadata(0, MD); 21630b57cec5SDimitry Andric F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 21640b57cec5SDimitry Andric 21650b57cec5SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 21660b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 21670b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 21680b57cec5SDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 21690b57cec5SDimitry Andric } 21700b57cec5SDimitry Andric 21710b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 21720b57cec5SDimitry Andric bool IsIncompleteFunction, 21730b57cec5SDimitry Andric bool IsThunk) { 21740b57cec5SDimitry Andric 21750b57cec5SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 21760b57cec5SDimitry Andric // If this is an intrinsic function, set the function's attributes 21770b57cec5SDimitry Andric // to the intrinsic's attributes. 21780b57cec5SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 21790b57cec5SDimitry Andric return; 21800b57cec5SDimitry Andric } 21810b57cec5SDimitry Andric 21820b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 21830b57cec5SDimitry Andric 21840b57cec5SDimitry Andric if (!IsIncompleteFunction) 2185fe6060f1SDimitry Andric SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2186fe6060f1SDimitry Andric IsThunk); 21870b57cec5SDimitry Andric 21880b57cec5SDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 21890b57cec5SDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 21900b57cec5SDimitry Andric // GCC and does not actually return "this". 21910b57cec5SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 21920b57cec5SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 21930b57cec5SDimitry Andric assert(!F->arg_empty() && 21940b57cec5SDimitry Andric F->arg_begin()->getType() 21950b57cec5SDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 21960b57cec5SDimitry Andric "unexpected this return"); 2197349cc55cSDimitry Andric F->addParamAttr(0, llvm::Attribute::Returned); 21980b57cec5SDimitry Andric } 21990b57cec5SDimitry Andric 22000b57cec5SDimitry Andric // Only a few attributes are set on declarations; these may later be 22010b57cec5SDimitry Andric // overridden by a definition. 22020b57cec5SDimitry Andric 22030b57cec5SDimitry Andric setLinkageForGV(F, FD); 22040b57cec5SDimitry Andric setGVProperties(F, FD); 22050b57cec5SDimitry Andric 22060b57cec5SDimitry Andric // Setup target-specific attributes. 22070b57cec5SDimitry Andric if (!IsIncompleteFunction && F->isDeclaration()) 22080b57cec5SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 22090b57cec5SDimitry Andric 22100b57cec5SDimitry Andric if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 22110b57cec5SDimitry Andric F->setSection(CSA->getName()); 22120b57cec5SDimitry Andric else if (const auto *SA = FD->getAttr<SectionAttr>()) 22130b57cec5SDimitry Andric F->setSection(SA->getName()); 22140b57cec5SDimitry Andric 2215349cc55cSDimitry Andric if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2216349cc55cSDimitry Andric if (EA->isError()) 2217349cc55cSDimitry Andric F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2218349cc55cSDimitry Andric else if (EA->isWarning()) 2219349cc55cSDimitry Andric F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2220349cc55cSDimitry Andric } 2221349cc55cSDimitry Andric 2222d65cd7a5SDimitry Andric // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2223480093f4SDimitry Andric if (FD->isInlineBuiltinDeclaration()) { 2224d65cd7a5SDimitry Andric const FunctionDecl *FDBody; 2225d65cd7a5SDimitry Andric bool HasBody = FD->hasBody(FDBody); 2226d65cd7a5SDimitry Andric (void)HasBody; 2227d65cd7a5SDimitry Andric assert(HasBody && "Inline builtin declarations should always have an " 2228d65cd7a5SDimitry Andric "available body!"); 2229d65cd7a5SDimitry Andric if (shouldEmitFunction(FDBody)) 2230349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 2231480093f4SDimitry Andric } 2232480093f4SDimitry Andric 22330b57cec5SDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 22340b57cec5SDimitry Andric // A replaceable global allocation function does not act like a builtin by 22350b57cec5SDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 2236349cc55cSDimitry Andric F->addFnAttr(llvm::Attribute::NoBuiltin); 22370b57cec5SDimitry Andric } 22380b57cec5SDimitry Andric 22390b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 22400b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 22410b57cec5SDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 22420b57cec5SDimitry Andric if (MD->isVirtual()) 22430b57cec5SDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 22440b57cec5SDimitry Andric 22450b57cec5SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 2246a7dea167SDimitry Andric // is handled with better precision by the receiving DSO. But if jump tables 2247a7dea167SDimitry Andric // are non-canonical then we need type metadata in order to produce the local 2248a7dea167SDimitry Andric // jump table. 2249a7dea167SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso || 2250a7dea167SDimitry Andric !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 22510b57cec5SDimitry Andric CreateFunctionTypeMetadataForIcall(FD, F); 22520b57cec5SDimitry Andric 22530b57cec5SDimitry Andric if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 22540b57cec5SDimitry Andric getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 22550b57cec5SDimitry Andric 22560b57cec5SDimitry Andric if (const auto *CB = FD->getAttr<CallbackAttr>()) { 22570b57cec5SDimitry Andric // Annotate the callback behavior as metadata: 22580b57cec5SDimitry Andric // - The callback callee (as argument number). 22590b57cec5SDimitry Andric // - The callback payloads (as argument numbers). 22600b57cec5SDimitry Andric llvm::LLVMContext &Ctx = F->getContext(); 22610b57cec5SDimitry Andric llvm::MDBuilder MDB(Ctx); 22620b57cec5SDimitry Andric 22630b57cec5SDimitry Andric // The payload indices are all but the first one in the encoding. The first 22640b57cec5SDimitry Andric // identifies the callback callee. 22650b57cec5SDimitry Andric int CalleeIdx = *CB->encoding_begin(); 22660b57cec5SDimitry Andric ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 22670b57cec5SDimitry Andric F->addMetadata(llvm::LLVMContext::MD_callback, 22680b57cec5SDimitry Andric *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 22690b57cec5SDimitry Andric CalleeIdx, PayloadIndices, 22700b57cec5SDimitry Andric /* VarArgsArePassed */ false)})); 22710b57cec5SDimitry Andric } 22720b57cec5SDimitry Andric } 22730b57cec5SDimitry Andric 22740b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2275e8d8bef9SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 22760b57cec5SDimitry Andric "Only globals with definition can force usage."); 22770b57cec5SDimitry Andric LLVMUsed.emplace_back(GV); 22780b57cec5SDimitry Andric } 22790b57cec5SDimitry Andric 22800b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 22810b57cec5SDimitry Andric assert(!GV->isDeclaration() && 22820b57cec5SDimitry Andric "Only globals with definition can force usage."); 22830b57cec5SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 22840b57cec5SDimitry Andric } 22850b57cec5SDimitry Andric 2286fe6060f1SDimitry Andric void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2287fe6060f1SDimitry Andric assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2288fe6060f1SDimitry Andric "Only globals with definition can force usage."); 2289fe6060f1SDimitry Andric if (getTriple().isOSBinFormatELF()) 2290fe6060f1SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 2291fe6060f1SDimitry Andric else 2292fe6060f1SDimitry Andric LLVMUsed.emplace_back(GV); 2293fe6060f1SDimitry Andric } 2294fe6060f1SDimitry Andric 22950b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 22960b57cec5SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 22970b57cec5SDimitry Andric // Don't create llvm.used if there is no need. 22980b57cec5SDimitry Andric if (List.empty()) 22990b57cec5SDimitry Andric return; 23000b57cec5SDimitry Andric 23010b57cec5SDimitry Andric // Convert List to what ConstantArray needs. 23020b57cec5SDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 23030b57cec5SDimitry Andric UsedArray.resize(List.size()); 23040b57cec5SDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 23050b57cec5SDimitry Andric UsedArray[i] = 23060b57cec5SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 23070b57cec5SDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 23080b57cec5SDimitry Andric } 23090b57cec5SDimitry Andric 23100b57cec5SDimitry Andric if (UsedArray.empty()) 23110b57cec5SDimitry Andric return; 23120b57cec5SDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 23130b57cec5SDimitry Andric 23140b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 23150b57cec5SDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 23160b57cec5SDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 23170b57cec5SDimitry Andric 23180b57cec5SDimitry Andric GV->setSection("llvm.metadata"); 23190b57cec5SDimitry Andric } 23200b57cec5SDimitry Andric 23210b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() { 23220b57cec5SDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 23230b57cec5SDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 23240b57cec5SDimitry Andric } 23250b57cec5SDimitry Andric 23260b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 23270b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 23280b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 23290b57cec5SDimitry Andric } 23300b57cec5SDimitry Andric 23310b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 23320b57cec5SDimitry Andric llvm::SmallString<32> Opt; 23330b57cec5SDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2334480093f4SDimitry Andric if (Opt.empty()) 2335480093f4SDimitry Andric return; 23360b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 23370b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 23380b57cec5SDimitry Andric } 23390b57cec5SDimitry Andric 23400b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 23410b57cec5SDimitry Andric auto &C = getLLVMContext(); 23420b57cec5SDimitry Andric if (getTarget().getTriple().isOSBinFormatELF()) { 23430b57cec5SDimitry Andric ELFDependentLibraries.push_back( 23440b57cec5SDimitry Andric llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 23450b57cec5SDimitry Andric return; 23460b57cec5SDimitry Andric } 23470b57cec5SDimitry Andric 23480b57cec5SDimitry Andric llvm::SmallString<24> Opt; 23490b57cec5SDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 23500b57cec5SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 23510b57cec5SDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric 23540b57cec5SDimitry Andric /// Add link options implied by the given module, including modules 23550b57cec5SDimitry Andric /// it depends on, using a postorder walk. 23560b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 23570b57cec5SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 23580b57cec5SDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 23590b57cec5SDimitry Andric // Import this module's parent. 23600b57cec5SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 23610b57cec5SDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 23620b57cec5SDimitry Andric } 23630b57cec5SDimitry Andric 23640b57cec5SDimitry Andric // Import this module's dependencies. 2365349cc55cSDimitry Andric for (Module *Import : llvm::reverse(Mod->Imports)) { 2366349cc55cSDimitry Andric if (Visited.insert(Import).second) 2367349cc55cSDimitry Andric addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 23680b57cec5SDimitry Andric } 23690b57cec5SDimitry Andric 23700b57cec5SDimitry Andric // Add linker options to link against the libraries/frameworks 23710b57cec5SDimitry Andric // described by this module. 23720b57cec5SDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 23730b57cec5SDimitry Andric bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 23740b57cec5SDimitry Andric 23750b57cec5SDimitry Andric // For modules that use export_as for linking, use that module 23760b57cec5SDimitry Andric // name instead. 23770b57cec5SDimitry Andric if (Mod->UseExportAsModuleLinkName) 23780b57cec5SDimitry Andric return; 23790b57cec5SDimitry Andric 2380349cc55cSDimitry Andric for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 23810b57cec5SDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 23820b57cec5SDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2383349cc55cSDimitry Andric if (LL.IsFramework) { 2384349cc55cSDimitry Andric llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2385349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library)}; 23860b57cec5SDimitry Andric 23870b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 23880b57cec5SDimitry Andric continue; 23890b57cec5SDimitry Andric } 23900b57cec5SDimitry Andric 23910b57cec5SDimitry Andric // Link against a library. 23920b57cec5SDimitry Andric if (IsELF) { 23930b57cec5SDimitry Andric llvm::Metadata *Args[2] = { 23940b57cec5SDimitry Andric llvm::MDString::get(Context, "lib"), 2395349cc55cSDimitry Andric llvm::MDString::get(Context, LL.Library), 23960b57cec5SDimitry Andric }; 23970b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 23980b57cec5SDimitry Andric } else { 23990b57cec5SDimitry Andric llvm::SmallString<24> Opt; 2400349cc55cSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 24010b57cec5SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 24020b57cec5SDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 24030b57cec5SDimitry Andric } 24040b57cec5SDimitry Andric } 24050b57cec5SDimitry Andric } 24060b57cec5SDimitry Andric 24070b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 24080b57cec5SDimitry Andric // Collect the set of all of the modules we want to visit to emit link 24090b57cec5SDimitry Andric // options, which is essentially the imported modules and all of their 24100b57cec5SDimitry Andric // non-explicit child modules. 24110b57cec5SDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 24120b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 24130b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 24140b57cec5SDimitry Andric 24150b57cec5SDimitry Andric // Seed the stack with imported modules. 24160b57cec5SDimitry Andric for (Module *M : ImportedModules) { 24170b57cec5SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 24180b57cec5SDimitry Andric // a header of that same module. 24190b57cec5SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 24200b57cec5SDimitry Andric !getLangOpts().isCompilingModule()) 24210b57cec5SDimitry Andric continue; 24220b57cec5SDimitry Andric if (Visited.insert(M).second) 24230b57cec5SDimitry Andric Stack.push_back(M); 24240b57cec5SDimitry Andric } 24250b57cec5SDimitry Andric 24260b57cec5SDimitry Andric // Find all of the modules to import, making a little effort to prune 24270b57cec5SDimitry Andric // non-leaf modules. 24280b57cec5SDimitry Andric while (!Stack.empty()) { 24290b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 24300b57cec5SDimitry Andric 24310b57cec5SDimitry Andric bool AnyChildren = false; 24320b57cec5SDimitry Andric 24330b57cec5SDimitry Andric // Visit the submodules of this module. 24340b57cec5SDimitry Andric for (const auto &SM : Mod->submodules()) { 24350b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to be 24360b57cec5SDimitry Andric // linked against. 24370b57cec5SDimitry Andric if (SM->IsExplicit) 24380b57cec5SDimitry Andric continue; 24390b57cec5SDimitry Andric 24400b57cec5SDimitry Andric if (Visited.insert(SM).second) { 24410b57cec5SDimitry Andric Stack.push_back(SM); 24420b57cec5SDimitry Andric AnyChildren = true; 24430b57cec5SDimitry Andric } 24440b57cec5SDimitry Andric } 24450b57cec5SDimitry Andric 24460b57cec5SDimitry Andric // We didn't find any children, so add this module to the list of 24470b57cec5SDimitry Andric // modules to link against. 24480b57cec5SDimitry Andric if (!AnyChildren) { 24490b57cec5SDimitry Andric LinkModules.insert(Mod); 24500b57cec5SDimitry Andric } 24510b57cec5SDimitry Andric } 24520b57cec5SDimitry Andric 24530b57cec5SDimitry Andric // Add link options for all of the imported modules in reverse topological 24540b57cec5SDimitry Andric // order. We don't do anything to try to order import link flags with respect 24550b57cec5SDimitry Andric // to linker options inserted by things like #pragma comment(). 24560b57cec5SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 24570b57cec5SDimitry Andric Visited.clear(); 24580b57cec5SDimitry Andric for (Module *M : LinkModules) 24590b57cec5SDimitry Andric if (Visited.insert(M).second) 24600b57cec5SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 24610b57cec5SDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 24620b57cec5SDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 24630b57cec5SDimitry Andric 24640b57cec5SDimitry Andric // Add the linker options metadata flag. 24650b57cec5SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 24660b57cec5SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 24670b57cec5SDimitry Andric NMD->addOperand(MD); 24680b57cec5SDimitry Andric } 24690b57cec5SDimitry Andric 24700b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() { 24710b57cec5SDimitry Andric // Emit deferred declare target declarations. 24720b57cec5SDimitry Andric if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 24730b57cec5SDimitry Andric getOpenMPRuntime().emitDeferredTargetDecls(); 24740b57cec5SDimitry Andric 24750b57cec5SDimitry Andric // Emit code for any potentially referenced deferred decls. Since a 24760b57cec5SDimitry Andric // previously unused static decl may become used during the generation of code 24770b57cec5SDimitry Andric // for a static function, iterate until no changes are made. 24780b57cec5SDimitry Andric 24790b57cec5SDimitry Andric if (!DeferredVTables.empty()) { 24800b57cec5SDimitry Andric EmitDeferredVTables(); 24810b57cec5SDimitry Andric 24820b57cec5SDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 24830b57cec5SDimitry Andric // become deferred, although it can cause functions to be 24840b57cec5SDimitry Andric // emitted that then need those vtables. 24850b57cec5SDimitry Andric assert(DeferredVTables.empty()); 24860b57cec5SDimitry Andric } 24870b57cec5SDimitry Andric 2488e8d8bef9SDimitry Andric // Emit CUDA/HIP static device variables referenced by host code only. 2489fe6060f1SDimitry Andric // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2490fe6060f1SDimitry Andric // needed for further handling. 2491fe6060f1SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2492fe6060f1SDimitry Andric for (const auto *V : getContext().CUDADeviceVarODRUsedByHost) 2493e8d8bef9SDimitry Andric DeferredDeclsToEmit.push_back(V); 2494e8d8bef9SDimitry Andric 24950b57cec5SDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 24960b57cec5SDimitry Andric if (DeferredDeclsToEmit.empty()) 24970b57cec5SDimitry Andric return; 24980b57cec5SDimitry Andric 24990b57cec5SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 25000b57cec5SDimitry Andric // work, it will not interfere with this. 25010b57cec5SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 25020b57cec5SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 25030b57cec5SDimitry Andric 25040b57cec5SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 25050b57cec5SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 25060b57cec5SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 25070b57cec5SDimitry Andric // might had been created for another decl with the same mangled name but 25080b57cec5SDimitry Andric // different type. 25090b57cec5SDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 25100b57cec5SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 25110b57cec5SDimitry Andric 25120b57cec5SDimitry Andric // In case of different address spaces, we may still get a cast, even with 25130b57cec5SDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 25140b57cec5SDimitry Andric // GlobalValue. 25150b57cec5SDimitry Andric if (!GV) 25160b57cec5SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 25170b57cec5SDimitry Andric 25180b57cec5SDimitry Andric // Make sure GetGlobalValue returned non-null. 25190b57cec5SDimitry Andric assert(GV); 25200b57cec5SDimitry Andric 25210b57cec5SDimitry Andric // Check to see if we've already emitted this. This is necessary 25220b57cec5SDimitry Andric // for a couple of reasons: first, decls can end up in the 25230b57cec5SDimitry Andric // deferred-decls queue multiple times, and second, decls can end 25240b57cec5SDimitry Andric // up with definitions in unusual ways (e.g. by an extern inline 25250b57cec5SDimitry Andric // function acquiring a strong function redefinition). Just 25260b57cec5SDimitry Andric // ignore these cases. 25270b57cec5SDimitry Andric if (!GV->isDeclaration()) 25280b57cec5SDimitry Andric continue; 25290b57cec5SDimitry Andric 2530a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 2531a7dea167SDimitry Andric if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2532a7dea167SDimitry Andric continue; 2533a7dea167SDimitry Andric 25340b57cec5SDimitry Andric // Otherwise, emit the definition and move on to the next one. 25350b57cec5SDimitry Andric EmitGlobalDefinition(D, GV); 25360b57cec5SDimitry Andric 25370b57cec5SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 25380b57cec5SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 25390b57cec5SDimitry Andric // ones are close together, which is convenient for testing. 25400b57cec5SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 25410b57cec5SDimitry Andric EmitDeferred(); 25420b57cec5SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 25430b57cec5SDimitry Andric } 25440b57cec5SDimitry Andric } 25450b57cec5SDimitry Andric } 25460b57cec5SDimitry Andric 25470b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 25480b57cec5SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 25490b57cec5SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 25500b57cec5SDimitry Andric // is not allowed to create new references to things that need to be emitted 25510b57cec5SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 25520b57cec5SDimitry Andric 25530b57cec5SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 25540b57cec5SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 25550b57cec5SDimitry Andric 25560b57cec5SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 25570b57cec5SDimitry Andric assert(getVTables().isVTableExternal(RD) && 25580b57cec5SDimitry Andric "This queue should only contain external vtables"); 25590b57cec5SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 25600b57cec5SDimitry Andric VTables.GenerateClassData(RD); 25610b57cec5SDimitry Andric } 25620b57cec5SDimitry Andric OpportunisticVTables.clear(); 25630b57cec5SDimitry Andric } 25640b57cec5SDimitry Andric 25650b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 25660b57cec5SDimitry Andric if (Annotations.empty()) 25670b57cec5SDimitry Andric return; 25680b57cec5SDimitry Andric 25690b57cec5SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 25700b57cec5SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 25710b57cec5SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 25720b57cec5SDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 25730b57cec5SDimitry Andric llvm::GlobalValue::AppendingLinkage, 25740b57cec5SDimitry Andric Array, "llvm.global.annotations"); 25750b57cec5SDimitry Andric gv->setSection(AnnotationSection); 25760b57cec5SDimitry Andric } 25770b57cec5SDimitry Andric 25780b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 25790b57cec5SDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 25800b57cec5SDimitry Andric if (AStr) 25810b57cec5SDimitry Andric return AStr; 25820b57cec5SDimitry Andric 25830b57cec5SDimitry Andric // Not found yet, create a new global. 25840b57cec5SDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 25850b57cec5SDimitry Andric auto *gv = 25860b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 25870b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 25880b57cec5SDimitry Andric gv->setSection(AnnotationSection); 25890b57cec5SDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 25900b57cec5SDimitry Andric AStr = gv; 25910b57cec5SDimitry Andric return gv; 25920b57cec5SDimitry Andric } 25930b57cec5SDimitry Andric 25940b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 25950b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 25960b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 25970b57cec5SDimitry Andric if (PLoc.isValid()) 25980b57cec5SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 25990b57cec5SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 26000b57cec5SDimitry Andric } 26010b57cec5SDimitry Andric 26020b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 26030b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 26040b57cec5SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 26050b57cec5SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 26060b57cec5SDimitry Andric SM.getExpansionLineNumber(L); 26070b57cec5SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 26080b57cec5SDimitry Andric } 26090b57cec5SDimitry Andric 2610e8d8bef9SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2611e8d8bef9SDimitry Andric ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2612e8d8bef9SDimitry Andric if (Exprs.empty()) 2613349cc55cSDimitry Andric return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2614e8d8bef9SDimitry Andric 2615e8d8bef9SDimitry Andric llvm::FoldingSetNodeID ID; 2616e8d8bef9SDimitry Andric for (Expr *E : Exprs) { 2617e8d8bef9SDimitry Andric ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2618e8d8bef9SDimitry Andric } 2619e8d8bef9SDimitry Andric llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2620e8d8bef9SDimitry Andric if (Lookup) 2621e8d8bef9SDimitry Andric return Lookup; 2622e8d8bef9SDimitry Andric 2623e8d8bef9SDimitry Andric llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2624e8d8bef9SDimitry Andric LLVMArgs.reserve(Exprs.size()); 2625e8d8bef9SDimitry Andric ConstantEmitter ConstEmiter(*this); 2626e8d8bef9SDimitry Andric llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2627e8d8bef9SDimitry Andric const auto *CE = cast<clang::ConstantExpr>(E); 2628e8d8bef9SDimitry Andric return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2629e8d8bef9SDimitry Andric CE->getType()); 2630e8d8bef9SDimitry Andric }); 2631e8d8bef9SDimitry Andric auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2632e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2633e8d8bef9SDimitry Andric llvm::GlobalValue::PrivateLinkage, Struct, 2634e8d8bef9SDimitry Andric ".args"); 2635e8d8bef9SDimitry Andric GV->setSection(AnnotationSection); 2636e8d8bef9SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2637349cc55cSDimitry Andric auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2638e8d8bef9SDimitry Andric 2639e8d8bef9SDimitry Andric Lookup = Bitcasted; 2640e8d8bef9SDimitry Andric return Bitcasted; 2641e8d8bef9SDimitry Andric } 2642e8d8bef9SDimitry Andric 26430b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 26440b57cec5SDimitry Andric const AnnotateAttr *AA, 26450b57cec5SDimitry Andric SourceLocation L) { 26460b57cec5SDimitry Andric // Get the globals for file name, annotation, and the line number. 26470b57cec5SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 26480b57cec5SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 2649e8d8bef9SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L), 2650e8d8bef9SDimitry Andric *Args = EmitAnnotationArgs(AA); 26510b57cec5SDimitry Andric 2652349cc55cSDimitry Andric llvm::Constant *GVInGlobalsAS = GV; 2653349cc55cSDimitry Andric if (GV->getAddressSpace() != 2654349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace()) { 2655349cc55cSDimitry Andric GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2656349cc55cSDimitry Andric GV, GV->getValueType()->getPointerTo( 2657349cc55cSDimitry Andric getDataLayout().getDefaultGlobalsAddressSpace())); 2658480093f4SDimitry Andric } 2659480093f4SDimitry Andric 26600b57cec5SDimitry Andric // Create the ConstantStruct for the global annotation. 2661e8d8bef9SDimitry Andric llvm::Constant *Fields[] = { 2662349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2663349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2664349cc55cSDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2665e8d8bef9SDimitry Andric LineNoCst, 2666e8d8bef9SDimitry Andric Args, 26670b57cec5SDimitry Andric }; 26680b57cec5SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 26690b57cec5SDimitry Andric } 26700b57cec5SDimitry Andric 26710b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 26720b57cec5SDimitry Andric llvm::GlobalValue *GV) { 26730b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 26740b57cec5SDimitry Andric // Get the struct elements for these annotations. 26750b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 26760b57cec5SDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 26770b57cec5SDimitry Andric } 26780b57cec5SDimitry Andric 2679fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 26800b57cec5SDimitry Andric SourceLocation Loc) const { 2681fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2682fe6060f1SDimitry Andric // NoSanitize by function name. 2683fe6060f1SDimitry Andric if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 26840b57cec5SDimitry Andric return true; 2685fe6060f1SDimitry Andric // NoSanitize by location. 26860b57cec5SDimitry Andric if (Loc.isValid()) 2687fe6060f1SDimitry Andric return NoSanitizeL.containsLocation(Kind, Loc); 26880b57cec5SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 26890b57cec5SDimitry Andric // it's located in the main file. 26900b57cec5SDimitry Andric auto &SM = Context.getSourceManager(); 26910b57cec5SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2692fe6060f1SDimitry Andric return NoSanitizeL.containsFile(Kind, MainFile->getName()); 26930b57cec5SDimitry Andric } 26940b57cec5SDimitry Andric return false; 26950b57cec5SDimitry Andric } 26960b57cec5SDimitry Andric 2697fe6060f1SDimitry Andric bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV, 26980b57cec5SDimitry Andric SourceLocation Loc, QualType Ty, 26990b57cec5SDimitry Andric StringRef Category) const { 2700fe6060f1SDimitry Andric // For now globals can be ignored only in ASan and KASan. 27010b57cec5SDimitry Andric const SanitizerMask EnabledAsanMask = 27020b57cec5SDimitry Andric LangOpts.Sanitize.Mask & 27030b57cec5SDimitry Andric (SanitizerKind::Address | SanitizerKind::KernelAddress | 27040b57cec5SDimitry Andric SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 27050b57cec5SDimitry Andric SanitizerKind::MemTag); 27060b57cec5SDimitry Andric if (!EnabledAsanMask) 27070b57cec5SDimitry Andric return false; 2708fe6060f1SDimitry Andric const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2709fe6060f1SDimitry Andric if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category)) 27100b57cec5SDimitry Andric return true; 2711fe6060f1SDimitry Andric if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category)) 27120b57cec5SDimitry Andric return true; 27130b57cec5SDimitry Andric // Check global type. 27140b57cec5SDimitry Andric if (!Ty.isNull()) { 27150b57cec5SDimitry Andric // Drill down the array types: if global variable of a fixed type is 2716fe6060f1SDimitry Andric // not sanitized, we also don't instrument arrays of them. 27170b57cec5SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 27180b57cec5SDimitry Andric Ty = AT->getElementType(); 27190b57cec5SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 2720fe6060f1SDimitry Andric // Only record types (classes, structs etc.) are ignored. 27210b57cec5SDimitry Andric if (Ty->isRecordType()) { 27220b57cec5SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2723fe6060f1SDimitry Andric if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category)) 27240b57cec5SDimitry Andric return true; 27250b57cec5SDimitry Andric } 27260b57cec5SDimitry Andric } 27270b57cec5SDimitry Andric return false; 27280b57cec5SDimitry Andric } 27290b57cec5SDimitry Andric 27300b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 27310b57cec5SDimitry Andric StringRef Category) const { 27320b57cec5SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 27330b57cec5SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 27340b57cec5SDimitry Andric auto Attr = ImbueAttr::NONE; 27350b57cec5SDimitry Andric if (Loc.isValid()) 27360b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 27370b57cec5SDimitry Andric if (Attr == ImbueAttr::NONE) 27380b57cec5SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 27390b57cec5SDimitry Andric switch (Attr) { 27400b57cec5SDimitry Andric case ImbueAttr::NONE: 27410b57cec5SDimitry Andric return false; 27420b57cec5SDimitry Andric case ImbueAttr::ALWAYS: 27430b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 27440b57cec5SDimitry Andric break; 27450b57cec5SDimitry Andric case ImbueAttr::ALWAYS_ARG1: 27460b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 27470b57cec5SDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 27480b57cec5SDimitry Andric break; 27490b57cec5SDimitry Andric case ImbueAttr::NEVER: 27500b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 27510b57cec5SDimitry Andric break; 27520b57cec5SDimitry Andric } 27530b57cec5SDimitry Andric return true; 27540b57cec5SDimitry Andric } 27550b57cec5SDimitry Andric 2756e8d8bef9SDimitry Andric bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, 2757e8d8bef9SDimitry Andric SourceLocation Loc) const { 2758e8d8bef9SDimitry Andric const auto &ProfileList = getContext().getProfileList(); 2759e8d8bef9SDimitry Andric // If the profile list is empty, then instrument everything. 2760e8d8bef9SDimitry Andric if (ProfileList.isEmpty()) 2761e8d8bef9SDimitry Andric return false; 2762e8d8bef9SDimitry Andric CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2763e8d8bef9SDimitry Andric // First, check the function name. 2764e8d8bef9SDimitry Andric Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); 2765e8d8bef9SDimitry Andric if (V.hasValue()) 2766e8d8bef9SDimitry Andric return *V; 2767e8d8bef9SDimitry Andric // Next, check the source location. 2768e8d8bef9SDimitry Andric if (Loc.isValid()) { 2769e8d8bef9SDimitry Andric Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2770e8d8bef9SDimitry Andric if (V.hasValue()) 2771e8d8bef9SDimitry Andric return *V; 2772e8d8bef9SDimitry Andric } 2773e8d8bef9SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 2774e8d8bef9SDimitry Andric // it's located in the main file. 2775e8d8bef9SDimitry Andric auto &SM = Context.getSourceManager(); 2776e8d8bef9SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2777e8d8bef9SDimitry Andric Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind); 2778e8d8bef9SDimitry Andric if (V.hasValue()) 2779e8d8bef9SDimitry Andric return *V; 2780e8d8bef9SDimitry Andric } 2781e8d8bef9SDimitry Andric return ProfileList.getDefault(); 2782e8d8bef9SDimitry Andric } 2783e8d8bef9SDimitry Andric 27840b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 27850b57cec5SDimitry Andric // Never defer when EmitAllDecls is specified. 27860b57cec5SDimitry Andric if (LangOpts.EmitAllDecls) 27870b57cec5SDimitry Andric return true; 27880b57cec5SDimitry Andric 27890b57cec5SDimitry Andric if (CodeGenOpts.KeepStaticConsts) { 27900b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(Global); 27910b57cec5SDimitry Andric if (VD && VD->getType().isConstQualified() && 27920b57cec5SDimitry Andric VD->getStorageDuration() == SD_Static) 27930b57cec5SDimitry Andric return true; 27940b57cec5SDimitry Andric } 27950b57cec5SDimitry Andric 27960b57cec5SDimitry Andric return getContext().DeclMustBeEmitted(Global); 27970b57cec5SDimitry Andric } 27980b57cec5SDimitry Andric 27990b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2800fe6060f1SDimitry Andric // In OpenMP 5.0 variables and function may be marked as 2801fe6060f1SDimitry Andric // device_type(host/nohost) and we should not emit them eagerly unless we sure 2802fe6060f1SDimitry Andric // that they must be emitted on the host/device. To be sure we need to have 2803fe6060f1SDimitry Andric // seen a declare target with an explicit mentioning of the function, we know 2804fe6060f1SDimitry Andric // we have if the level of the declare target attribute is -1. Note that we 2805fe6060f1SDimitry Andric // check somewhere else if we should emit this at all. 2806fe6060f1SDimitry Andric if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 2807fe6060f1SDimitry Andric llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 2808fe6060f1SDimitry Andric OMPDeclareTargetDeclAttr::getActiveAttr(Global); 2809fe6060f1SDimitry Andric if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 2810fe6060f1SDimitry Andric return false; 2811fe6060f1SDimitry Andric } 2812fe6060f1SDimitry Andric 2813a7dea167SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 28140b57cec5SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 28150b57cec5SDimitry Andric // Implicit template instantiations may change linkage if they are later 28160b57cec5SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 28170b57cec5SDimitry Andric return false; 2818a7dea167SDimitry Andric } 28190b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 28200b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 28210b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 28220b57cec5SDimitry Andric // A definition of an inline constexpr static data member may change 28230b57cec5SDimitry Andric // linkage later if it's redeclared outside the class. 28240b57cec5SDimitry Andric return false; 28250b57cec5SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 28260b57cec5SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 28270b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 28280b57cec5SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 28290b57cec5SDimitry Andric !isTypeConstant(Global->getType(), false) && 28300b57cec5SDimitry Andric !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 28310b57cec5SDimitry Andric return false; 28320b57cec5SDimitry Andric 28330b57cec5SDimitry Andric return true; 28340b57cec5SDimitry Andric } 28350b57cec5SDimitry Andric 28365ffd83dbSDimitry Andric ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 28375ffd83dbSDimitry Andric StringRef Name = getMangledName(GD); 28380b57cec5SDimitry Andric 28390b57cec5SDimitry Andric // The UUID descriptor should be pointer aligned. 28400b57cec5SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 28410b57cec5SDimitry Andric 28420b57cec5SDimitry Andric // Look for an existing global. 28430b57cec5SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 28440eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 28450b57cec5SDimitry Andric 28465ffd83dbSDimitry Andric ConstantEmitter Emitter(*this); 28475ffd83dbSDimitry Andric llvm::Constant *Init; 28485ffd83dbSDimitry Andric 28495ffd83dbSDimitry Andric APValue &V = GD->getAsAPValue(); 28505ffd83dbSDimitry Andric if (!V.isAbsent()) { 28515ffd83dbSDimitry Andric // If possible, emit the APValue version of the initializer. In particular, 28525ffd83dbSDimitry Andric // this gets the type of the constant right. 28535ffd83dbSDimitry Andric Init = Emitter.emitForInitializer( 28545ffd83dbSDimitry Andric GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 28555ffd83dbSDimitry Andric } else { 28565ffd83dbSDimitry Andric // As a fallback, directly construct the constant. 28575ffd83dbSDimitry Andric // FIXME: This may get padding wrong under esoteric struct layout rules. 28585ffd83dbSDimitry Andric // MSVC appears to create a complete type 'struct __s_GUID' that it 28595ffd83dbSDimitry Andric // presumably uses to represent these constants. 28605ffd83dbSDimitry Andric MSGuidDecl::Parts Parts = GD->getParts(); 28615ffd83dbSDimitry Andric llvm::Constant *Fields[4] = { 28625ffd83dbSDimitry Andric llvm::ConstantInt::get(Int32Ty, Parts.Part1), 28635ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part2), 28645ffd83dbSDimitry Andric llvm::ConstantInt::get(Int16Ty, Parts.Part3), 28655ffd83dbSDimitry Andric llvm::ConstantDataArray::getRaw( 28665ffd83dbSDimitry Andric StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 28675ffd83dbSDimitry Andric Int8Ty)}; 28685ffd83dbSDimitry Andric Init = llvm::ConstantStruct::getAnon(Fields); 28695ffd83dbSDimitry Andric } 28700b57cec5SDimitry Andric 28710b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 28720b57cec5SDimitry Andric getModule(), Init->getType(), 28730b57cec5SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 28740b57cec5SDimitry Andric if (supportsCOMDAT()) 28750b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 28760b57cec5SDimitry Andric setDSOLocal(GV); 28775ffd83dbSDimitry Andric 28785ffd83dbSDimitry Andric if (!V.isAbsent()) { 28795ffd83dbSDimitry Andric Emitter.finalize(GV); 28800eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 28815ffd83dbSDimitry Andric } 28820eae32dcSDimitry Andric 28830eae32dcSDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 28840eae32dcSDimitry Andric llvm::Constant *Addr = llvm::ConstantExpr::getBitCast( 28850eae32dcSDimitry Andric GV, Ty->getPointerTo(GV->getAddressSpace())); 28860eae32dcSDimitry Andric return ConstantAddress(Addr, Ty, Alignment); 28870b57cec5SDimitry Andric } 28880b57cec5SDimitry Andric 2889e8d8bef9SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 2890e8d8bef9SDimitry Andric const TemplateParamObjectDecl *TPO) { 2891e8d8bef9SDimitry Andric StringRef Name = getMangledName(TPO); 2892e8d8bef9SDimitry Andric CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 2893e8d8bef9SDimitry Andric 2894e8d8bef9SDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 28950eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 2896e8d8bef9SDimitry Andric 2897e8d8bef9SDimitry Andric ConstantEmitter Emitter(*this); 2898e8d8bef9SDimitry Andric llvm::Constant *Init = Emitter.emitForInitializer( 2899e8d8bef9SDimitry Andric TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 2900e8d8bef9SDimitry Andric 2901e8d8bef9SDimitry Andric if (!Init) { 2902e8d8bef9SDimitry Andric ErrorUnsupported(TPO, "template parameter object"); 2903e8d8bef9SDimitry Andric return ConstantAddress::invalid(); 2904e8d8bef9SDimitry Andric } 2905e8d8bef9SDimitry Andric 2906e8d8bef9SDimitry Andric auto *GV = new llvm::GlobalVariable( 2907e8d8bef9SDimitry Andric getModule(), Init->getType(), 2908e8d8bef9SDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2909e8d8bef9SDimitry Andric if (supportsCOMDAT()) 2910e8d8bef9SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2911e8d8bef9SDimitry Andric Emitter.finalize(GV); 2912e8d8bef9SDimitry Andric 29130eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 2914e8d8bef9SDimitry Andric } 2915e8d8bef9SDimitry Andric 29160b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 29170b57cec5SDimitry Andric const AliasAttr *AA = VD->getAttr<AliasAttr>(); 29180b57cec5SDimitry Andric assert(AA && "No alias?"); 29190b57cec5SDimitry Andric 29200b57cec5SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 29210b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 29220b57cec5SDimitry Andric 29230b57cec5SDimitry Andric // See if there is already something with the target's name in the module. 29240b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 29250b57cec5SDimitry Andric if (Entry) { 29260b57cec5SDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 29270b57cec5SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 29280eae32dcSDimitry Andric return ConstantAddress(Ptr, DeclTy, Alignment); 29290b57cec5SDimitry Andric } 29300b57cec5SDimitry Andric 29310b57cec5SDimitry Andric llvm::Constant *Aliasee; 29320b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) 29330b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 29340b57cec5SDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 29350b57cec5SDimitry Andric /*ForVTable=*/false); 29360b57cec5SDimitry Andric else 2937349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 2938349cc55cSDimitry Andric nullptr); 29390b57cec5SDimitry Andric 29400b57cec5SDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 29410b57cec5SDimitry Andric F->setLinkage(llvm::Function::ExternalWeakLinkage); 29420b57cec5SDimitry Andric WeakRefReferences.insert(F); 29430b57cec5SDimitry Andric 29440eae32dcSDimitry Andric return ConstantAddress(Aliasee, DeclTy, Alignment); 29450b57cec5SDimitry Andric } 29460b57cec5SDimitry Andric 29470b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) { 29480b57cec5SDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 29490b57cec5SDimitry Andric 29500b57cec5SDimitry Andric // Weak references don't produce any output by themselves. 29510b57cec5SDimitry Andric if (Global->hasAttr<WeakRefAttr>()) 29520b57cec5SDimitry Andric return; 29530b57cec5SDimitry Andric 29540b57cec5SDimitry Andric // If this is an alias definition (which otherwise looks like a declaration) 29550b57cec5SDimitry Andric // emit it now. 29560b57cec5SDimitry Andric if (Global->hasAttr<AliasAttr>()) 29570b57cec5SDimitry Andric return EmitAliasDefinition(GD); 29580b57cec5SDimitry Andric 29590b57cec5SDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 29600b57cec5SDimitry Andric if (Global->hasAttr<IFuncAttr>()) 29610b57cec5SDimitry Andric return emitIFuncDefinition(GD); 29620b57cec5SDimitry Andric 29630b57cec5SDimitry Andric // If this is a cpu_dispatch multiversion function, emit the resolver. 29640b57cec5SDimitry Andric if (Global->hasAttr<CPUDispatchAttr>()) 29650b57cec5SDimitry Andric return emitCPUDispatchDefinition(GD); 29660b57cec5SDimitry Andric 29670b57cec5SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 29680b57cec5SDimitry Andric if (LangOpts.CUDA) { 29690b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 29700b57cec5SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 29710b57cec5SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 29720b57cec5SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 29730b57cec5SDimitry Andric !Global->hasAttr<CUDASharedAttr>() && 29745ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 29755ffd83dbSDimitry Andric !Global->getType()->isCUDADeviceBuiltinTextureType()) 29760b57cec5SDimitry Andric return; 29770b57cec5SDimitry Andric } else { 29780b57cec5SDimitry Andric // We need to emit host-side 'shadows' for all global 29790b57cec5SDimitry Andric // device-side variables because the CUDA runtime needs their 29800b57cec5SDimitry Andric // size and host-side address in order to provide access to 29810b57cec5SDimitry Andric // their device-side incarnations. 29820b57cec5SDimitry Andric 29830b57cec5SDimitry Andric // So device-only functions are the only things we skip. 29840b57cec5SDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 29850b57cec5SDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 29860b57cec5SDimitry Andric return; 29870b57cec5SDimitry Andric 29880b57cec5SDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 29890b57cec5SDimitry Andric "Expected Variable or Function"); 29900b57cec5SDimitry Andric } 29910b57cec5SDimitry Andric } 29920b57cec5SDimitry Andric 29930b57cec5SDimitry Andric if (LangOpts.OpenMP) { 2994a7dea167SDimitry Andric // If this is OpenMP, check if it is legal to emit this global normally. 29950b57cec5SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 29960b57cec5SDimitry Andric return; 29970b57cec5SDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 29980b57cec5SDimitry Andric if (MustBeEmitted(Global)) 29990b57cec5SDimitry Andric EmitOMPDeclareReduction(DRD); 30000b57cec5SDimitry Andric return; 30010b57cec5SDimitry Andric } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 30020b57cec5SDimitry Andric if (MustBeEmitted(Global)) 30030b57cec5SDimitry Andric EmitOMPDeclareMapper(DMD); 30040b57cec5SDimitry Andric return; 30050b57cec5SDimitry Andric } 30060b57cec5SDimitry Andric } 30070b57cec5SDimitry Andric 30080b57cec5SDimitry Andric // Ignore declarations, they will be emitted on their first use. 30090b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 30100b57cec5SDimitry Andric // Forward declarations are emitted lazily on first use. 30110b57cec5SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 30120b57cec5SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 30130b57cec5SDimitry Andric return; 30140b57cec5SDimitry Andric 30150b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 30160b57cec5SDimitry Andric 30170b57cec5SDimitry Andric // Compute the function info and LLVM type. 30180b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 30190b57cec5SDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 30200b57cec5SDimitry Andric 30210b57cec5SDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 30220b57cec5SDimitry Andric /*DontDefer=*/false); 30230b57cec5SDimitry Andric return; 30240b57cec5SDimitry Andric } 30250b57cec5SDimitry Andric } else { 30260b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(Global); 30270b57cec5SDimitry Andric assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 30280b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 30290b57cec5SDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 30300b57cec5SDimitry Andric if (LangOpts.OpenMP) { 30310b57cec5SDimitry Andric // Emit declaration of the must-be-emitted declare target variable. 30320b57cec5SDimitry Andric if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 30330b57cec5SDimitry Andric OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 30340b57cec5SDimitry Andric bool UnifiedMemoryEnabled = 30350b57cec5SDimitry Andric getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 30360b57cec5SDimitry Andric if (*Res == OMPDeclareTargetDeclAttr::MT_To && 30370b57cec5SDimitry Andric !UnifiedMemoryEnabled) { 30380b57cec5SDimitry Andric (void)GetAddrOfGlobalVar(VD); 30390b57cec5SDimitry Andric } else { 30400b57cec5SDimitry Andric assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 30410b57cec5SDimitry Andric (*Res == OMPDeclareTargetDeclAttr::MT_To && 30420b57cec5SDimitry Andric UnifiedMemoryEnabled)) && 30430b57cec5SDimitry Andric "Link clause or to clause with unified memory expected."); 30440b57cec5SDimitry Andric (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 30450b57cec5SDimitry Andric } 30460b57cec5SDimitry Andric 30470b57cec5SDimitry Andric return; 30480b57cec5SDimitry Andric } 30490b57cec5SDimitry Andric } 30500b57cec5SDimitry Andric // If this declaration may have caused an inline variable definition to 30510b57cec5SDimitry Andric // change linkage, make sure that it's emitted. 30520b57cec5SDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 30530b57cec5SDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 30540b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 30550b57cec5SDimitry Andric return; 30560b57cec5SDimitry Andric } 30570b57cec5SDimitry Andric } 30580b57cec5SDimitry Andric 30590b57cec5SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 30600b57cec5SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 30610b57cec5SDimitry Andric // to benefit from cache locality. 30620b57cec5SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 30630b57cec5SDimitry Andric // Emit the definition if it can't be deferred. 30640b57cec5SDimitry Andric EmitGlobalDefinition(GD); 30650b57cec5SDimitry Andric return; 30660b57cec5SDimitry Andric } 30670b57cec5SDimitry Andric 30680b57cec5SDimitry Andric // If we're deferring emission of a C++ variable with an 30690b57cec5SDimitry Andric // initializer, remember the order in which it appeared in the file. 30700b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 30710b57cec5SDimitry Andric cast<VarDecl>(Global)->hasInit()) { 30720b57cec5SDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 30730b57cec5SDimitry Andric CXXGlobalInits.push_back(nullptr); 30740b57cec5SDimitry Andric } 30750b57cec5SDimitry Andric 30760b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 30770b57cec5SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 30780b57cec5SDimitry Andric // The value has already been used and should therefore be emitted. 30790b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 30800b57cec5SDimitry Andric } else if (MustBeEmitted(Global)) { 30810b57cec5SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 30820b57cec5SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 30830b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 30840b57cec5SDimitry Andric } else { 30850b57cec5SDimitry Andric // Otherwise, remember that we saw a deferred decl with this name. The 30860b57cec5SDimitry Andric // first use of the mangled name will cause it to move into 30870b57cec5SDimitry Andric // DeferredDeclsToEmit. 30880b57cec5SDimitry Andric DeferredDecls[MangledName] = GD; 30890b57cec5SDimitry Andric } 30900b57cec5SDimitry Andric } 30910b57cec5SDimitry Andric 30920b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 30930b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 30940b57cec5SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 30950b57cec5SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 30960b57cec5SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 30970b57cec5SDimitry Andric return true; 30980b57cec5SDimitry Andric 30990b57cec5SDimitry Andric return false; 31000b57cec5SDimitry Andric } 31010b57cec5SDimitry Andric 31020b57cec5SDimitry Andric namespace { 31030b57cec5SDimitry Andric struct FunctionIsDirectlyRecursive 31040b57cec5SDimitry Andric : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 31050b57cec5SDimitry Andric const StringRef Name; 31060b57cec5SDimitry Andric const Builtin::Context &BI; 31070b57cec5SDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 31080b57cec5SDimitry Andric : Name(N), BI(C) {} 31090b57cec5SDimitry Andric 31100b57cec5SDimitry Andric bool VisitCallExpr(const CallExpr *E) { 31110b57cec5SDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 31120b57cec5SDimitry Andric if (!FD) 31130b57cec5SDimitry Andric return false; 31140b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 31150b57cec5SDimitry Andric if (Attr && Name == Attr->getLabel()) 31160b57cec5SDimitry Andric return true; 31170b57cec5SDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 31180b57cec5SDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 31190b57cec5SDimitry Andric return false; 31200b57cec5SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 31210b57cec5SDimitry Andric if (BuiltinName.startswith("__builtin_") && 31220b57cec5SDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 31230b57cec5SDimitry Andric return true; 31240b57cec5SDimitry Andric } 31250b57cec5SDimitry Andric return false; 31260b57cec5SDimitry Andric } 31270b57cec5SDimitry Andric 31280b57cec5SDimitry Andric bool VisitStmt(const Stmt *S) { 31290b57cec5SDimitry Andric for (const Stmt *Child : S->children()) 31300b57cec5SDimitry Andric if (Child && this->Visit(Child)) 31310b57cec5SDimitry Andric return true; 31320b57cec5SDimitry Andric return false; 31330b57cec5SDimitry Andric } 31340b57cec5SDimitry Andric }; 31350b57cec5SDimitry Andric 31360b57cec5SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 31370b57cec5SDimitry Andric struct DLLImportFunctionVisitor 31380b57cec5SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 31390b57cec5SDimitry Andric bool SafeToInline = true; 31400b57cec5SDimitry Andric 31410b57cec5SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 31420b57cec5SDimitry Andric 31430b57cec5SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 31440b57cec5SDimitry Andric if (VD->getTLSKind()) { 31450b57cec5SDimitry Andric // A thread-local variable cannot be imported. 31460b57cec5SDimitry Andric SafeToInline = false; 31470b57cec5SDimitry Andric return SafeToInline; 31480b57cec5SDimitry Andric } 31490b57cec5SDimitry Andric 31500b57cec5SDimitry Andric // A variable definition might imply a destructor call. 31510b57cec5SDimitry Andric if (VD->isThisDeclarationADefinition()) 31520b57cec5SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 31530b57cec5SDimitry Andric 31540b57cec5SDimitry Andric return SafeToInline; 31550b57cec5SDimitry Andric } 31560b57cec5SDimitry Andric 31570b57cec5SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 31580b57cec5SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 31590b57cec5SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 31600b57cec5SDimitry Andric return SafeToInline; 31610b57cec5SDimitry Andric } 31620b57cec5SDimitry Andric 31630b57cec5SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 31640b57cec5SDimitry Andric ValueDecl *VD = E->getDecl(); 31650b57cec5SDimitry Andric if (isa<FunctionDecl>(VD)) 31660b57cec5SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 31670b57cec5SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 31680b57cec5SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 31690b57cec5SDimitry Andric return SafeToInline; 31700b57cec5SDimitry Andric } 31710b57cec5SDimitry Andric 31720b57cec5SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 31730b57cec5SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 31740b57cec5SDimitry Andric return SafeToInline; 31750b57cec5SDimitry Andric } 31760b57cec5SDimitry Andric 31770b57cec5SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 31780b57cec5SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 31790b57cec5SDimitry Andric if (!M) { 31800b57cec5SDimitry Andric // Call through a pointer to member function. This is safe to inline. 31810b57cec5SDimitry Andric SafeToInline = true; 31820b57cec5SDimitry Andric } else { 31830b57cec5SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 31840b57cec5SDimitry Andric } 31850b57cec5SDimitry Andric return SafeToInline; 31860b57cec5SDimitry Andric } 31870b57cec5SDimitry Andric 31880b57cec5SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 31890b57cec5SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 31900b57cec5SDimitry Andric return SafeToInline; 31910b57cec5SDimitry Andric } 31920b57cec5SDimitry Andric 31930b57cec5SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 31940b57cec5SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 31950b57cec5SDimitry Andric return SafeToInline; 31960b57cec5SDimitry Andric } 31970b57cec5SDimitry Andric }; 31980b57cec5SDimitry Andric } 31990b57cec5SDimitry Andric 32000b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another 32010b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 32020b57cec5SDimitry Andric // ends up pointing to itself. 32030b57cec5SDimitry Andric bool 32040b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 32050b57cec5SDimitry Andric StringRef Name; 32060b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 32070b57cec5SDimitry Andric // asm labels are a special kind of mangling we have to support. 32080b57cec5SDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 32090b57cec5SDimitry Andric if (!Attr) 32100b57cec5SDimitry Andric return false; 32110b57cec5SDimitry Andric Name = Attr->getLabel(); 32120b57cec5SDimitry Andric } else { 32130b57cec5SDimitry Andric Name = FD->getName(); 32140b57cec5SDimitry Andric } 32150b57cec5SDimitry Andric 32160b57cec5SDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 32170b57cec5SDimitry Andric const Stmt *Body = FD->getBody(); 32180b57cec5SDimitry Andric return Body ? Walker.Visit(Body) : false; 32190b57cec5SDimitry Andric } 32200b57cec5SDimitry Andric 32210b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 32220b57cec5SDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 32230b57cec5SDimitry Andric return true; 32240b57cec5SDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 32250b57cec5SDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 32260b57cec5SDimitry Andric return false; 32270b57cec5SDimitry Andric 3228fe6060f1SDimitry Andric if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 32290b57cec5SDimitry Andric // Check whether it would be safe to inline this dllimport function. 32300b57cec5SDimitry Andric DLLImportFunctionVisitor Visitor; 32310b57cec5SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 32320b57cec5SDimitry Andric if (!Visitor.SafeToInline) 32330b57cec5SDimitry Andric return false; 32340b57cec5SDimitry Andric 32350b57cec5SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 32360b57cec5SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 32370b57cec5SDimitry Andric // check above can't see them. Check for them manually here. 32380b57cec5SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 32390b57cec5SDimitry Andric if (isa<FieldDecl>(Member)) 32400b57cec5SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 32410b57cec5SDimitry Andric return false; 32420b57cec5SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 32430b57cec5SDimitry Andric if (HasNonDllImportDtor(B.getType())) 32440b57cec5SDimitry Andric return false; 32450b57cec5SDimitry Andric } 32460b57cec5SDimitry Andric } 32470b57cec5SDimitry Andric 3248349cc55cSDimitry Andric // Inline builtins declaration must be emitted. They often are fortified 3249349cc55cSDimitry Andric // functions. 3250349cc55cSDimitry Andric if (F->isInlineBuiltinDeclaration()) 3251349cc55cSDimitry Andric return true; 3252349cc55cSDimitry Andric 32530b57cec5SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 32540b57cec5SDimitry Andric // externally function should have an equivalent function somewhere else, 32555ffd83dbSDimitry Andric // but a function that calls itself through asm label/`__builtin_` trickery is 32565ffd83dbSDimitry Andric // clearly not equivalent to the real implementation. 32570b57cec5SDimitry Andric // This happens in glibc's btowc and in some configure checks. 32580b57cec5SDimitry Andric return !isTriviallyRecursive(F); 32590b57cec5SDimitry Andric } 32600b57cec5SDimitry Andric 32610b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 32620b57cec5SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 32630b57cec5SDimitry Andric } 32640b57cec5SDimitry Andric 32650b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 32660b57cec5SDimitry Andric llvm::GlobalValue *GV) { 32670b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 32680b57cec5SDimitry Andric 32690b57cec5SDimitry Andric if (FD->isCPUSpecificMultiVersion()) { 32700b57cec5SDimitry Andric auto *Spec = FD->getAttr<CPUSpecificAttr>(); 32710b57cec5SDimitry Andric for (unsigned I = 0; I < Spec->cpus_size(); ++I) 32720b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 32730b57cec5SDimitry Andric // Requires multiple emits. 32744824e7fdSDimitry Andric } else if (FD->isTargetClonesMultiVersion()) { 32754824e7fdSDimitry Andric auto *Clone = FD->getAttr<TargetClonesAttr>(); 32764824e7fdSDimitry Andric for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 32774824e7fdSDimitry Andric if (Clone->isFirstOfVersion(I)) 32784824e7fdSDimitry Andric EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 32794824e7fdSDimitry Andric EmitTargetClonesResolver(GD); 32800b57cec5SDimitry Andric } else 32810b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 32820b57cec5SDimitry Andric } 32830b57cec5SDimitry Andric 32840b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 32850b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 32860b57cec5SDimitry Andric 32870b57cec5SDimitry Andric PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 32880b57cec5SDimitry Andric Context.getSourceManager(), 32890b57cec5SDimitry Andric "Generating code for declaration"); 32900b57cec5SDimitry Andric 32910b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 32920b57cec5SDimitry Andric // At -O0, don't generate IR for functions with available_externally 32930b57cec5SDimitry Andric // linkage. 32940b57cec5SDimitry Andric if (!shouldEmitFunction(GD)) 32950b57cec5SDimitry Andric return; 32960b57cec5SDimitry Andric 32970b57cec5SDimitry Andric llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 32980b57cec5SDimitry Andric std::string Name; 32990b57cec5SDimitry Andric llvm::raw_string_ostream OS(Name); 33000b57cec5SDimitry Andric FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 33010b57cec5SDimitry Andric /*Qualified=*/true); 33020b57cec5SDimitry Andric return Name; 33030b57cec5SDimitry Andric }); 33040b57cec5SDimitry Andric 33050b57cec5SDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 33060b57cec5SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 33070b57cec5SDimitry Andric // This is necessary for the generation of certain thunks. 33080b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 33090b57cec5SDimitry Andric ABI->emitCXXStructor(GD); 33100b57cec5SDimitry Andric else if (FD->isMultiVersion()) 33110b57cec5SDimitry Andric EmitMultiVersionFunctionDefinition(GD, GV); 33120b57cec5SDimitry Andric else 33130b57cec5SDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 33140b57cec5SDimitry Andric 33150b57cec5SDimitry Andric if (Method->isVirtual()) 33160b57cec5SDimitry Andric getVTables().EmitThunks(GD); 33170b57cec5SDimitry Andric 33180b57cec5SDimitry Andric return; 33190b57cec5SDimitry Andric } 33200b57cec5SDimitry Andric 33210b57cec5SDimitry Andric if (FD->isMultiVersion()) 33220b57cec5SDimitry Andric return EmitMultiVersionFunctionDefinition(GD, GV); 33230b57cec5SDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 33240b57cec5SDimitry Andric } 33250b57cec5SDimitry Andric 33260b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 33270b57cec5SDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 33280b57cec5SDimitry Andric 33290b57cec5SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 33300b57cec5SDimitry Andric } 33310b57cec5SDimitry Andric 33320b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 33330b57cec5SDimitry Andric llvm::Function *NewFn); 33340b57cec5SDimitry Andric 33350b57cec5SDimitry Andric static unsigned 33360b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI, 33370b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RO) { 33380b57cec5SDimitry Andric unsigned Priority = 0; 33390b57cec5SDimitry Andric for (StringRef Feat : RO.Conditions.Features) 33400b57cec5SDimitry Andric Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 33410b57cec5SDimitry Andric 33420b57cec5SDimitry Andric if (!RO.Conditions.Architecture.empty()) 33430b57cec5SDimitry Andric Priority = std::max( 33440b57cec5SDimitry Andric Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 33450b57cec5SDimitry Andric return Priority; 33460b57cec5SDimitry Andric } 33470b57cec5SDimitry Andric 3348349cc55cSDimitry Andric // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3349349cc55cSDimitry Andric // TU can forward declare the function without causing problems. Particularly 3350349cc55cSDimitry Andric // in the cases of CPUDispatch, this causes issues. This also makes sure we 3351349cc55cSDimitry Andric // work with internal linkage functions, so that the same function name can be 3352349cc55cSDimitry Andric // used with internal linkage in multiple TUs. 3353349cc55cSDimitry Andric llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3354349cc55cSDimitry Andric GlobalDecl GD) { 3355349cc55cSDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3356349cc55cSDimitry Andric if (FD->getFormalLinkage() == InternalLinkage) 3357349cc55cSDimitry Andric return llvm::GlobalValue::InternalLinkage; 3358349cc55cSDimitry Andric return llvm::GlobalValue::WeakODRLinkage; 3359349cc55cSDimitry Andric } 3360349cc55cSDimitry Andric 33614824e7fdSDimitry Andric void CodeGenModule::EmitTargetClonesResolver(GlobalDecl GD) { 33624824e7fdSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 33634824e7fdSDimitry Andric assert(FD && "Not a FunctionDecl?"); 33644824e7fdSDimitry Andric const auto *TC = FD->getAttr<TargetClonesAttr>(); 33654824e7fdSDimitry Andric assert(TC && "Not a target_clones Function?"); 33664824e7fdSDimitry Andric 33674824e7fdSDimitry Andric QualType CanonTy = Context.getCanonicalType(FD->getType()); 33684824e7fdSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertType(CanonTy); 33694824e7fdSDimitry Andric 33704824e7fdSDimitry Andric if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 33714824e7fdSDimitry Andric const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 33724824e7fdSDimitry Andric DeclTy = getTypes().GetFunctionType(FInfo); 33734824e7fdSDimitry Andric } 33744824e7fdSDimitry Andric 33754824e7fdSDimitry Andric llvm::Function *ResolverFunc; 33764824e7fdSDimitry Andric if (getTarget().supportsIFunc()) { 33774824e7fdSDimitry Andric auto *IFunc = cast<llvm::GlobalIFunc>( 33784824e7fdSDimitry Andric GetOrCreateMultiVersionResolver(GD, DeclTy, FD)); 33794824e7fdSDimitry Andric ResolverFunc = cast<llvm::Function>(IFunc->getResolver()); 33804824e7fdSDimitry Andric } else 33814824e7fdSDimitry Andric ResolverFunc = 33824824e7fdSDimitry Andric cast<llvm::Function>(GetOrCreateMultiVersionResolver(GD, DeclTy, FD)); 33834824e7fdSDimitry Andric 33844824e7fdSDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 33854824e7fdSDimitry Andric for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 33864824e7fdSDimitry Andric ++VersionIndex) { 33874824e7fdSDimitry Andric if (!TC->isFirstOfVersion(VersionIndex)) 33884824e7fdSDimitry Andric continue; 33894824e7fdSDimitry Andric StringRef Version = TC->getFeatureStr(VersionIndex); 33904824e7fdSDimitry Andric StringRef MangledName = 33914824e7fdSDimitry Andric getMangledName(GD.getWithMultiVersionIndex(VersionIndex)); 33924824e7fdSDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 33934824e7fdSDimitry Andric assert(Func && 33944824e7fdSDimitry Andric "Should have already been created before calling resolver emit"); 33954824e7fdSDimitry Andric 33964824e7fdSDimitry Andric StringRef Architecture; 33974824e7fdSDimitry Andric llvm::SmallVector<StringRef, 1> Feature; 33984824e7fdSDimitry Andric 33994824e7fdSDimitry Andric if (Version.startswith("arch=")) 34004824e7fdSDimitry Andric Architecture = Version.drop_front(sizeof("arch=") - 1); 34014824e7fdSDimitry Andric else if (Version != "default") 34024824e7fdSDimitry Andric Feature.push_back(Version); 34034824e7fdSDimitry Andric 34044824e7fdSDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 34054824e7fdSDimitry Andric } 34064824e7fdSDimitry Andric 34074824e7fdSDimitry Andric const TargetInfo &TI = getTarget(); 34084824e7fdSDimitry Andric std::stable_sort( 34094824e7fdSDimitry Andric Options.begin(), Options.end(), 34104824e7fdSDimitry Andric [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 34114824e7fdSDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 34124824e7fdSDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 34134824e7fdSDimitry Andric }); 34144824e7fdSDimitry Andric CodeGenFunction CGF(*this); 34154824e7fdSDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 34164824e7fdSDimitry Andric } 34174824e7fdSDimitry Andric 34180b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() { 3419fe6060f1SDimitry Andric std::vector<GlobalDecl> MVFuncsToEmit; 3420fe6060f1SDimitry Andric MultiVersionFuncs.swap(MVFuncsToEmit); 3421fe6060f1SDimitry Andric for (GlobalDecl GD : MVFuncsToEmit) { 34220b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 34230b57cec5SDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 34240b57cec5SDimitry Andric getContext().forEachMultiversionedFunctionVersion( 34250b57cec5SDimitry Andric FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 34260b57cec5SDimitry Andric GlobalDecl CurGD{ 34270b57cec5SDimitry Andric (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 34280b57cec5SDimitry Andric StringRef MangledName = getMangledName(CurGD); 34290b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 34300b57cec5SDimitry Andric if (!Func) { 34310b57cec5SDimitry Andric if (CurFD->isDefined()) { 34320b57cec5SDimitry Andric EmitGlobalFunctionDefinition(CurGD, nullptr); 34330b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 34340b57cec5SDimitry Andric } else { 34350b57cec5SDimitry Andric const CGFunctionInfo &FI = 34360b57cec5SDimitry Andric getTypes().arrangeGlobalDeclaration(GD); 34370b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 34380b57cec5SDimitry Andric Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 34390b57cec5SDimitry Andric /*DontDefer=*/false, ForDefinition); 34400b57cec5SDimitry Andric } 34410b57cec5SDimitry Andric assert(Func && "This should have just been created"); 34420b57cec5SDimitry Andric } 34430b57cec5SDimitry Andric 34440b57cec5SDimitry Andric const auto *TA = CurFD->getAttr<TargetAttr>(); 34450b57cec5SDimitry Andric llvm::SmallVector<StringRef, 8> Feats; 34460b57cec5SDimitry Andric TA->getAddedFeatures(Feats); 34470b57cec5SDimitry Andric 34480b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), 34490b57cec5SDimitry Andric TA->getArchitecture(), Feats); 34500b57cec5SDimitry Andric }); 34510b57cec5SDimitry Andric 34520b57cec5SDimitry Andric llvm::Function *ResolverFunc; 34530b57cec5SDimitry Andric const TargetInfo &TI = getTarget(); 34540b57cec5SDimitry Andric 3455a7dea167SDimitry Andric if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 34560b57cec5SDimitry Andric ResolverFunc = cast<llvm::Function>( 34570b57cec5SDimitry Andric GetGlobalValue((getMangledName(GD) + ".resolver").str())); 3458349cc55cSDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3459a7dea167SDimitry Andric } else { 34600b57cec5SDimitry Andric ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 3461a7dea167SDimitry Andric } 34620b57cec5SDimitry Andric 34630b57cec5SDimitry Andric if (supportsCOMDAT()) 34640b57cec5SDimitry Andric ResolverFunc->setComdat( 34650b57cec5SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 34660b57cec5SDimitry Andric 34670b57cec5SDimitry Andric llvm::stable_sort( 34680b57cec5SDimitry Andric Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 34690b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 34700b57cec5SDimitry Andric return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 34710b57cec5SDimitry Andric }); 34720b57cec5SDimitry Andric CodeGenFunction CGF(*this); 34730b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 34740b57cec5SDimitry Andric } 3475fe6060f1SDimitry Andric 3476fe6060f1SDimitry Andric // Ensure that any additions to the deferred decls list caused by emitting a 3477fe6060f1SDimitry Andric // variant are emitted. This can happen when the variant itself is inline and 3478fe6060f1SDimitry Andric // calls a function without linkage. 3479fe6060f1SDimitry Andric if (!MVFuncsToEmit.empty()) 3480fe6060f1SDimitry Andric EmitDeferred(); 3481fe6060f1SDimitry Andric 3482fe6060f1SDimitry Andric // Ensure that any additions to the multiversion funcs list from either the 3483fe6060f1SDimitry Andric // deferred decls or the multiversion functions themselves are emitted. 3484fe6060f1SDimitry Andric if (!MultiVersionFuncs.empty()) 3485fe6060f1SDimitry Andric emitMultiVersionFunctions(); 34860b57cec5SDimitry Andric } 34870b57cec5SDimitry Andric 34880b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 34890b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 34900b57cec5SDimitry Andric assert(FD && "Not a FunctionDecl?"); 349104eeddc0SDimitry Andric assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 34920b57cec5SDimitry Andric const auto *DD = FD->getAttr<CPUDispatchAttr>(); 34930b57cec5SDimitry Andric assert(DD && "Not a cpu_dispatch Function?"); 34940b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 34950b57cec5SDimitry Andric 34960b57cec5SDimitry Andric if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 34970b57cec5SDimitry Andric const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 34980b57cec5SDimitry Andric DeclTy = getTypes().GetFunctionType(FInfo); 34990b57cec5SDimitry Andric } 35000b57cec5SDimitry Andric 35010b57cec5SDimitry Andric StringRef ResolverName = getMangledName(GD); 350204eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, ResolverName); 35030b57cec5SDimitry Andric 35040b57cec5SDimitry Andric llvm::Type *ResolverType; 35050b57cec5SDimitry Andric GlobalDecl ResolverGD; 350604eeddc0SDimitry Andric if (getTarget().supportsIFunc()) { 35070b57cec5SDimitry Andric ResolverType = llvm::FunctionType::get( 35080b57cec5SDimitry Andric llvm::PointerType::get(DeclTy, 35090b57cec5SDimitry Andric Context.getTargetAddressSpace(FD->getType())), 35100b57cec5SDimitry Andric false); 351104eeddc0SDimitry Andric } 35120b57cec5SDimitry Andric else { 35130b57cec5SDimitry Andric ResolverType = DeclTy; 35140b57cec5SDimitry Andric ResolverGD = GD; 35150b57cec5SDimitry Andric } 35160b57cec5SDimitry Andric 35170b57cec5SDimitry Andric auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 35180b57cec5SDimitry Andric ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3519349cc55cSDimitry Andric ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3520a7dea167SDimitry Andric if (supportsCOMDAT()) 3521a7dea167SDimitry Andric ResolverFunc->setComdat( 3522a7dea167SDimitry Andric getModule().getOrInsertComdat(ResolverFunc->getName())); 35230b57cec5SDimitry Andric 35240b57cec5SDimitry Andric SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 35250b57cec5SDimitry Andric const TargetInfo &Target = getTarget(); 35260b57cec5SDimitry Andric unsigned Index = 0; 35270b57cec5SDimitry Andric for (const IdentifierInfo *II : DD->cpus()) { 35280b57cec5SDimitry Andric // Get the name of the target function so we can look it up/create it. 35290b57cec5SDimitry Andric std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 35300b57cec5SDimitry Andric getCPUSpecificMangling(*this, II->getName()); 35310b57cec5SDimitry Andric 35320b57cec5SDimitry Andric llvm::Constant *Func = GetGlobalValue(MangledName); 35330b57cec5SDimitry Andric 35340b57cec5SDimitry Andric if (!Func) { 35350b57cec5SDimitry Andric GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 35360b57cec5SDimitry Andric if (ExistingDecl.getDecl() && 35370b57cec5SDimitry Andric ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 35380b57cec5SDimitry Andric EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 35390b57cec5SDimitry Andric Func = GetGlobalValue(MangledName); 35400b57cec5SDimitry Andric } else { 35410b57cec5SDimitry Andric if (!ExistingDecl.getDecl()) 35420b57cec5SDimitry Andric ExistingDecl = GD.getWithMultiVersionIndex(Index); 35430b57cec5SDimitry Andric 35440b57cec5SDimitry Andric Func = GetOrCreateLLVMFunction( 35450b57cec5SDimitry Andric MangledName, DeclTy, ExistingDecl, 35460b57cec5SDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 35470b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 35480b57cec5SDimitry Andric } 35490b57cec5SDimitry Andric } 35500b57cec5SDimitry Andric 35510b57cec5SDimitry Andric llvm::SmallVector<StringRef, 32> Features; 35520b57cec5SDimitry Andric Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 35530b57cec5SDimitry Andric llvm::transform(Features, Features.begin(), 35540b57cec5SDimitry Andric [](StringRef Str) { return Str.substr(1); }); 3555349cc55cSDimitry Andric llvm::erase_if(Features, [&Target](StringRef Feat) { 35560b57cec5SDimitry Andric return !Target.validateCpuSupports(Feat); 3557349cc55cSDimitry Andric }); 35580b57cec5SDimitry Andric Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 35590b57cec5SDimitry Andric ++Index; 35600b57cec5SDimitry Andric } 35610b57cec5SDimitry Andric 3562fe6060f1SDimitry Andric llvm::stable_sort( 35630b57cec5SDimitry Andric Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 35640b57cec5SDimitry Andric const CodeGenFunction::MultiVersionResolverOption &RHS) { 3565349cc55cSDimitry Andric return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3566349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 35670b57cec5SDimitry Andric }); 35680b57cec5SDimitry Andric 35690b57cec5SDimitry Andric // If the list contains multiple 'default' versions, such as when it contains 35700b57cec5SDimitry Andric // 'pentium' and 'generic', don't emit the call to the generic one (since we 35710b57cec5SDimitry Andric // always run on at least a 'pentium'). We do this by deleting the 'least 35720b57cec5SDimitry Andric // advanced' (read, lowest mangling letter). 35730b57cec5SDimitry Andric while (Options.size() > 1 && 3574349cc55cSDimitry Andric llvm::X86::getCpuSupportsMask( 35750b57cec5SDimitry Andric (Options.end() - 2)->Conditions.Features) == 0) { 35760b57cec5SDimitry Andric StringRef LHSName = (Options.end() - 2)->Function->getName(); 35770b57cec5SDimitry Andric StringRef RHSName = (Options.end() - 1)->Function->getName(); 35780b57cec5SDimitry Andric if (LHSName.compare(RHSName) < 0) 35790b57cec5SDimitry Andric Options.erase(Options.end() - 2); 35800b57cec5SDimitry Andric else 35810b57cec5SDimitry Andric Options.erase(Options.end() - 1); 35820b57cec5SDimitry Andric } 35830b57cec5SDimitry Andric 35840b57cec5SDimitry Andric CodeGenFunction CGF(*this); 35850b57cec5SDimitry Andric CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3586a7dea167SDimitry Andric 3587a7dea167SDimitry Andric if (getTarget().supportsIFunc()) { 3588a7dea167SDimitry Andric std::string AliasName = getMangledNameImpl( 3589a7dea167SDimitry Andric *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3590a7dea167SDimitry Andric llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3591a7dea167SDimitry Andric if (!AliasFunc) { 3592a7dea167SDimitry Andric auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3593a7dea167SDimitry Andric AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3594a7dea167SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3595349cc55cSDimitry Andric auto *GA = llvm::GlobalAlias::create(DeclTy, 0, 3596349cc55cSDimitry Andric getMultiversionLinkage(*this, GD), 3597349cc55cSDimitry Andric AliasName, IFunc, &getModule()); 3598a7dea167SDimitry Andric SetCommonAttributes(GD, GA); 3599a7dea167SDimitry Andric } 3600a7dea167SDimitry Andric } 36010b57cec5SDimitry Andric } 36020b57cec5SDimitry Andric 36030b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create 36040b57cec5SDimitry Andric /// and return an llvm Function with the specified type. 36050b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 36060b57cec5SDimitry Andric GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 36070b57cec5SDimitry Andric std::string MangledName = 36080b57cec5SDimitry Andric getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 36090b57cec5SDimitry Andric 36100b57cec5SDimitry Andric // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 36110b57cec5SDimitry Andric // a separate resolver). 36120b57cec5SDimitry Andric std::string ResolverName = MangledName; 36130b57cec5SDimitry Andric if (getTarget().supportsIFunc()) 36140b57cec5SDimitry Andric ResolverName += ".ifunc"; 36150b57cec5SDimitry Andric else if (FD->isTargetMultiVersion()) 36160b57cec5SDimitry Andric ResolverName += ".resolver"; 36170b57cec5SDimitry Andric 36180b57cec5SDimitry Andric // If this already exists, just return that one. 36190b57cec5SDimitry Andric if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 36200b57cec5SDimitry Andric return ResolverGV; 36210b57cec5SDimitry Andric 36220b57cec5SDimitry Andric // Since this is the first time we've created this IFunc, make sure 36230b57cec5SDimitry Andric // that we put this multiversioned function into the list to be 36240b57cec5SDimitry Andric // replaced later if necessary (target multiversioning only). 36254824e7fdSDimitry Andric if (FD->isTargetMultiVersion()) 36260b57cec5SDimitry Andric MultiVersionFuncs.push_back(GD); 36274824e7fdSDimitry Andric else if (FD->isTargetClonesMultiVersion()) { 36284824e7fdSDimitry Andric // In target_clones multiversioning, make sure we emit this if used. 36294824e7fdSDimitry Andric auto DDI = 36304824e7fdSDimitry Andric DeferredDecls.find(getMangledName(GD.getWithMultiVersionIndex(0))); 36314824e7fdSDimitry Andric if (DDI != DeferredDecls.end()) { 36324824e7fdSDimitry Andric addDeferredDeclToEmit(GD); 36334824e7fdSDimitry Andric DeferredDecls.erase(DDI); 36344824e7fdSDimitry Andric } else { 36354824e7fdSDimitry Andric // Emit the symbol of the 1st variant, so that the deferred decls know we 36364824e7fdSDimitry Andric // need it, otherwise the only global value will be the resolver/ifunc, 36374824e7fdSDimitry Andric // which end up getting broken if we search for them with GetGlobalValue'. 36384824e7fdSDimitry Andric GetOrCreateLLVMFunction( 36394824e7fdSDimitry Andric getMangledName(GD.getWithMultiVersionIndex(0)), DeclTy, FD, 36404824e7fdSDimitry Andric /*ForVTable=*/false, /*DontDefer=*/true, 36414824e7fdSDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 36424824e7fdSDimitry Andric } 36434824e7fdSDimitry Andric } 36440b57cec5SDimitry Andric 36450b57cec5SDimitry Andric if (getTarget().supportsIFunc()) { 36460b57cec5SDimitry Andric llvm::Type *ResolverType = llvm::FunctionType::get( 36470b57cec5SDimitry Andric llvm::PointerType::get( 36480b57cec5SDimitry Andric DeclTy, getContext().getTargetAddressSpace(FD->getType())), 36490b57cec5SDimitry Andric false); 36500b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 36510b57cec5SDimitry Andric MangledName + ".resolver", ResolverType, GlobalDecl{}, 36520b57cec5SDimitry Andric /*ForVTable=*/false); 3653349cc55cSDimitry Andric llvm::GlobalIFunc *GIF = 3654349cc55cSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3655349cc55cSDimitry Andric "", Resolver, &getModule()); 36560b57cec5SDimitry Andric GIF->setName(ResolverName); 36570b57cec5SDimitry Andric SetCommonAttributes(FD, GIF); 36580b57cec5SDimitry Andric 36590b57cec5SDimitry Andric return GIF; 36600b57cec5SDimitry Andric } 36610b57cec5SDimitry Andric 36620b57cec5SDimitry Andric llvm::Constant *Resolver = GetOrCreateLLVMFunction( 36630b57cec5SDimitry Andric ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 36640b57cec5SDimitry Andric assert(isa<llvm::GlobalValue>(Resolver) && 36650b57cec5SDimitry Andric "Resolver should be created for the first time"); 36660b57cec5SDimitry Andric SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 36670b57cec5SDimitry Andric return Resolver; 36680b57cec5SDimitry Andric } 36690b57cec5SDimitry Andric 36700b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 36710b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there 36720b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially 36730b57cec5SDimitry Andric /// bitcasted to the right type. 36740b57cec5SDimitry Andric /// 36750b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 36760b57cec5SDimitry Andric /// to set the attributes on the function when it is first created. 36770b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 36780b57cec5SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 36790b57cec5SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 36800b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 36810b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 36820b57cec5SDimitry Andric 36830b57cec5SDimitry Andric // Any attempts to use a MultiVersion function should result in retrieving 36840b57cec5SDimitry Andric // the iFunc instead. Name Mangling will handle the rest of the changes. 36850b57cec5SDimitry Andric if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 36860b57cec5SDimitry Andric // For the device mark the function as one that should be emitted. 36870b57cec5SDimitry Andric if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 36880b57cec5SDimitry Andric !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 36890b57cec5SDimitry Andric !DontDefer && !IsForDefinition) { 36900b57cec5SDimitry Andric if (const FunctionDecl *FDDef = FD->getDefinition()) { 36910b57cec5SDimitry Andric GlobalDecl GDDef; 36920b57cec5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 36930b57cec5SDimitry Andric GDDef = GlobalDecl(CD, GD.getCtorType()); 36940b57cec5SDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 36950b57cec5SDimitry Andric GDDef = GlobalDecl(DD, GD.getDtorType()); 36960b57cec5SDimitry Andric else 36970b57cec5SDimitry Andric GDDef = GlobalDecl(FDDef); 36980b57cec5SDimitry Andric EmitGlobal(GDDef); 36990b57cec5SDimitry Andric } 37000b57cec5SDimitry Andric } 37010b57cec5SDimitry Andric 37020b57cec5SDimitry Andric if (FD->isMultiVersion()) { 370304eeddc0SDimitry Andric UpdateMultiVersionNames(GD, FD, MangledName); 37040b57cec5SDimitry Andric if (!IsForDefinition) 37050b57cec5SDimitry Andric return GetOrCreateMultiVersionResolver(GD, Ty, FD); 37060b57cec5SDimitry Andric } 37070b57cec5SDimitry Andric } 37080b57cec5SDimitry Andric 37090b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 37100b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 37110b57cec5SDimitry Andric if (Entry) { 37120b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 37130b57cec5SDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 37140b57cec5SDimitry Andric if (FD && !FD->hasAttr<WeakAttr>()) 37150b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 37160b57cec5SDimitry Andric } 37170b57cec5SDimitry Andric 37180b57cec5SDimitry Andric // Handle dropped DLL attributes. 37190b57cec5SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 37200b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 37210b57cec5SDimitry Andric setDSOLocal(Entry); 37220b57cec5SDimitry Andric } 37230b57cec5SDimitry Andric 37240b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 37250b57cec5SDimitry Andric // error. 37260b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 37270b57cec5SDimitry Andric GlobalDecl OtherGD; 37280b57cec5SDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 37290b57cec5SDimitry Andric // to make sure that we issue an error only once. 37300b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 37310b57cec5SDimitry Andric (GD.getCanonicalDecl().getDecl() != 37320b57cec5SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 37330b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 37340b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 37350b57cec5SDimitry Andric << MangledName; 37360b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 37370b57cec5SDimitry Andric diag::note_previous_definition); 37380b57cec5SDimitry Andric } 37390b57cec5SDimitry Andric } 37400b57cec5SDimitry Andric 37410b57cec5SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 37425ffd83dbSDimitry Andric (Entry->getValueType() == Ty)) { 37430b57cec5SDimitry Andric return Entry; 37440b57cec5SDimitry Andric } 37450b57cec5SDimitry Andric 37460b57cec5SDimitry Andric // Make sure the result is of the correct type. 37470b57cec5SDimitry Andric // (If function is requested for a definition, we always need to create a new 37480b57cec5SDimitry Andric // function, not just return a bitcast.) 37490b57cec5SDimitry Andric if (!IsForDefinition) 37500b57cec5SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 37510b57cec5SDimitry Andric } 37520b57cec5SDimitry Andric 37530b57cec5SDimitry Andric // This function doesn't have a complete type (for example, the return 37540b57cec5SDimitry Andric // type is an incomplete struct). Use a fake type instead, and make 37550b57cec5SDimitry Andric // sure not to try to set attributes. 37560b57cec5SDimitry Andric bool IsIncompleteFunction = false; 37570b57cec5SDimitry Andric 37580b57cec5SDimitry Andric llvm::FunctionType *FTy; 37590b57cec5SDimitry Andric if (isa<llvm::FunctionType>(Ty)) { 37600b57cec5SDimitry Andric FTy = cast<llvm::FunctionType>(Ty); 37610b57cec5SDimitry Andric } else { 37620b57cec5SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 37630b57cec5SDimitry Andric IsIncompleteFunction = true; 37640b57cec5SDimitry Andric } 37650b57cec5SDimitry Andric 37660b57cec5SDimitry Andric llvm::Function *F = 37670b57cec5SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 37680b57cec5SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 37690b57cec5SDimitry Andric 37700b57cec5SDimitry Andric // If we already created a function with the same mangled name (but different 37710b57cec5SDimitry Andric // type) before, take its name and add it to the list of functions to be 37720b57cec5SDimitry Andric // replaced with F at the end of CodeGen. 37730b57cec5SDimitry Andric // 37740b57cec5SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 37750b57cec5SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 37760b57cec5SDimitry Andric if (Entry) { 37770b57cec5SDimitry Andric F->takeName(Entry); 37780b57cec5SDimitry Andric 37790b57cec5SDimitry Andric // This might be an implementation of a function without a prototype, in 37800b57cec5SDimitry Andric // which case, try to do special replacement of calls which match the new 37810b57cec5SDimitry Andric // prototype. The really key thing here is that we also potentially drop 37820b57cec5SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 37830b57cec5SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 37840b57cec5SDimitry Andric // dropping arguments. 37850b57cec5SDimitry Andric if (!Entry->use_empty()) { 37860b57cec5SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 37870b57cec5SDimitry Andric Entry->removeDeadConstantUsers(); 37880b57cec5SDimitry Andric } 37890b57cec5SDimitry Andric 37900b57cec5SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 37915ffd83dbSDimitry Andric F, Entry->getValueType()->getPointerTo()); 37920b57cec5SDimitry Andric addGlobalValReplacement(Entry, BC); 37930b57cec5SDimitry Andric } 37940b57cec5SDimitry Andric 37950b57cec5SDimitry Andric assert(F->getName() == MangledName && "name was uniqued!"); 37960b57cec5SDimitry Andric if (D) 37970b57cec5SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3798349cc55cSDimitry Andric if (ExtraAttrs.hasFnAttrs()) { 379904eeddc0SDimitry Andric llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 3800349cc55cSDimitry Andric F->addFnAttrs(B); 38010b57cec5SDimitry Andric } 38020b57cec5SDimitry Andric 38030b57cec5SDimitry Andric if (!DontDefer) { 38040b57cec5SDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 38050b57cec5SDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 38060b57cec5SDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 38070b57cec5SDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 38080b57cec5SDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 38090b57cec5SDimitry Andric GD.getDtorType())) 38100b57cec5SDimitry Andric addDeferredDeclToEmit(GD); 38110b57cec5SDimitry Andric 38120b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 38130b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 38140b57cec5SDimitry Andric // of the file. 38150b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 38160b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 38170b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the 38180b57cec5SDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 38190b57cec5SDimitry Andric // don't need it anymore). 38200b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 38210b57cec5SDimitry Andric DeferredDecls.erase(DDI); 38220b57cec5SDimitry Andric 38230b57cec5SDimitry Andric // Otherwise, there are cases we have to worry about where we're 38240b57cec5SDimitry Andric // using a declaration for which we must emit a definition but where 38250b57cec5SDimitry Andric // we might not find a top-level definition: 38260b57cec5SDimitry Andric // - member functions defined inline in their classes 38270b57cec5SDimitry Andric // - friend functions defined inline in some class 38280b57cec5SDimitry Andric // - special member functions with implicit definitions 38290b57cec5SDimitry Andric // If we ever change our AST traversal to walk into class methods, 38300b57cec5SDimitry Andric // this will be unnecessary. 38310b57cec5SDimitry Andric // 38320b57cec5SDimitry Andric // We also don't emit a definition for a function if it's going to be an 38330b57cec5SDimitry Andric // entry in a vtable, unless it's already marked as used. 38340b57cec5SDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 38350b57cec5SDimitry Andric // Look for a declaration that's lexically in a record. 38360b57cec5SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 38370b57cec5SDimitry Andric FD = FD->getPreviousDecl()) { 38380b57cec5SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 38390b57cec5SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 38400b57cec5SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 38410b57cec5SDimitry Andric break; 38420b57cec5SDimitry Andric } 38430b57cec5SDimitry Andric } 38440b57cec5SDimitry Andric } 38450b57cec5SDimitry Andric } 38460b57cec5SDimitry Andric } 38470b57cec5SDimitry Andric 38480b57cec5SDimitry Andric // Make sure the result is of the requested type. 38490b57cec5SDimitry Andric if (!IsIncompleteFunction) { 38505ffd83dbSDimitry Andric assert(F->getFunctionType() == Ty); 38510b57cec5SDimitry Andric return F; 38520b57cec5SDimitry Andric } 38530b57cec5SDimitry Andric 38540b57cec5SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 38550b57cec5SDimitry Andric return llvm::ConstantExpr::getBitCast(F, PTy); 38560b57cec5SDimitry Andric } 38570b57cec5SDimitry Andric 38580b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function. If Ty is 38590b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to 38600b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function). 38610b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 38620b57cec5SDimitry Andric llvm::Type *Ty, 38630b57cec5SDimitry Andric bool ForVTable, 38640b57cec5SDimitry Andric bool DontDefer, 38650b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 38665ffd83dbSDimitry Andric assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 38675ffd83dbSDimitry Andric "consteval function should never be emitted"); 38680b57cec5SDimitry Andric // If there was no specific requested type, just convert it now. 38690b57cec5SDimitry Andric if (!Ty) { 38700b57cec5SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 38710b57cec5SDimitry Andric Ty = getTypes().ConvertType(FD->getType()); 38720b57cec5SDimitry Andric } 38730b57cec5SDimitry Andric 38740b57cec5SDimitry Andric // Devirtualized destructor calls may come through here instead of via 38750b57cec5SDimitry Andric // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 38760b57cec5SDimitry Andric // of the complete destructor when necessary. 38770b57cec5SDimitry Andric if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 38780b57cec5SDimitry Andric if (getTarget().getCXXABI().isMicrosoft() && 38790b57cec5SDimitry Andric GD.getDtorType() == Dtor_Complete && 38800b57cec5SDimitry Andric DD->getParent()->getNumVBases() == 0) 38810b57cec5SDimitry Andric GD = GlobalDecl(DD, Dtor_Base); 38820b57cec5SDimitry Andric } 38830b57cec5SDimitry Andric 38840b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 3885fe6060f1SDimitry Andric auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 38860b57cec5SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 38870b57cec5SDimitry Andric IsForDefinition); 3888fe6060f1SDimitry Andric // Returns kernel handle for HIP kernel stub function. 3889fe6060f1SDimitry Andric if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 3890fe6060f1SDimitry Andric cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 3891fe6060f1SDimitry Andric auto *Handle = getCUDARuntime().getKernelHandle( 3892fe6060f1SDimitry Andric cast<llvm::Function>(F->stripPointerCasts()), GD); 3893fe6060f1SDimitry Andric if (IsForDefinition) 3894fe6060f1SDimitry Andric return F; 3895fe6060f1SDimitry Andric return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 3896fe6060f1SDimitry Andric } 3897fe6060f1SDimitry Andric return F; 38980b57cec5SDimitry Andric } 38990b57cec5SDimitry Andric 39000eae32dcSDimitry Andric llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 39010eae32dcSDimitry Andric llvm::GlobalValue *F = 39020eae32dcSDimitry Andric cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 39030eae32dcSDimitry Andric 39040eae32dcSDimitry Andric return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F), 39050eae32dcSDimitry Andric llvm::Type::getInt8PtrTy(VMContext)); 39060eae32dcSDimitry Andric } 39070eae32dcSDimitry Andric 39080b57cec5SDimitry Andric static const FunctionDecl * 39090b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 39100b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 39110b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 39120b57cec5SDimitry Andric 39130b57cec5SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 3914fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&CII)) 3915fe6060f1SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 39160b57cec5SDimitry Andric return FD; 39170b57cec5SDimitry Andric 39180b57cec5SDimitry Andric if (!C.getLangOpts().CPlusPlus) 39190b57cec5SDimitry Andric return nullptr; 39200b57cec5SDimitry Andric 39210b57cec5SDimitry Andric // Demangle the premangled name from getTerminateFn() 39220b57cec5SDimitry Andric IdentifierInfo &CXXII = 39230b57cec5SDimitry Andric (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 39240b57cec5SDimitry Andric ? C.Idents.get("terminate") 39250b57cec5SDimitry Andric : C.Idents.get(Name); 39260b57cec5SDimitry Andric 39270b57cec5SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 39280b57cec5SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 3929fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&NS)) { 3930fe6060f1SDimitry Andric const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3931fe6060f1SDimitry Andric if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 3932fe6060f1SDimitry Andric for (const auto *Result : LSD->lookup(&NS)) 39330b57cec5SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 39340b57cec5SDimitry Andric break; 39350b57cec5SDimitry Andric 39360b57cec5SDimitry Andric if (ND) 3937fe6060f1SDimitry Andric for (const auto *Result : ND->lookup(&CXXII)) 39380b57cec5SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 39390b57cec5SDimitry Andric return FD; 39400b57cec5SDimitry Andric } 39410b57cec5SDimitry Andric } 39420b57cec5SDimitry Andric 39430b57cec5SDimitry Andric return nullptr; 39440b57cec5SDimitry Andric } 39450b57cec5SDimitry Andric 39460b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified 39470b57cec5SDimitry Andric /// type and name. 39480b57cec5SDimitry Andric llvm::FunctionCallee 39490b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3950480093f4SDimitry Andric llvm::AttributeList ExtraAttrs, bool Local, 3951480093f4SDimitry Andric bool AssumeConvergent) { 3952480093f4SDimitry Andric if (AssumeConvergent) { 3953480093f4SDimitry Andric ExtraAttrs = 3954349cc55cSDimitry Andric ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 3955480093f4SDimitry Andric } 3956480093f4SDimitry Andric 39570b57cec5SDimitry Andric llvm::Constant *C = 39580b57cec5SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 39590b57cec5SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 39600b57cec5SDimitry Andric ExtraAttrs); 39610b57cec5SDimitry Andric 39620b57cec5SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 39630b57cec5SDimitry Andric if (F->empty()) { 39640b57cec5SDimitry Andric F->setCallingConv(getRuntimeCC()); 39650b57cec5SDimitry Andric 39660b57cec5SDimitry Andric // In Windows Itanium environments, try to mark runtime functions 39670b57cec5SDimitry Andric // dllimport. For Mingw and MSVC, don't. We don't really know if the user 39680b57cec5SDimitry Andric // will link their standard library statically or dynamically. Marking 39690b57cec5SDimitry Andric // functions imported when they are not imported can cause linker errors 39700b57cec5SDimitry Andric // and warnings. 39710b57cec5SDimitry Andric if (!Local && getTriple().isWindowsItaniumEnvironment() && 39720b57cec5SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 39730b57cec5SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 39740b57cec5SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 39750b57cec5SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 39760b57cec5SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 39770b57cec5SDimitry Andric } 39780b57cec5SDimitry Andric } 39790b57cec5SDimitry Andric setDSOLocal(F); 39800b57cec5SDimitry Andric } 39810b57cec5SDimitry Andric } 39820b57cec5SDimitry Andric 39830b57cec5SDimitry Andric return {FTy, C}; 39840b57cec5SDimitry Andric } 39850b57cec5SDimitry Andric 39860b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 39870b57cec5SDimitry Andric /// as a constant. 39880b57cec5SDimitry Andric /// 39890b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 39900b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is 39910b57cec5SDimitry Andric /// not written to during its construction. 39920b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 39930b57cec5SDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 39940b57cec5SDimitry Andric return false; 39950b57cec5SDimitry Andric 39960b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus) { 39970b57cec5SDimitry Andric if (const CXXRecordDecl *Record 39980b57cec5SDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 39990b57cec5SDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 40000b57cec5SDimitry Andric Record->hasTrivialDestructor(); 40010b57cec5SDimitry Andric } 40020b57cec5SDimitry Andric 40030b57cec5SDimitry Andric return true; 40040b57cec5SDimitry Andric } 40050b57cec5SDimitry Andric 40060b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4007fe6060f1SDimitry Andric /// create and return an llvm GlobalVariable with the specified type and address 4008fe6060f1SDimitry Andric /// space. If there is something in the module with the specified name, return 4009fe6060f1SDimitry Andric /// it potentially bitcasted to the right type. 40100b57cec5SDimitry Andric /// 40110b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this. This is used 40120b57cec5SDimitry Andric /// to set the attributes on the global when it is first created. 40130b57cec5SDimitry Andric /// 40140b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with 40150b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 40160b57cec5SDimitry Andric /// mangled name but some other type. 40170b57cec5SDimitry Andric llvm::Constant * 4018fe6060f1SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4019349cc55cSDimitry Andric LangAS AddrSpace, const VarDecl *D, 40200b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 40210b57cec5SDimitry Andric // Lookup the entry, lazily creating it if necessary. 40220b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4023349cc55cSDimitry Andric unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 40240b57cec5SDimitry Andric if (Entry) { 40250b57cec5SDimitry Andric if (WeakRefReferences.erase(Entry)) { 40260b57cec5SDimitry Andric if (D && !D->hasAttr<WeakAttr>()) 40270b57cec5SDimitry Andric Entry->setLinkage(llvm::Function::ExternalLinkage); 40280b57cec5SDimitry Andric } 40290b57cec5SDimitry Andric 40300b57cec5SDimitry Andric // Handle dropped DLL attributes. 40310b57cec5SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 40320b57cec5SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 40330b57cec5SDimitry Andric 40340b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 40350b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 40360b57cec5SDimitry Andric 4037349cc55cSDimitry Andric if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 40380b57cec5SDimitry Andric return Entry; 40390b57cec5SDimitry Andric 40400b57cec5SDimitry Andric // If there are two attempts to define the same mangled name, issue an 40410b57cec5SDimitry Andric // error. 40420b57cec5SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 40430b57cec5SDimitry Andric GlobalDecl OtherGD; 40440b57cec5SDimitry Andric const VarDecl *OtherD; 40450b57cec5SDimitry Andric 40460b57cec5SDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 40470b57cec5SDimitry Andric // to make sure that we issue an error only once. 40480b57cec5SDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 40490b57cec5SDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 40500b57cec5SDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 40510b57cec5SDimitry Andric OtherD->hasInit() && 40520b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 40530b57cec5SDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 40540b57cec5SDimitry Andric << MangledName; 40550b57cec5SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 40560b57cec5SDimitry Andric diag::note_previous_definition); 40570b57cec5SDimitry Andric } 40580b57cec5SDimitry Andric } 40590b57cec5SDimitry Andric 40600b57cec5SDimitry Andric // Make sure the result is of the correct type. 4061349cc55cSDimitry Andric if (Entry->getType()->getAddressSpace() != TargetAS) { 4062fe6060f1SDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4063349cc55cSDimitry Andric Ty->getPointerTo(TargetAS)); 4064fe6060f1SDimitry Andric } 40650b57cec5SDimitry Andric 40660b57cec5SDimitry Andric // (If global is requested for a definition, we always need to create a new 40670b57cec5SDimitry Andric // global, not just return a bitcast.) 40680b57cec5SDimitry Andric if (!IsForDefinition) 4069349cc55cSDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 40700b57cec5SDimitry Andric } 40710b57cec5SDimitry Andric 4072fe6060f1SDimitry Andric auto DAddrSpace = GetGlobalVarAddressSpace(D); 40730b57cec5SDimitry Andric 40740b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 4075fe6060f1SDimitry Andric getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4076fe6060f1SDimitry Andric MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4077349cc55cSDimitry Andric getContext().getTargetAddressSpace(DAddrSpace)); 40780b57cec5SDimitry Andric 40790b57cec5SDimitry Andric // If we already created a global with the same mangled name (but different 40800b57cec5SDimitry Andric // type) before, take its name and remove it from its parent. 40810b57cec5SDimitry Andric if (Entry) { 40820b57cec5SDimitry Andric GV->takeName(Entry); 40830b57cec5SDimitry Andric 40840b57cec5SDimitry Andric if (!Entry->use_empty()) { 40850b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 40860b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 40870b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 40880b57cec5SDimitry Andric } 40890b57cec5SDimitry Andric 40900b57cec5SDimitry Andric Entry->eraseFromParent(); 40910b57cec5SDimitry Andric } 40920b57cec5SDimitry Andric 40930b57cec5SDimitry Andric // This is the first use or definition of a mangled name. If there is a 40940b57cec5SDimitry Andric // deferred decl with this name, remember that we need to emit it at the end 40950b57cec5SDimitry Andric // of the file. 40960b57cec5SDimitry Andric auto DDI = DeferredDecls.find(MangledName); 40970b57cec5SDimitry Andric if (DDI != DeferredDecls.end()) { 40980b57cec5SDimitry Andric // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 40990b57cec5SDimitry Andric // list, and remove it from DeferredDecls (since we don't need it anymore). 41000b57cec5SDimitry Andric addDeferredDeclToEmit(DDI->second); 41010b57cec5SDimitry Andric DeferredDecls.erase(DDI); 41020b57cec5SDimitry Andric } 41030b57cec5SDimitry Andric 41040b57cec5SDimitry Andric // Handle things which are present even on external declarations. 41050b57cec5SDimitry Andric if (D) { 41060b57cec5SDimitry Andric if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 41070b57cec5SDimitry Andric getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 41080b57cec5SDimitry Andric 41090b57cec5SDimitry Andric // FIXME: This code is overly simple and should be merged with other global 41100b57cec5SDimitry Andric // handling. 41110b57cec5SDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 41120b57cec5SDimitry Andric 4113a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 41140b57cec5SDimitry Andric 41150b57cec5SDimitry Andric setLinkageForGV(GV, D); 41160b57cec5SDimitry Andric 41170b57cec5SDimitry Andric if (D->getTLSKind()) { 41180b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 41190b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 41200b57cec5SDimitry Andric setTLSMode(GV, *D); 41210b57cec5SDimitry Andric } 41220b57cec5SDimitry Andric 41230b57cec5SDimitry Andric setGVProperties(GV, D); 41240b57cec5SDimitry Andric 41250b57cec5SDimitry Andric // If required by the ABI, treat declarations of static data members with 41260b57cec5SDimitry Andric // inline initializers as definitions. 41270b57cec5SDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 41280b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 41290b57cec5SDimitry Andric } 41300b57cec5SDimitry Andric 41310b57cec5SDimitry Andric // Emit section information for extern variables. 41320b57cec5SDimitry Andric if (D->hasExternalStorage()) { 41330b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 41340b57cec5SDimitry Andric GV->setSection(SA->getName()); 41350b57cec5SDimitry Andric } 41360b57cec5SDimitry Andric 41370b57cec5SDimitry Andric // Handle XCore specific ABI requirements. 41380b57cec5SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 41390b57cec5SDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 41400b57cec5SDimitry Andric D->getType().isConstant(Context) && 41410b57cec5SDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 41420b57cec5SDimitry Andric GV->setSection(".cp.rodata"); 41430b57cec5SDimitry Andric 41440b57cec5SDimitry Andric // Check if we a have a const declaration with an initializer, we may be 41450b57cec5SDimitry Andric // able to emit it as available_externally to expose it's value to the 41460b57cec5SDimitry Andric // optimizer. 41470b57cec5SDimitry Andric if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 41480b57cec5SDimitry Andric D->getType().isConstQualified() && !GV->hasInitializer() && 41490b57cec5SDimitry Andric !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 41500b57cec5SDimitry Andric const auto *Record = 41510b57cec5SDimitry Andric Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 41520b57cec5SDimitry Andric bool HasMutableFields = Record && Record->hasMutableFields(); 41530b57cec5SDimitry Andric if (!HasMutableFields) { 41540b57cec5SDimitry Andric const VarDecl *InitDecl; 41550b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 41560b57cec5SDimitry Andric if (InitExpr) { 41570b57cec5SDimitry Andric ConstantEmitter emitter(*this); 41580b57cec5SDimitry Andric llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 41590b57cec5SDimitry Andric if (Init) { 41600b57cec5SDimitry Andric auto *InitType = Init->getType(); 41615ffd83dbSDimitry Andric if (GV->getValueType() != InitType) { 41620b57cec5SDimitry Andric // The type of the initializer does not match the definition. 41630b57cec5SDimitry Andric // This happens when an initializer has a different type from 41640b57cec5SDimitry Andric // the type of the global (because of padding at the end of a 41650b57cec5SDimitry Andric // structure for instance). 41660b57cec5SDimitry Andric GV->setName(StringRef()); 41670b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed 41680b57cec5SDimitry Andric // to work. 41690b57cec5SDimitry Andric auto *NewGV = cast<llvm::GlobalVariable>( 4170a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4171a7dea167SDimitry Andric ->stripPointerCasts()); 41720b57cec5SDimitry Andric 41730b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 41740b57cec5SDimitry Andric GV->eraseFromParent(); 41750b57cec5SDimitry Andric GV = NewGV; 41760b57cec5SDimitry Andric } else { 41770b57cec5SDimitry Andric GV->setInitializer(Init); 41780b57cec5SDimitry Andric GV->setConstant(true); 41790b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 41800b57cec5SDimitry Andric } 41810b57cec5SDimitry Andric emitter.finalize(GV); 41820b57cec5SDimitry Andric } 41830b57cec5SDimitry Andric } 41840b57cec5SDimitry Andric } 41850b57cec5SDimitry Andric } 41860b57cec5SDimitry Andric } 41870b57cec5SDimitry Andric 4188fe6060f1SDimitry Andric if (GV->isDeclaration()) { 4189480093f4SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4190fe6060f1SDimitry Andric // External HIP managed variables needed to be recorded for transformation 4191fe6060f1SDimitry Andric // in both device and host compilations. 4192fe6060f1SDimitry Andric if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4193fe6060f1SDimitry Andric D->hasExternalStorage()) 4194fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 4195fe6060f1SDimitry Andric } 4196480093f4SDimitry Andric 41970b57cec5SDimitry Andric LangAS ExpectedAS = 41980b57cec5SDimitry Andric D ? D->getType().getAddressSpace() 41990b57cec5SDimitry Andric : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4200349cc55cSDimitry Andric assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4201fe6060f1SDimitry Andric if (DAddrSpace != ExpectedAS) { 4202fe6060f1SDimitry Andric return getTargetCodeGenInfo().performAddrSpaceCast( 4203349cc55cSDimitry Andric *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4204fe6060f1SDimitry Andric } 42050b57cec5SDimitry Andric 42060b57cec5SDimitry Andric return GV; 42070b57cec5SDimitry Andric } 42080b57cec5SDimitry Andric 42090b57cec5SDimitry Andric llvm::Constant * 42105ffd83dbSDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 42110b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 42125ffd83dbSDimitry Andric 42130b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 42140b57cec5SDimitry Andric return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 42150b57cec5SDimitry Andric /*DontDefer=*/false, IsForDefinition); 42165ffd83dbSDimitry Andric 42175ffd83dbSDimitry Andric if (isa<CXXMethodDecl>(D)) { 42185ffd83dbSDimitry Andric auto FInfo = 42195ffd83dbSDimitry Andric &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 42200b57cec5SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 42210b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 42220b57cec5SDimitry Andric IsForDefinition); 42235ffd83dbSDimitry Andric } 42245ffd83dbSDimitry Andric 42255ffd83dbSDimitry Andric if (isa<FunctionDecl>(D)) { 42260b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 42270b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 42280b57cec5SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 42290b57cec5SDimitry Andric IsForDefinition); 42305ffd83dbSDimitry Andric } 42315ffd83dbSDimitry Andric 42325ffd83dbSDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 42330b57cec5SDimitry Andric } 42340b57cec5SDimitry Andric 42350b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 42360b57cec5SDimitry Andric StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 42370b57cec5SDimitry Andric unsigned Alignment) { 42380b57cec5SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 42390b57cec5SDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 42400b57cec5SDimitry Andric 42410b57cec5SDimitry Andric if (GV) { 42420b57cec5SDimitry Andric // Check if the variable has the right type. 42435ffd83dbSDimitry Andric if (GV->getValueType() == Ty) 42440b57cec5SDimitry Andric return GV; 42450b57cec5SDimitry Andric 42460b57cec5SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 42470b57cec5SDimitry Andric // existing global with the same name is if it has been declared extern "C". 42480b57cec5SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 42490b57cec5SDimitry Andric OldGV = GV; 42500b57cec5SDimitry Andric } 42510b57cec5SDimitry Andric 42520b57cec5SDimitry Andric // Create a new variable. 42530b57cec5SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 42540b57cec5SDimitry Andric Linkage, nullptr, Name); 42550b57cec5SDimitry Andric 42560b57cec5SDimitry Andric if (OldGV) { 42570b57cec5SDimitry Andric // Replace occurrences of the old variable if needed. 42580b57cec5SDimitry Andric GV->takeName(OldGV); 42590b57cec5SDimitry Andric 42600b57cec5SDimitry Andric if (!OldGV->use_empty()) { 42610b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 42620b57cec5SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 42630b57cec5SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 42640b57cec5SDimitry Andric } 42650b57cec5SDimitry Andric 42660b57cec5SDimitry Andric OldGV->eraseFromParent(); 42670b57cec5SDimitry Andric } 42680b57cec5SDimitry Andric 42690b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 42700b57cec5SDimitry Andric !GV->hasAvailableExternallyLinkage()) 42710b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 42720b57cec5SDimitry Andric 4273a7dea167SDimitry Andric GV->setAlignment(llvm::MaybeAlign(Alignment)); 42740b57cec5SDimitry Andric 42750b57cec5SDimitry Andric return GV; 42760b57cec5SDimitry Andric } 42770b57cec5SDimitry Andric 42780b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 42790b57cec5SDimitry Andric /// given global variable. If Ty is non-null and if the global doesn't exist, 42800b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the 42810b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed 42820b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 42830b57cec5SDimitry Andric /// variable with the same mangled name but some other type. 42840b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 42850b57cec5SDimitry Andric llvm::Type *Ty, 42860b57cec5SDimitry Andric ForDefinition_t IsForDefinition) { 42870b57cec5SDimitry Andric assert(D->hasGlobalStorage() && "Not a global variable"); 42880b57cec5SDimitry Andric QualType ASTTy = D->getType(); 42890b57cec5SDimitry Andric if (!Ty) 42900b57cec5SDimitry Andric Ty = getTypes().ConvertTypeForMem(ASTTy); 42910b57cec5SDimitry Andric 42920b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 4293349cc55cSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4294fe6060f1SDimitry Andric IsForDefinition); 42950b57cec5SDimitry Andric } 42960b57cec5SDimitry Andric 42970b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the 42980b57cec5SDimitry Andric /// specified type and name. 42990b57cec5SDimitry Andric llvm::Constant * 43000b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 43010b57cec5SDimitry Andric StringRef Name) { 4302349cc55cSDimitry Andric LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4303349cc55cSDimitry Andric : LangAS::Default; 4304fe6060f1SDimitry Andric auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 43050b57cec5SDimitry Andric setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 43060b57cec5SDimitry Andric return Ret; 43070b57cec5SDimitry Andric } 43080b57cec5SDimitry Andric 43090b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 43100b57cec5SDimitry Andric assert(!D->getInit() && "Cannot emit definite definitions here!"); 43110b57cec5SDimitry Andric 43120b57cec5SDimitry Andric StringRef MangledName = getMangledName(D); 43130b57cec5SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 43140b57cec5SDimitry Andric 43150b57cec5SDimitry Andric // We already have a definition, not declaration, with the same mangled name. 43160b57cec5SDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 43170b57cec5SDimitry Andric // definition). 43180b57cec5SDimitry Andric if (GV && !GV->isDeclaration()) 43190b57cec5SDimitry Andric return; 43200b57cec5SDimitry Andric 43210b57cec5SDimitry Andric // If we have not seen a reference to this variable yet, place it into the 43220b57cec5SDimitry Andric // deferred declarations table to be emitted if needed later. 43230b57cec5SDimitry Andric if (!MustBeEmitted(D) && !GV) { 43240b57cec5SDimitry Andric DeferredDecls[MangledName] = D; 43250b57cec5SDimitry Andric return; 43260b57cec5SDimitry Andric } 43270b57cec5SDimitry Andric 43280b57cec5SDimitry Andric // The tentative definition is the only definition. 43290b57cec5SDimitry Andric EmitGlobalVarDefinition(D); 43300b57cec5SDimitry Andric } 43310b57cec5SDimitry Andric 4332480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4333480093f4SDimitry Andric EmitExternalVarDeclaration(D); 4334480093f4SDimitry Andric } 4335480093f4SDimitry Andric 43360b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 43370b57cec5SDimitry Andric return Context.toCharUnitsFromBits( 43380b57cec5SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 43390b57cec5SDimitry Andric } 43400b57cec5SDimitry Andric 43410b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 43420b57cec5SDimitry Andric if (LangOpts.OpenCL) { 4343349cc55cSDimitry Andric LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4344349cc55cSDimitry Andric assert(AS == LangAS::opencl_global || 4345349cc55cSDimitry Andric AS == LangAS::opencl_global_device || 4346349cc55cSDimitry Andric AS == LangAS::opencl_global_host || 4347349cc55cSDimitry Andric AS == LangAS::opencl_constant || 4348349cc55cSDimitry Andric AS == LangAS::opencl_local || 4349349cc55cSDimitry Andric AS >= LangAS::FirstTargetAddressSpace); 4350349cc55cSDimitry Andric return AS; 43510b57cec5SDimitry Andric } 43520b57cec5SDimitry Andric 4353fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice && 4354fe6060f1SDimitry Andric (!D || D->getType().getAddressSpace() == LangAS::Default)) 4355fe6060f1SDimitry Andric return LangAS::sycl_global; 4356fe6060f1SDimitry Andric 43570b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 43580b57cec5SDimitry Andric if (D && D->hasAttr<CUDAConstantAttr>()) 43590b57cec5SDimitry Andric return LangAS::cuda_constant; 43600b57cec5SDimitry Andric else if (D && D->hasAttr<CUDASharedAttr>()) 43610b57cec5SDimitry Andric return LangAS::cuda_shared; 43620b57cec5SDimitry Andric else if (D && D->hasAttr<CUDADeviceAttr>()) 43630b57cec5SDimitry Andric return LangAS::cuda_device; 43640b57cec5SDimitry Andric else if (D && D->getType().isConstQualified()) 43650b57cec5SDimitry Andric return LangAS::cuda_constant; 43660b57cec5SDimitry Andric else 43670b57cec5SDimitry Andric return LangAS::cuda_device; 43680b57cec5SDimitry Andric } 43690b57cec5SDimitry Andric 43700b57cec5SDimitry Andric if (LangOpts.OpenMP) { 43710b57cec5SDimitry Andric LangAS AS; 43720b57cec5SDimitry Andric if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 43730b57cec5SDimitry Andric return AS; 43740b57cec5SDimitry Andric } 43750b57cec5SDimitry Andric return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 43760b57cec5SDimitry Andric } 43770b57cec5SDimitry Andric 4378fe6060f1SDimitry Andric LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 43790b57cec5SDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 43800b57cec5SDimitry Andric if (LangOpts.OpenCL) 43810b57cec5SDimitry Andric return LangAS::opencl_constant; 4382fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 4383fe6060f1SDimitry Andric return LangAS::sycl_global; 4384d56accc7SDimitry Andric if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 4385d56accc7SDimitry Andric // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 4386d56accc7SDimitry Andric // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 4387d56accc7SDimitry Andric // with OpVariable instructions with Generic storage class which is not 4388d56accc7SDimitry Andric // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 4389d56accc7SDimitry Andric // UniformConstant storage class is not viable as pointers to it may not be 4390d56accc7SDimitry Andric // casted to Generic pointers which are used to model HIP's "flat" pointers. 4391d56accc7SDimitry Andric return LangAS::cuda_device; 43920b57cec5SDimitry Andric if (auto AS = getTarget().getConstantAddressSpace()) 43930b57cec5SDimitry Andric return AS.getValue(); 43940b57cec5SDimitry Andric return LangAS::Default; 43950b57cec5SDimitry Andric } 43960b57cec5SDimitry Andric 43970b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address 43980b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be 43990b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other 44000b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space 44010b57cec5SDimitry Andric // need to be casted to default address space before being put into address 44020b57cec5SDimitry Andric // map and referenced by other part of CodeGen. 44030b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore 44040b57cec5SDimitry Andric // they should not be casted to default address space. 44050b57cec5SDimitry Andric static llvm::Constant * 44060b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 44070b57cec5SDimitry Andric llvm::GlobalVariable *GV) { 44080b57cec5SDimitry Andric llvm::Constant *Cast = GV; 44090b57cec5SDimitry Andric if (!CGM.getLangOpts().OpenCL) { 4410fe6060f1SDimitry Andric auto AS = CGM.GetGlobalConstantAddressSpace(); 44110b57cec5SDimitry Andric if (AS != LangAS::Default) 44120b57cec5SDimitry Andric Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4413fe6060f1SDimitry Andric CGM, GV, AS, LangAS::Default, 44140b57cec5SDimitry Andric GV->getValueType()->getPointerTo( 44150b57cec5SDimitry Andric CGM.getContext().getTargetAddressSpace(LangAS::Default))); 44160b57cec5SDimitry Andric } 44170b57cec5SDimitry Andric return Cast; 44180b57cec5SDimitry Andric } 44190b57cec5SDimitry Andric 44200b57cec5SDimitry Andric template<typename SomeDecl> 44210b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 44220b57cec5SDimitry Andric llvm::GlobalValue *GV) { 44230b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 44240b57cec5SDimitry Andric return; 44250b57cec5SDimitry Andric 44260b57cec5SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 44270b57cec5SDimitry Andric // the name existing. 44280b57cec5SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 44290b57cec5SDimitry Andric return; 44300b57cec5SDimitry Andric 44310b57cec5SDimitry Andric // Must have internal linkage and an ordinary name. 44320b57cec5SDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 44330b57cec5SDimitry Andric return; 44340b57cec5SDimitry Andric 44350b57cec5SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 44360b57cec5SDimitry Andric // a record are not extern "C" even if the record is in such a context. 44370b57cec5SDimitry Andric const SomeDecl *First = D->getFirstDecl(); 44380b57cec5SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 44390b57cec5SDimitry Andric return; 44400b57cec5SDimitry Andric 44410b57cec5SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 44420b57cec5SDimitry Andric // specification. Make a note of that so we can give it the "expected" 44430b57cec5SDimitry Andric // mangled name if nothing else is using that name. 44440b57cec5SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 44450b57cec5SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 44460b57cec5SDimitry Andric 44470b57cec5SDimitry Andric // If we have multiple internal linkage entities with the same name 44480b57cec5SDimitry Andric // in extern "C" regions, none of them gets that name. 44490b57cec5SDimitry Andric if (!R.second) 44500b57cec5SDimitry Andric R.first->second = nullptr; 44510b57cec5SDimitry Andric } 44520b57cec5SDimitry Andric 44530b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 44540b57cec5SDimitry Andric if (!CGM.supportsCOMDAT()) 44550b57cec5SDimitry Andric return false; 44560b57cec5SDimitry Andric 44570b57cec5SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 44580b57cec5SDimitry Andric return true; 44590b57cec5SDimitry Andric 44600b57cec5SDimitry Andric GVALinkage Linkage; 44610b57cec5SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 44620b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 44630b57cec5SDimitry Andric else 44640b57cec5SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 44650b57cec5SDimitry Andric 44660b57cec5SDimitry Andric switch (Linkage) { 44670b57cec5SDimitry Andric case GVA_Internal: 44680b57cec5SDimitry Andric case GVA_AvailableExternally: 44690b57cec5SDimitry Andric case GVA_StrongExternal: 44700b57cec5SDimitry Andric return false; 44710b57cec5SDimitry Andric case GVA_DiscardableODR: 44720b57cec5SDimitry Andric case GVA_StrongODR: 44730b57cec5SDimitry Andric return true; 44740b57cec5SDimitry Andric } 44750b57cec5SDimitry Andric llvm_unreachable("No such linkage"); 44760b57cec5SDimitry Andric } 44770b57cec5SDimitry Andric 44780b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 44790b57cec5SDimitry Andric llvm::GlobalObject &GO) { 44800b57cec5SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 44810b57cec5SDimitry Andric return; 44820b57cec5SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 44830b57cec5SDimitry Andric } 44840b57cec5SDimitry Andric 44850b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 44860b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 44870b57cec5SDimitry Andric bool IsTentative) { 44880b57cec5SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 44890b57cec5SDimitry Andric // therefore no need to be translated. 44900b57cec5SDimitry Andric QualType ASTTy = D->getType(); 44910b57cec5SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 44920b57cec5SDimitry Andric return; 44930b57cec5SDimitry Andric 44940b57cec5SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 44950b57cec5SDimitry Andric // normally. 44960b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 44970b57cec5SDimitry Andric OpenMPRuntime->emitTargetGlobalVariable(D)) 44980b57cec5SDimitry Andric return; 44990b57cec5SDimitry Andric 4500fe6060f1SDimitry Andric llvm::TrackingVH<llvm::Constant> Init; 45010b57cec5SDimitry Andric bool NeedsGlobalCtor = false; 4502a7dea167SDimitry Andric bool NeedsGlobalDtor = 4503a7dea167SDimitry Andric D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 45040b57cec5SDimitry Andric 45050b57cec5SDimitry Andric const VarDecl *InitDecl; 45060b57cec5SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 45070b57cec5SDimitry Andric 45080b57cec5SDimitry Andric Optional<ConstantEmitter> emitter; 45090b57cec5SDimitry Andric 45100b57cec5SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 45110b57cec5SDimitry Andric // as part of their declaration." Sema has already checked for 45120b57cec5SDimitry Andric // error cases, so we just need to set Init to UndefValue. 45130b57cec5SDimitry Andric bool IsCUDASharedVar = 45140b57cec5SDimitry Andric getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 45150b57cec5SDimitry Andric // Shadows of initialized device-side global variables are also left 45160b57cec5SDimitry Andric // undefined. 4517fe6060f1SDimitry Andric // Managed Variables should be initialized on both host side and device side. 45180b57cec5SDimitry Andric bool IsCUDAShadowVar = 4519e8d8bef9SDimitry Andric !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 45200b57cec5SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 45210b57cec5SDimitry Andric D->hasAttr<CUDASharedAttr>()); 45225ffd83dbSDimitry Andric bool IsCUDADeviceShadowVar = 4523fe6060f1SDimitry Andric getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 45245ffd83dbSDimitry Andric (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4525fe6060f1SDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType()); 45260b57cec5SDimitry Andric if (getLangOpts().CUDA && 45275ffd83dbSDimitry Andric (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4528fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 45295ffd83dbSDimitry Andric else if (D->hasAttr<LoaderUninitializedAttr>()) 4530fe6060f1SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 45310b57cec5SDimitry Andric else if (!InitExpr) { 45320b57cec5SDimitry Andric // This is a tentative definition; tentative definitions are 45330b57cec5SDimitry Andric // implicitly initialized with { 0 }. 45340b57cec5SDimitry Andric // 45350b57cec5SDimitry Andric // Note that tentative definitions are only emitted at the end of 45360b57cec5SDimitry Andric // a translation unit, so they should never have incomplete 45370b57cec5SDimitry Andric // type. In addition, EmitTentativeDefinition makes sure that we 45380b57cec5SDimitry Andric // never attempt to emit a tentative definition if a real one 45390b57cec5SDimitry Andric // exists. A use may still exists, however, so we still may need 45400b57cec5SDimitry Andric // to do a RAUW. 45410b57cec5SDimitry Andric assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 45420b57cec5SDimitry Andric Init = EmitNullConstant(D->getType()); 45430b57cec5SDimitry Andric } else { 45440b57cec5SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 45450b57cec5SDimitry Andric emitter.emplace(*this); 4546fe6060f1SDimitry Andric llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4547fe6060f1SDimitry Andric if (!Initializer) { 45480b57cec5SDimitry Andric QualType T = InitExpr->getType(); 45490b57cec5SDimitry Andric if (D->getType()->isReferenceType()) 45500b57cec5SDimitry Andric T = D->getType(); 45510b57cec5SDimitry Andric 45520b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 45530b57cec5SDimitry Andric Init = EmitNullConstant(T); 45540b57cec5SDimitry Andric NeedsGlobalCtor = true; 45550b57cec5SDimitry Andric } else { 45560b57cec5SDimitry Andric ErrorUnsupported(D, "static initializer"); 45570b57cec5SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 45580b57cec5SDimitry Andric } 45590b57cec5SDimitry Andric } else { 4560fe6060f1SDimitry Andric Init = Initializer; 45610b57cec5SDimitry Andric // We don't need an initializer, so remove the entry for the delayed 45620b57cec5SDimitry Andric // initializer position (just in case this entry was delayed) if we 45630b57cec5SDimitry Andric // also don't need to register a destructor. 45640b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 45650b57cec5SDimitry Andric DelayedCXXInitPosition.erase(D); 45660b57cec5SDimitry Andric } 45670b57cec5SDimitry Andric } 45680b57cec5SDimitry Andric 45690b57cec5SDimitry Andric llvm::Type* InitType = Init->getType(); 45700b57cec5SDimitry Andric llvm::Constant *Entry = 45710b57cec5SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 45720b57cec5SDimitry Andric 4573a7dea167SDimitry Andric // Strip off pointer casts if we got them. 4574a7dea167SDimitry Andric Entry = Entry->stripPointerCasts(); 45750b57cec5SDimitry Andric 45760b57cec5SDimitry Andric // Entry is now either a Function or GlobalVariable. 45770b57cec5SDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 45780b57cec5SDimitry Andric 45790b57cec5SDimitry Andric // We have a definition after a declaration with the wrong type. 45800b57cec5SDimitry Andric // We must make a new GlobalVariable* and update everything that used OldGV 45810b57cec5SDimitry Andric // (a declaration or tentative definition) with the new GlobalVariable* 45820b57cec5SDimitry Andric // (which will be a definition). 45830b57cec5SDimitry Andric // 45840b57cec5SDimitry Andric // This happens if there is a prototype for a global (e.g. 45850b57cec5SDimitry Andric // "extern int x[];") and then a definition of a different type (e.g. 45860b57cec5SDimitry Andric // "int x[10];"). This also happens when an initializer has a different type 45870b57cec5SDimitry Andric // from the type of the global (this happens with unions). 45885ffd83dbSDimitry Andric if (!GV || GV->getValueType() != InitType || 45890b57cec5SDimitry Andric GV->getType()->getAddressSpace() != 45900b57cec5SDimitry Andric getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 45910b57cec5SDimitry Andric 45920b57cec5SDimitry Andric // Move the old entry aside so that we'll create a new one. 45930b57cec5SDimitry Andric Entry->setName(StringRef()); 45940b57cec5SDimitry Andric 45950b57cec5SDimitry Andric // Make a new global with the correct type, this is now guaranteed to work. 45960b57cec5SDimitry Andric GV = cast<llvm::GlobalVariable>( 4597a7dea167SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4598a7dea167SDimitry Andric ->stripPointerCasts()); 45990b57cec5SDimitry Andric 46000b57cec5SDimitry Andric // Replace all uses of the old global with the new global 46010b57cec5SDimitry Andric llvm::Constant *NewPtrForOldDecl = 4602fe6060f1SDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4603fe6060f1SDimitry Andric Entry->getType()); 46040b57cec5SDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 46050b57cec5SDimitry Andric 46060b57cec5SDimitry Andric // Erase the old global, since it is no longer used. 46070b57cec5SDimitry Andric cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 46080b57cec5SDimitry Andric } 46090b57cec5SDimitry Andric 46100b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, GV); 46110b57cec5SDimitry Andric 46120b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 46130b57cec5SDimitry Andric AddGlobalAnnotations(D, GV); 46140b57cec5SDimitry Andric 46150b57cec5SDimitry Andric // Set the llvm linkage type as appropriate. 46160b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 46170b57cec5SDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 46180b57cec5SDimitry Andric 46190b57cec5SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 46200b57cec5SDimitry Andric // the device. [...]" 46210b57cec5SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 46220b57cec5SDimitry Andric // __device__, declares a variable that: [...] 46230b57cec5SDimitry Andric // Is accessible from all the threads within the grid and from the host 46240b57cec5SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 46250b57cec5SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 46260b57cec5SDimitry Andric if (GV && LangOpts.CUDA) { 46270b57cec5SDimitry Andric if (LangOpts.CUDAIsDevice) { 46280b57cec5SDimitry Andric if (Linkage != llvm::GlobalValue::InternalLinkage && 4629349cc55cSDimitry Andric (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4630349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinSurfaceType() || 4631349cc55cSDimitry Andric D->getType()->isCUDADeviceBuiltinTextureType())) 46320b57cec5SDimitry Andric GV->setExternallyInitialized(true); 46330b57cec5SDimitry Andric } else { 4634fe6060f1SDimitry Andric getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 46355ffd83dbSDimitry Andric } 4636fe6060f1SDimitry Andric getCUDARuntime().handleVarRegistration(D, *GV); 46370b57cec5SDimitry Andric } 46380b57cec5SDimitry Andric 46390b57cec5SDimitry Andric GV->setInitializer(Init); 46405ffd83dbSDimitry Andric if (emitter) 46415ffd83dbSDimitry Andric emitter->finalize(GV); 46420b57cec5SDimitry Andric 46430b57cec5SDimitry Andric // If it is safe to mark the global 'constant', do so now. 46440b57cec5SDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 46450b57cec5SDimitry Andric isTypeConstant(D->getType(), true)); 46460b57cec5SDimitry Andric 46470b57cec5SDimitry Andric // If it is in a read-only section, mark it 'constant'. 46480b57cec5SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 46490b57cec5SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 46500b57cec5SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 46510b57cec5SDimitry Andric GV->setConstant(true); 46520b57cec5SDimitry Andric } 46530b57cec5SDimitry Andric 4654a7dea167SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 46550b57cec5SDimitry Andric 46565ffd83dbSDimitry Andric // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 46575ffd83dbSDimitry Andric // function is only defined alongside the variable, not also alongside 46585ffd83dbSDimitry Andric // callers. Normally, all accesses to a thread_local go through the 46595ffd83dbSDimitry Andric // thread-wrapper in order to ensure initialization has occurred, underlying 46605ffd83dbSDimitry Andric // variable will never be used other than the thread-wrapper, so it can be 46615ffd83dbSDimitry Andric // converted to internal linkage. 46625ffd83dbSDimitry Andric // 46635ffd83dbSDimitry Andric // However, if the variable has the 'constinit' attribute, it _can_ be 46645ffd83dbSDimitry Andric // referenced directly, without calling the thread-wrapper, so the linkage 46655ffd83dbSDimitry Andric // must not be changed. 46665ffd83dbSDimitry Andric // 46675ffd83dbSDimitry Andric // Additionally, if the variable isn't plain external linkage, e.g. if it's 46685ffd83dbSDimitry Andric // weak or linkonce, the de-duplication semantics are important to preserve, 46695ffd83dbSDimitry Andric // so we don't change the linkage. 46705ffd83dbSDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic && 46715ffd83dbSDimitry Andric Linkage == llvm::GlobalValue::ExternalLinkage && 46720b57cec5SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 46735ffd83dbSDimitry Andric !D->hasAttr<ConstInitAttr>()) 46740b57cec5SDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 46750b57cec5SDimitry Andric 46760b57cec5SDimitry Andric GV->setLinkage(Linkage); 46770b57cec5SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 46780b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 46790b57cec5SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 46800b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 46810b57cec5SDimitry Andric else 46820b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 46830b57cec5SDimitry Andric 46840b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 46850b57cec5SDimitry Andric // common vars aren't constant even if declared const. 46860b57cec5SDimitry Andric GV->setConstant(false); 46870b57cec5SDimitry Andric // Tentative definition of global variables may be initialized with 46880b57cec5SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 46890b57cec5SDimitry Andric // since common linkage must have zero initializer and must not have 46900b57cec5SDimitry Andric // explicit section therefore cannot have non-zero initial value. 46910b57cec5SDimitry Andric if (!GV->getInitializer()->isNullValue()) 46920b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 46930b57cec5SDimitry Andric } 46940b57cec5SDimitry Andric 46950b57cec5SDimitry Andric setNonAliasAttributes(D, GV); 46960b57cec5SDimitry Andric 46970b57cec5SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 46980b57cec5SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 46990b57cec5SDimitry Andric CXXThreadLocals.push_back(D); 47000b57cec5SDimitry Andric setTLSMode(GV, *D); 47010b57cec5SDimitry Andric } 47020b57cec5SDimitry Andric 47030b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *GV); 47040b57cec5SDimitry Andric 47050b57cec5SDimitry Andric // Emit the initializer function if necessary. 47060b57cec5SDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 47070b57cec5SDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 47080b57cec5SDimitry Andric 47090b57cec5SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 47100b57cec5SDimitry Andric 47110b57cec5SDimitry Andric // Emit global variable debug information. 47120b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4713480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 47140b57cec5SDimitry Andric DI->EmitGlobalVariable(GV, D); 47150b57cec5SDimitry Andric } 47160b57cec5SDimitry Andric 4717480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4718480093f4SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4719480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) { 4720480093f4SDimitry Andric QualType ASTTy = D->getType(); 4721480093f4SDimitry Andric llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4722349cc55cSDimitry Andric llvm::Constant *GV = 4723349cc55cSDimitry Andric GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4724480093f4SDimitry Andric DI->EmitExternalVariable( 4725480093f4SDimitry Andric cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4726480093f4SDimitry Andric } 4727480093f4SDimitry Andric } 4728480093f4SDimitry Andric 47290b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 47300b57cec5SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 47310b57cec5SDimitry Andric bool NoCommon) { 47320b57cec5SDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 47330b57cec5SDimitry Andric // was overridden by a NoCommon attribute. 47340b57cec5SDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 47350b57cec5SDimitry Andric return true; 47360b57cec5SDimitry Andric 47370b57cec5SDimitry Andric // C11 6.9.2/2: 47380b57cec5SDimitry Andric // A declaration of an identifier for an object that has file scope without 47390b57cec5SDimitry Andric // an initializer, and without a storage-class specifier or with the 47400b57cec5SDimitry Andric // storage-class specifier static, constitutes a tentative definition. 47410b57cec5SDimitry Andric if (D->getInit() || D->hasExternalStorage()) 47420b57cec5SDimitry Andric return true; 47430b57cec5SDimitry Andric 47440b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 47450b57cec5SDimitry Andric if (D->hasAttr<SectionAttr>()) 47460b57cec5SDimitry Andric return true; 47470b57cec5SDimitry Andric 47480b57cec5SDimitry Andric // A variable cannot be both common and exist in a section. 47490b57cec5SDimitry Andric // We don't try to determine which is the right section in the front-end. 47500b57cec5SDimitry Andric // If no specialized section name is applicable, it will resort to default. 47510b57cec5SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 47520b57cec5SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 4753a7dea167SDimitry Andric D->hasAttr<PragmaClangRelroSectionAttr>() || 47540b57cec5SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 47550b57cec5SDimitry Andric return true; 47560b57cec5SDimitry Andric 47570b57cec5SDimitry Andric // Thread local vars aren't considered common linkage. 47580b57cec5SDimitry Andric if (D->getTLSKind()) 47590b57cec5SDimitry Andric return true; 47600b57cec5SDimitry Andric 47610b57cec5SDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 47620b57cec5SDimitry Andric if (D->hasAttr<WeakImportAttr>()) 47630b57cec5SDimitry Andric return true; 47640b57cec5SDimitry Andric 47650b57cec5SDimitry Andric // A variable cannot be both common and exist in a comdat. 47660b57cec5SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 47670b57cec5SDimitry Andric return true; 47680b57cec5SDimitry Andric 47690b57cec5SDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 47700b57cec5SDimitry Andric // mode. 47710b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 47720b57cec5SDimitry Andric if (D->hasAttr<AlignedAttr>()) 47730b57cec5SDimitry Andric return true; 47740b57cec5SDimitry Andric QualType VarType = D->getType(); 47750b57cec5SDimitry Andric if (Context.isAlignmentRequired(VarType)) 47760b57cec5SDimitry Andric return true; 47770b57cec5SDimitry Andric 47780b57cec5SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 47790b57cec5SDimitry Andric const RecordDecl *RD = RT->getDecl(); 47800b57cec5SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 47810b57cec5SDimitry Andric if (FD->isBitField()) 47820b57cec5SDimitry Andric continue; 47830b57cec5SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 47840b57cec5SDimitry Andric return true; 47850b57cec5SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 47860b57cec5SDimitry Andric return true; 47870b57cec5SDimitry Andric } 47880b57cec5SDimitry Andric } 47890b57cec5SDimitry Andric } 47900b57cec5SDimitry Andric 47910b57cec5SDimitry Andric // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 47920b57cec5SDimitry Andric // common symbols, so symbols with greater alignment requirements cannot be 47930b57cec5SDimitry Andric // common. 47940b57cec5SDimitry Andric // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 47950b57cec5SDimitry Andric // alignments for common symbols via the aligncomm directive, so this 47960b57cec5SDimitry Andric // restriction only applies to MSVC environments. 47970b57cec5SDimitry Andric if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 47980b57cec5SDimitry Andric Context.getTypeAlignIfKnown(D->getType()) > 47990b57cec5SDimitry Andric Context.toBits(CharUnits::fromQuantity(32))) 48000b57cec5SDimitry Andric return true; 48010b57cec5SDimitry Andric 48020b57cec5SDimitry Andric return false; 48030b57cec5SDimitry Andric } 48040b57cec5SDimitry Andric 48050b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 48060b57cec5SDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 48070b57cec5SDimitry Andric if (Linkage == GVA_Internal) 48080b57cec5SDimitry Andric return llvm::Function::InternalLinkage; 48090b57cec5SDimitry Andric 48100b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>()) { 48110b57cec5SDimitry Andric if (IsConstantVariable) 48120b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 48130b57cec5SDimitry Andric else 48140b57cec5SDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 48150b57cec5SDimitry Andric } 48160b57cec5SDimitry Andric 48170b57cec5SDimitry Andric if (const auto *FD = D->getAsFunction()) 48180b57cec5SDimitry Andric if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 48190b57cec5SDimitry Andric return llvm::GlobalVariable::LinkOnceAnyLinkage; 48200b57cec5SDimitry Andric 48210b57cec5SDimitry Andric // We are guaranteed to have a strong definition somewhere else, 48220b57cec5SDimitry Andric // so we can use available_externally linkage. 48230b57cec5SDimitry Andric if (Linkage == GVA_AvailableExternally) 48240b57cec5SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 48250b57cec5SDimitry Andric 48260b57cec5SDimitry Andric // Note that Apple's kernel linker doesn't support symbol 48270b57cec5SDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 48280b57cec5SDimitry Andric // Normally, this means we just map to internal, but for explicit 48290b57cec5SDimitry Andric // instantiations we'll map to external. 48300b57cec5SDimitry Andric 48310b57cec5SDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 48320b57cec5SDimitry Andric // that references the function. We should use linkonce_odr because 48330b57cec5SDimitry Andric // a) if all references in this translation unit are optimized away, we 48340b57cec5SDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 48350b57cec5SDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 48360b57cec5SDimitry Andric // definition is dependable. 48370b57cec5SDimitry Andric if (Linkage == GVA_DiscardableODR) 48380b57cec5SDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 48390b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 48400b57cec5SDimitry Andric 48410b57cec5SDimitry Andric // An explicit instantiation of a template has weak linkage, since 48420b57cec5SDimitry Andric // explicit instantiations can occur in multiple translation units 48430b57cec5SDimitry Andric // and must all be equivalent. However, we are not allowed to 48440b57cec5SDimitry Andric // throw away these explicit instantiations. 48450b57cec5SDimitry Andric // 4846e8d8bef9SDimitry Andric // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 48470b57cec5SDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 4848e8d8bef9SDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. For 4849e8d8bef9SDimitry Andric // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4850e8d8bef9SDimitry Andric // therefore we need to follow the normal linkage paradigm. 48510b57cec5SDimitry Andric if (Linkage == GVA_StrongODR) { 4852e8d8bef9SDimitry Andric if (getLangOpts().AppleKext) 48530b57cec5SDimitry Andric return llvm::Function::ExternalLinkage; 4854e8d8bef9SDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4855e8d8bef9SDimitry Andric !getLangOpts().GPURelocatableDeviceCode) 48560b57cec5SDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 48570b57cec5SDimitry Andric : llvm::Function::InternalLinkage; 48580b57cec5SDimitry Andric return llvm::Function::WeakODRLinkage; 48590b57cec5SDimitry Andric } 48600b57cec5SDimitry Andric 48610b57cec5SDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 48620b57cec5SDimitry Andric // linkage. 48630b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 48640b57cec5SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 48650b57cec5SDimitry Andric CodeGenOpts.NoCommon)) 48660b57cec5SDimitry Andric return llvm::GlobalVariable::CommonLinkage; 48670b57cec5SDimitry Andric 48680b57cec5SDimitry Andric // selectany symbols are externally visible, so use weak instead of 48690b57cec5SDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 48700b57cec5SDimitry Andric // all definitions should be the same and ODR linkage should be used. 48710b57cec5SDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 48720b57cec5SDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 48730b57cec5SDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 48740b57cec5SDimitry Andric 48750b57cec5SDimitry Andric // Otherwise, we have strong external linkage. 48760b57cec5SDimitry Andric assert(Linkage == GVA_StrongExternal); 48770b57cec5SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 48780b57cec5SDimitry Andric } 48790b57cec5SDimitry Andric 48800b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 48810b57cec5SDimitry Andric const VarDecl *VD, bool IsConstant) { 48820b57cec5SDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 48830b57cec5SDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 48840b57cec5SDimitry Andric } 48850b57cec5SDimitry Andric 48860b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 48870b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites 48880b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 48890b57cec5SDimitry Andric llvm::Function *newFn) { 48900b57cec5SDimitry Andric // Fast path. 48910b57cec5SDimitry Andric if (old->use_empty()) return; 48920b57cec5SDimitry Andric 48930b57cec5SDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 48940b57cec5SDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 48950b57cec5SDimitry Andric 48960b57cec5SDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 48970b57cec5SDimitry Andric ui != ue; ) { 48980b57cec5SDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 48990b57cec5SDimitry Andric llvm::User *user = use->getUser(); 49000b57cec5SDimitry Andric 49010b57cec5SDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 49020b57cec5SDimitry Andric // unprototyped functions will use bitcasts. 49030b57cec5SDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 49040b57cec5SDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 49050b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 49060b57cec5SDimitry Andric continue; 49070b57cec5SDimitry Andric } 49080b57cec5SDimitry Andric 49090b57cec5SDimitry Andric // Recognize calls to the function. 49100b57cec5SDimitry Andric llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 49110b57cec5SDimitry Andric if (!callSite) continue; 49120b57cec5SDimitry Andric if (!callSite->isCallee(&*use)) 49130b57cec5SDimitry Andric continue; 49140b57cec5SDimitry Andric 49150b57cec5SDimitry Andric // If the return types don't match exactly, then we can't 49160b57cec5SDimitry Andric // transform this call unless it's dead. 49170b57cec5SDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 49180b57cec5SDimitry Andric continue; 49190b57cec5SDimitry Andric 49200b57cec5SDimitry Andric // Get the call site's attribute list. 49210b57cec5SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 49220b57cec5SDimitry Andric llvm::AttributeList oldAttrs = callSite->getAttributes(); 49230b57cec5SDimitry Andric 49240b57cec5SDimitry Andric // If the function was passed too few arguments, don't transform. 49250b57cec5SDimitry Andric unsigned newNumArgs = newFn->arg_size(); 49260b57cec5SDimitry Andric if (callSite->arg_size() < newNumArgs) 49270b57cec5SDimitry Andric continue; 49280b57cec5SDimitry Andric 49290b57cec5SDimitry Andric // If extra arguments were passed, we silently drop them. 49300b57cec5SDimitry Andric // If any of the types mismatch, we don't transform. 49310b57cec5SDimitry Andric unsigned argNo = 0; 49320b57cec5SDimitry Andric bool dontTransform = false; 49330b57cec5SDimitry Andric for (llvm::Argument &A : newFn->args()) { 49340b57cec5SDimitry Andric if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 49350b57cec5SDimitry Andric dontTransform = true; 49360b57cec5SDimitry Andric break; 49370b57cec5SDimitry Andric } 49380b57cec5SDimitry Andric 49390b57cec5SDimitry Andric // Add any parameter attributes. 4940349cc55cSDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 49410b57cec5SDimitry Andric argNo++; 49420b57cec5SDimitry Andric } 49430b57cec5SDimitry Andric if (dontTransform) 49440b57cec5SDimitry Andric continue; 49450b57cec5SDimitry Andric 49460b57cec5SDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 49470b57cec5SDimitry Andric // over the required information. 49480b57cec5SDimitry Andric newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 49490b57cec5SDimitry Andric 49500b57cec5SDimitry Andric // Copy over any operand bundles. 4951fe6060f1SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 49520b57cec5SDimitry Andric callSite->getOperandBundlesAsDefs(newBundles); 49530b57cec5SDimitry Andric 49540b57cec5SDimitry Andric llvm::CallBase *newCall; 4955349cc55cSDimitry Andric if (isa<llvm::CallInst>(callSite)) { 49560b57cec5SDimitry Andric newCall = 49570b57cec5SDimitry Andric llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 49580b57cec5SDimitry Andric } else { 49590b57cec5SDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 49600b57cec5SDimitry Andric newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 49610b57cec5SDimitry Andric oldInvoke->getUnwindDest(), newArgs, 49620b57cec5SDimitry Andric newBundles, "", callSite); 49630b57cec5SDimitry Andric } 49640b57cec5SDimitry Andric newArgs.clear(); // for the next iteration 49650b57cec5SDimitry Andric 49660b57cec5SDimitry Andric if (!newCall->getType()->isVoidTy()) 49670b57cec5SDimitry Andric newCall->takeName(callSite); 4968349cc55cSDimitry Andric newCall->setAttributes( 4969349cc55cSDimitry Andric llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 4970349cc55cSDimitry Andric oldAttrs.getRetAttrs(), newArgAttrs)); 49710b57cec5SDimitry Andric newCall->setCallingConv(callSite->getCallingConv()); 49720b57cec5SDimitry Andric 49730b57cec5SDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 49740b57cec5SDimitry Andric if (!callSite->use_empty()) 49750b57cec5SDimitry Andric callSite->replaceAllUsesWith(newCall); 49760b57cec5SDimitry Andric 49770b57cec5SDimitry Andric // Copy debug location attached to CI. 49780b57cec5SDimitry Andric if (callSite->getDebugLoc()) 49790b57cec5SDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 49800b57cec5SDimitry Andric 49810b57cec5SDimitry Andric callSite->eraseFromParent(); 49820b57cec5SDimitry Andric } 49830b57cec5SDimitry Andric } 49840b57cec5SDimitry Andric 49850b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 49860b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}". If there are 49870b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to 49880b57cec5SDimitry Andric /// call the new function directly. 49890b57cec5SDimitry Andric /// 49900b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to 49910b57cec5SDimitry Andric /// functions to be able to inline them. If there is a bitcast in the way, it 49920b57cec5SDimitry Andric /// won't inline them. Instcombine normally deletes these calls, but it isn't 49930b57cec5SDimitry Andric /// run at -O0. 49940b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 49950b57cec5SDimitry Andric llvm::Function *NewFn) { 49960b57cec5SDimitry Andric // If we're redefining a global as a function, don't transform it. 49970b57cec5SDimitry Andric if (!isa<llvm::Function>(Old)) return; 49980b57cec5SDimitry Andric 49990b57cec5SDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 50000b57cec5SDimitry Andric } 50010b57cec5SDimitry Andric 50020b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 50030b57cec5SDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 50040b57cec5SDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 50050b57cec5SDimitry Andric return; 50060b57cec5SDimitry Andric 50070b57cec5SDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 50080b57cec5SDimitry Andric // If we have a definition, this might be a deferred decl. If the 50090b57cec5SDimitry Andric // instantiation is explicit, make sure we emit it at the end. 50100b57cec5SDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 50110b57cec5SDimitry Andric GetAddrOfGlobalVar(VD); 50120b57cec5SDimitry Andric 50130b57cec5SDimitry Andric EmitTopLevelDecl(VD); 50140b57cec5SDimitry Andric } 50150b57cec5SDimitry Andric 50160b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 50170b57cec5SDimitry Andric llvm::GlobalValue *GV) { 50180b57cec5SDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 50190b57cec5SDimitry Andric 50200b57cec5SDimitry Andric // Compute the function info and LLVM type. 50210b57cec5SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 50220b57cec5SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 50230b57cec5SDimitry Andric 50240b57cec5SDimitry Andric // Get or create the prototype for the function. 50255ffd83dbSDimitry Andric if (!GV || (GV->getValueType() != Ty)) 50260b57cec5SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 50270b57cec5SDimitry Andric /*DontDefer=*/true, 50280b57cec5SDimitry Andric ForDefinition)); 50290b57cec5SDimitry Andric 50300b57cec5SDimitry Andric // Already emitted. 50310b57cec5SDimitry Andric if (!GV->isDeclaration()) 50320b57cec5SDimitry Andric return; 50330b57cec5SDimitry Andric 50340b57cec5SDimitry Andric // We need to set linkage and visibility on the function before 50350b57cec5SDimitry Andric // generating code for it because various parts of IR generation 50360b57cec5SDimitry Andric // want to propagate this information down (e.g. to local static 50370b57cec5SDimitry Andric // declarations). 50380b57cec5SDimitry Andric auto *Fn = cast<llvm::Function>(GV); 50390b57cec5SDimitry Andric setFunctionLinkage(GD, Fn); 50400b57cec5SDimitry Andric 50410b57cec5SDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 50420b57cec5SDimitry Andric setGVProperties(Fn, GD); 50430b57cec5SDimitry Andric 50440b57cec5SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 50450b57cec5SDimitry Andric 50460b57cec5SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 50470b57cec5SDimitry Andric 5048e8d8bef9SDimitry Andric // Set CodeGen attributes that represent floating point environment. 5049e8d8bef9SDimitry Andric setLLVMFunctionFEnvAttributes(D, Fn); 5050e8d8bef9SDimitry Andric 50515ffd83dbSDimitry Andric CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 50520b57cec5SDimitry Andric 50530b57cec5SDimitry Andric setNonAliasAttributes(GD, Fn); 50540b57cec5SDimitry Andric SetLLVMFunctionAttributesForDefinition(D, Fn); 50550b57cec5SDimitry Andric 50560b57cec5SDimitry Andric if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 50570b57cec5SDimitry Andric AddGlobalCtor(Fn, CA->getPriority()); 50580b57cec5SDimitry Andric if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5059e8d8bef9SDimitry Andric AddGlobalDtor(Fn, DA->getPriority(), true); 50600b57cec5SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 50610b57cec5SDimitry Andric AddGlobalAnnotations(D, Fn); 50620b57cec5SDimitry Andric } 50630b57cec5SDimitry Andric 50640b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 50650b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 50660b57cec5SDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 50670b57cec5SDimitry Andric assert(AA && "Not an alias?"); 50680b57cec5SDimitry Andric 50690b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 50700b57cec5SDimitry Andric 50710b57cec5SDimitry Andric if (AA->getAliasee() == MangledName) { 50720b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 50730b57cec5SDimitry Andric return; 50740b57cec5SDimitry Andric } 50750b57cec5SDimitry Andric 50760b57cec5SDimitry Andric // If there is a definition in the module, then it wins over the alias. 50770b57cec5SDimitry Andric // This is dubious, but allow it to be safe. Just ignore the alias. 50780b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 50790b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) 50800b57cec5SDimitry Andric return; 50810b57cec5SDimitry Andric 50820b57cec5SDimitry Andric Aliases.push_back(GD); 50830b57cec5SDimitry Andric 50840b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 50850b57cec5SDimitry Andric 50860b57cec5SDimitry Andric // Create a reference to the named value. This ensures that it is emitted 50870b57cec5SDimitry Andric // if a deferred decl. 50880b57cec5SDimitry Andric llvm::Constant *Aliasee; 50890b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 50900b57cec5SDimitry Andric if (isa<llvm::FunctionType>(DeclTy)) { 50910b57cec5SDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 50920b57cec5SDimitry Andric /*ForVTable=*/false); 50930b57cec5SDimitry Andric LT = getFunctionLinkage(GD); 50940b57cec5SDimitry Andric } else { 5095349cc55cSDimitry Andric Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 50960b57cec5SDimitry Andric /*D=*/nullptr); 5097e8d8bef9SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5098e8d8bef9SDimitry Andric LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5099e8d8bef9SDimitry Andric else 5100e8d8bef9SDimitry Andric LT = getFunctionLinkage(GD); 51010b57cec5SDimitry Andric } 51020b57cec5SDimitry Andric 51030b57cec5SDimitry Andric // Create the new alias itself, but don't set a name yet. 51045ffd83dbSDimitry Andric unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 51050b57cec5SDimitry Andric auto *GA = 51065ffd83dbSDimitry Andric llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 51070b57cec5SDimitry Andric 51080b57cec5SDimitry Andric if (Entry) { 51090b57cec5SDimitry Andric if (GA->getAliasee() == Entry) { 51100b57cec5SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 51110b57cec5SDimitry Andric return; 51120b57cec5SDimitry Andric } 51130b57cec5SDimitry Andric 51140b57cec5SDimitry Andric assert(Entry->isDeclaration()); 51150b57cec5SDimitry Andric 51160b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 51170b57cec5SDimitry Andric // by the alias, as in: 51180b57cec5SDimitry Andric // extern int test6(); 51190b57cec5SDimitry Andric // ... 51200b57cec5SDimitry Andric // int test6() __attribute__((alias("test7"))); 51210b57cec5SDimitry Andric // 51220b57cec5SDimitry Andric // Remove it and replace uses of it with the alias. 51230b57cec5SDimitry Andric GA->takeName(Entry); 51240b57cec5SDimitry Andric 51250b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 51260b57cec5SDimitry Andric Entry->getType())); 51270b57cec5SDimitry Andric Entry->eraseFromParent(); 51280b57cec5SDimitry Andric } else { 51290b57cec5SDimitry Andric GA->setName(MangledName); 51300b57cec5SDimitry Andric } 51310b57cec5SDimitry Andric 51320b57cec5SDimitry Andric // Set attributes which are particular to an alias; this is a 51330b57cec5SDimitry Andric // specialization of the attributes which may be set on a global 51340b57cec5SDimitry Andric // variable/function. 51350b57cec5SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 51360b57cec5SDimitry Andric D->isWeakImported()) { 51370b57cec5SDimitry Andric GA->setLinkage(llvm::Function::WeakAnyLinkage); 51380b57cec5SDimitry Andric } 51390b57cec5SDimitry Andric 51400b57cec5SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 51410b57cec5SDimitry Andric if (VD->getTLSKind()) 51420b57cec5SDimitry Andric setTLSMode(GA, *VD); 51430b57cec5SDimitry Andric 51440b57cec5SDimitry Andric SetCommonAttributes(GD, GA); 51450b57cec5SDimitry Andric } 51460b57cec5SDimitry Andric 51470b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 51480b57cec5SDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 51490b57cec5SDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 51500b57cec5SDimitry Andric assert(IFA && "Not an ifunc?"); 51510b57cec5SDimitry Andric 51520b57cec5SDimitry Andric StringRef MangledName = getMangledName(GD); 51530b57cec5SDimitry Andric 51540b57cec5SDimitry Andric if (IFA->getResolver() == MangledName) { 51550b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 51560b57cec5SDimitry Andric return; 51570b57cec5SDimitry Andric } 51580b57cec5SDimitry Andric 51590b57cec5SDimitry Andric // Report an error if some definition overrides ifunc. 51600b57cec5SDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 51610b57cec5SDimitry Andric if (Entry && !Entry->isDeclaration()) { 51620b57cec5SDimitry Andric GlobalDecl OtherGD; 51630b57cec5SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 51640b57cec5SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 51650b57cec5SDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 51660b57cec5SDimitry Andric << MangledName; 51670b57cec5SDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 51680b57cec5SDimitry Andric diag::note_previous_definition); 51690b57cec5SDimitry Andric } 51700b57cec5SDimitry Andric return; 51710b57cec5SDimitry Andric } 51720b57cec5SDimitry Andric 51730b57cec5SDimitry Andric Aliases.push_back(GD); 51740b57cec5SDimitry Andric 51750b57cec5SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5176349cc55cSDimitry Andric llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 51770b57cec5SDimitry Andric llvm::Constant *Resolver = 5178349cc55cSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 51790b57cec5SDimitry Andric /*ForVTable=*/false); 51800b57cec5SDimitry Andric llvm::GlobalIFunc *GIF = 51810b57cec5SDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 51820b57cec5SDimitry Andric "", Resolver, &getModule()); 51830b57cec5SDimitry Andric if (Entry) { 51840b57cec5SDimitry Andric if (GIF->getResolver() == Entry) { 51850b57cec5SDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 51860b57cec5SDimitry Andric return; 51870b57cec5SDimitry Andric } 51880b57cec5SDimitry Andric assert(Entry->isDeclaration()); 51890b57cec5SDimitry Andric 51900b57cec5SDimitry Andric // If there is a declaration in the module, then we had an extern followed 51910b57cec5SDimitry Andric // by the ifunc, as in: 51920b57cec5SDimitry Andric // extern int test(); 51930b57cec5SDimitry Andric // ... 51940b57cec5SDimitry Andric // int test() __attribute__((ifunc("resolver"))); 51950b57cec5SDimitry Andric // 51960b57cec5SDimitry Andric // Remove it and replace uses of it with the ifunc. 51970b57cec5SDimitry Andric GIF->takeName(Entry); 51980b57cec5SDimitry Andric 51990b57cec5SDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 52000b57cec5SDimitry Andric Entry->getType())); 52010b57cec5SDimitry Andric Entry->eraseFromParent(); 52020b57cec5SDimitry Andric } else 52030b57cec5SDimitry Andric GIF->setName(MangledName); 52040b57cec5SDimitry Andric 52050b57cec5SDimitry Andric SetCommonAttributes(GD, GIF); 52060b57cec5SDimitry Andric } 52070b57cec5SDimitry Andric 52080b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 52090b57cec5SDimitry Andric ArrayRef<llvm::Type*> Tys) { 52100b57cec5SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 52110b57cec5SDimitry Andric Tys); 52120b57cec5SDimitry Andric } 52130b57cec5SDimitry Andric 52140b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 52150b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 52160b57cec5SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 52170b57cec5SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 52180b57cec5SDimitry Andric StringRef String = Literal->getString(); 52190b57cec5SDimitry Andric unsigned NumBytes = String.size(); 52200b57cec5SDimitry Andric 52210b57cec5SDimitry Andric // Check for simple case. 52220b57cec5SDimitry Andric if (!Literal->containsNonAsciiOrNull()) { 52230b57cec5SDimitry Andric StringLength = NumBytes; 52240b57cec5SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 52250b57cec5SDimitry Andric } 52260b57cec5SDimitry Andric 52270b57cec5SDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 52280b57cec5SDimitry Andric IsUTF16 = true; 52290b57cec5SDimitry Andric 52300b57cec5SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 52310b57cec5SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 52320b57cec5SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 52330b57cec5SDimitry Andric 52340b57cec5SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 52350b57cec5SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 52360b57cec5SDimitry Andric 52370b57cec5SDimitry Andric // ConvertUTF8toUTF16 returns the length in ToPtr. 52380b57cec5SDimitry Andric StringLength = ToPtr - &ToBuf[0]; 52390b57cec5SDimitry Andric 52400b57cec5SDimitry Andric // Add an explicit null. 52410b57cec5SDimitry Andric *ToPtr = 0; 52420b57cec5SDimitry Andric return *Map.insert(std::make_pair( 52430b57cec5SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 52440b57cec5SDimitry Andric (StringLength + 1) * 2), 52450b57cec5SDimitry Andric nullptr)).first; 52460b57cec5SDimitry Andric } 52470b57cec5SDimitry Andric 52480b57cec5SDimitry Andric ConstantAddress 52490b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 52500b57cec5SDimitry Andric unsigned StringLength = 0; 52510b57cec5SDimitry Andric bool isUTF16 = false; 52520b57cec5SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 52530b57cec5SDimitry Andric GetConstantCFStringEntry(CFConstantStringMap, Literal, 52540b57cec5SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 52550b57cec5SDimitry Andric StringLength); 52560b57cec5SDimitry Andric 52570b57cec5SDimitry Andric if (auto *C = Entry.second) 52580eae32dcSDimitry Andric return ConstantAddress( 52590eae32dcSDimitry Andric C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 52600b57cec5SDimitry Andric 52610b57cec5SDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 52620b57cec5SDimitry Andric llvm::Constant *Zeros[] = { Zero, Zero }; 52630b57cec5SDimitry Andric 52640b57cec5SDimitry Andric const ASTContext &Context = getContext(); 52650b57cec5SDimitry Andric const llvm::Triple &Triple = getTriple(); 52660b57cec5SDimitry Andric 52670b57cec5SDimitry Andric const auto CFRuntime = getLangOpts().CFRuntime; 52680b57cec5SDimitry Andric const bool IsSwiftABI = 52690b57cec5SDimitry Andric static_cast<unsigned>(CFRuntime) >= 52700b57cec5SDimitry Andric static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 52710b57cec5SDimitry Andric const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 52720b57cec5SDimitry Andric 52730b57cec5SDimitry Andric // If we don't already have it, get __CFConstantStringClassReference. 52740b57cec5SDimitry Andric if (!CFConstantStringClassRef) { 52750b57cec5SDimitry Andric const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 52760b57cec5SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 52770b57cec5SDimitry Andric Ty = llvm::ArrayType::get(Ty, 0); 52780b57cec5SDimitry Andric 52790b57cec5SDimitry Andric switch (CFRuntime) { 52800b57cec5SDimitry Andric default: break; 52810b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 52820b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift5_0: 52830b57cec5SDimitry Andric CFConstantStringClassName = 52840b57cec5SDimitry Andric Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 52850b57cec5SDimitry Andric : "$s10Foundation19_NSCFConstantStringCN"; 52860b57cec5SDimitry Andric Ty = IntPtrTy; 52870b57cec5SDimitry Andric break; 52880b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_2: 52890b57cec5SDimitry Andric CFConstantStringClassName = 52900b57cec5SDimitry Andric Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 52910b57cec5SDimitry Andric : "$S10Foundation19_NSCFConstantStringCN"; 52920b57cec5SDimitry Andric Ty = IntPtrTy; 52930b57cec5SDimitry Andric break; 52940b57cec5SDimitry Andric case LangOptions::CoreFoundationABI::Swift4_1: 52950b57cec5SDimitry Andric CFConstantStringClassName = 52960b57cec5SDimitry Andric Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 52970b57cec5SDimitry Andric : "__T010Foundation19_NSCFConstantStringCN"; 52980b57cec5SDimitry Andric Ty = IntPtrTy; 52990b57cec5SDimitry Andric break; 53000b57cec5SDimitry Andric } 53010b57cec5SDimitry Andric 53020b57cec5SDimitry Andric llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 53030b57cec5SDimitry Andric 53040b57cec5SDimitry Andric if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 53050b57cec5SDimitry Andric llvm::GlobalValue *GV = nullptr; 53060b57cec5SDimitry Andric 53070b57cec5SDimitry Andric if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 53080b57cec5SDimitry Andric IdentifierInfo &II = Context.Idents.get(GV->getName()); 53090b57cec5SDimitry Andric TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 53100b57cec5SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 53110b57cec5SDimitry Andric 53120b57cec5SDimitry Andric const VarDecl *VD = nullptr; 5313fe6060f1SDimitry Andric for (const auto *Result : DC->lookup(&II)) 53140b57cec5SDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 53150b57cec5SDimitry Andric break; 53160b57cec5SDimitry Andric 53170b57cec5SDimitry Andric if (Triple.isOSBinFormatELF()) { 53180b57cec5SDimitry Andric if (!VD) 53190b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 53200b57cec5SDimitry Andric } else { 53210b57cec5SDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 53220b57cec5SDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) 53230b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 53240b57cec5SDimitry Andric else 53250b57cec5SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 53260b57cec5SDimitry Andric } 53270b57cec5SDimitry Andric 53280b57cec5SDimitry Andric setDSOLocal(GV); 53290b57cec5SDimitry Andric } 53300b57cec5SDimitry Andric } 53310b57cec5SDimitry Andric 53320b57cec5SDimitry Andric // Decay array -> ptr 53330b57cec5SDimitry Andric CFConstantStringClassRef = 53340b57cec5SDimitry Andric IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 53350b57cec5SDimitry Andric : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 53360b57cec5SDimitry Andric } 53370b57cec5SDimitry Andric 53380b57cec5SDimitry Andric QualType CFTy = Context.getCFConstantStringType(); 53390b57cec5SDimitry Andric 53400b57cec5SDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 53410b57cec5SDimitry Andric 53420b57cec5SDimitry Andric ConstantInitBuilder Builder(*this); 53430b57cec5SDimitry Andric auto Fields = Builder.beginStruct(STy); 53440b57cec5SDimitry Andric 53450b57cec5SDimitry Andric // Class pointer. 53460b57cec5SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 53470b57cec5SDimitry Andric 53480b57cec5SDimitry Andric // Flags. 53490b57cec5SDimitry Andric if (IsSwiftABI) { 53500b57cec5SDimitry Andric Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 53510b57cec5SDimitry Andric Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 53520b57cec5SDimitry Andric } else { 53530b57cec5SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 53540b57cec5SDimitry Andric } 53550b57cec5SDimitry Andric 53560b57cec5SDimitry Andric // String pointer. 53570b57cec5SDimitry Andric llvm::Constant *C = nullptr; 53580b57cec5SDimitry Andric if (isUTF16) { 53590b57cec5SDimitry Andric auto Arr = llvm::makeArrayRef( 53600b57cec5SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 53610b57cec5SDimitry Andric Entry.first().size() / 2); 53620b57cec5SDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 53630b57cec5SDimitry Andric } else { 53640b57cec5SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 53650b57cec5SDimitry Andric } 53660b57cec5SDimitry Andric 53670b57cec5SDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 53680b57cec5SDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 53690b57cec5SDimitry Andric auto *GV = 53700b57cec5SDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 53710b57cec5SDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 53720b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 53730b57cec5SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 53740b57cec5SDimitry Andric // of the string is via this class initializer. 53750b57cec5SDimitry Andric CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 53760b57cec5SDimitry Andric : Context.getTypeAlignInChars(Context.CharTy); 5377a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 53780b57cec5SDimitry Andric 53790b57cec5SDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 53800b57cec5SDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 53810b57cec5SDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 53820b57cec5SDimitry Andric if (Triple.isOSBinFormatMachO()) 53830b57cec5SDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 53840b57cec5SDimitry Andric : "__TEXT,__cstring,cstring_literals"); 53850b57cec5SDimitry Andric // Make sure the literal ends up in .rodata to allow for safe ICF and for 53860b57cec5SDimitry Andric // the static linker to adjust permissions to read-only later on. 53870b57cec5SDimitry Andric else if (Triple.isOSBinFormatELF()) 53880b57cec5SDimitry Andric GV->setSection(".rodata"); 53890b57cec5SDimitry Andric 53900b57cec5SDimitry Andric // String. 53910b57cec5SDimitry Andric llvm::Constant *Str = 53920b57cec5SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 53930b57cec5SDimitry Andric 53940b57cec5SDimitry Andric if (isUTF16) 53950b57cec5SDimitry Andric // Cast the UTF16 string to the correct type. 53960b57cec5SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 53970b57cec5SDimitry Andric Fields.add(Str); 53980b57cec5SDimitry Andric 53990b57cec5SDimitry Andric // String length. 54000b57cec5SDimitry Andric llvm::IntegerType *LengthTy = 54010b57cec5SDimitry Andric llvm::IntegerType::get(getModule().getContext(), 54020b57cec5SDimitry Andric Context.getTargetInfo().getLongWidth()); 54030b57cec5SDimitry Andric if (IsSwiftABI) { 54040b57cec5SDimitry Andric if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 54050b57cec5SDimitry Andric CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 54060b57cec5SDimitry Andric LengthTy = Int32Ty; 54070b57cec5SDimitry Andric else 54080b57cec5SDimitry Andric LengthTy = IntPtrTy; 54090b57cec5SDimitry Andric } 54100b57cec5SDimitry Andric Fields.addInt(LengthTy, StringLength); 54110b57cec5SDimitry Andric 5412a7dea167SDimitry Andric // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5413a7dea167SDimitry Andric // properly aligned on 32-bit platforms. 5414a7dea167SDimitry Andric CharUnits Alignment = 5415a7dea167SDimitry Andric IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 54160b57cec5SDimitry Andric 54170b57cec5SDimitry Andric // The struct. 54180b57cec5SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 54190b57cec5SDimitry Andric /*isConstant=*/false, 54200b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 54210b57cec5SDimitry Andric GV->addAttribute("objc_arc_inert"); 54220b57cec5SDimitry Andric switch (Triple.getObjectFormat()) { 54230b57cec5SDimitry Andric case llvm::Triple::UnknownObjectFormat: 54240b57cec5SDimitry Andric llvm_unreachable("unknown file format"); 5425e8d8bef9SDimitry Andric case llvm::Triple::GOFF: 5426e8d8bef9SDimitry Andric llvm_unreachable("GOFF is not yet implemented"); 54270b57cec5SDimitry Andric case llvm::Triple::XCOFF: 54280b57cec5SDimitry Andric llvm_unreachable("XCOFF is not yet implemented"); 54290b57cec5SDimitry Andric case llvm::Triple::COFF: 54300b57cec5SDimitry Andric case llvm::Triple::ELF: 54310b57cec5SDimitry Andric case llvm::Triple::Wasm: 54320b57cec5SDimitry Andric GV->setSection("cfstring"); 54330b57cec5SDimitry Andric break; 54340b57cec5SDimitry Andric case llvm::Triple::MachO: 54350b57cec5SDimitry Andric GV->setSection("__DATA,__cfstring"); 54360b57cec5SDimitry Andric break; 54370b57cec5SDimitry Andric } 54380b57cec5SDimitry Andric Entry.second = GV; 54390b57cec5SDimitry Andric 54400eae32dcSDimitry Andric return ConstantAddress(GV, GV->getValueType(), Alignment); 54410b57cec5SDimitry Andric } 54420b57cec5SDimitry Andric 54430b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const { 54440b57cec5SDimitry Andric return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 54450b57cec5SDimitry Andric } 54460b57cec5SDimitry Andric 54470b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 54480b57cec5SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 54490b57cec5SDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 54500b57cec5SDimitry Andric D->startDefinition(); 54510b57cec5SDimitry Andric 54520b57cec5SDimitry Andric QualType FieldTypes[] = { 54530b57cec5SDimitry Andric Context.UnsignedLongTy, 54540b57cec5SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 54550b57cec5SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 54560b57cec5SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 5457a7dea167SDimitry Andric llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 54580b57cec5SDimitry Andric }; 54590b57cec5SDimitry Andric 54600b57cec5SDimitry Andric for (size_t i = 0; i < 4; ++i) { 54610b57cec5SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 54620b57cec5SDimitry Andric D, 54630b57cec5SDimitry Andric SourceLocation(), 54640b57cec5SDimitry Andric SourceLocation(), nullptr, 54650b57cec5SDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 54660b57cec5SDimitry Andric /*BitWidth=*/nullptr, 54670b57cec5SDimitry Andric /*Mutable=*/false, 54680b57cec5SDimitry Andric ICIS_NoInit); 54690b57cec5SDimitry Andric Field->setAccess(AS_public); 54700b57cec5SDimitry Andric D->addDecl(Field); 54710b57cec5SDimitry Andric } 54720b57cec5SDimitry Andric 54730b57cec5SDimitry Andric D->completeDefinition(); 54740b57cec5SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 54750b57cec5SDimitry Andric } 54760b57cec5SDimitry Andric 54770b57cec5SDimitry Andric return ObjCFastEnumerationStateType; 54780b57cec5SDimitry Andric } 54790b57cec5SDimitry Andric 54800b57cec5SDimitry Andric llvm::Constant * 54810b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 54820b57cec5SDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 54830b57cec5SDimitry Andric 54840b57cec5SDimitry Andric // Don't emit it as the address of the string, emit the string data itself 54850b57cec5SDimitry Andric // as an inline array. 54860b57cec5SDimitry Andric if (E->getCharByteWidth() == 1) { 54870b57cec5SDimitry Andric SmallString<64> Str(E->getString()); 54880b57cec5SDimitry Andric 54890b57cec5SDimitry Andric // Resize the string to the right size, which is indicated by its type. 54900b57cec5SDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 54910b57cec5SDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 54920b57cec5SDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 54930b57cec5SDimitry Andric } 54940b57cec5SDimitry Andric 54950b57cec5SDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 54960b57cec5SDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 54970b57cec5SDimitry Andric unsigned NumElements = AType->getNumElements(); 54980b57cec5SDimitry Andric 54990b57cec5SDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 55000b57cec5SDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 55010b57cec5SDimitry Andric SmallVector<uint16_t, 32> Elements; 55020b57cec5SDimitry Andric Elements.reserve(NumElements); 55030b57cec5SDimitry Andric 55040b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 55050b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 55060b57cec5SDimitry Andric Elements.resize(NumElements); 55070b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 55080b57cec5SDimitry Andric } 55090b57cec5SDimitry Andric 55100b57cec5SDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 55110b57cec5SDimitry Andric SmallVector<uint32_t, 32> Elements; 55120b57cec5SDimitry Andric Elements.reserve(NumElements); 55130b57cec5SDimitry Andric 55140b57cec5SDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 55150b57cec5SDimitry Andric Elements.push_back(E->getCodeUnit(i)); 55160b57cec5SDimitry Andric Elements.resize(NumElements); 55170b57cec5SDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 55180b57cec5SDimitry Andric } 55190b57cec5SDimitry Andric 55200b57cec5SDimitry Andric static llvm::GlobalVariable * 55210b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 55220b57cec5SDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 55230b57cec5SDimitry Andric CharUnits Alignment) { 55240b57cec5SDimitry Andric unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5525fe6060f1SDimitry Andric CGM.GetGlobalConstantAddressSpace()); 55260b57cec5SDimitry Andric 55270b57cec5SDimitry Andric llvm::Module &M = CGM.getModule(); 55280b57cec5SDimitry Andric // Create a global variable for this string 55290b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 55300b57cec5SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 55310b57cec5SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5532a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 55330b57cec5SDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 55340b57cec5SDimitry Andric if (GV->isWeakForLinker()) { 55350b57cec5SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 55360b57cec5SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 55370b57cec5SDimitry Andric } 55380b57cec5SDimitry Andric CGM.setDSOLocal(GV); 55390b57cec5SDimitry Andric 55400b57cec5SDimitry Andric return GV; 55410b57cec5SDimitry Andric } 55420b57cec5SDimitry Andric 55430b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 55440b57cec5SDimitry Andric /// constant array for the given string literal. 55450b57cec5SDimitry Andric ConstantAddress 55460b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 55470b57cec5SDimitry Andric StringRef Name) { 55480b57cec5SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 55490b57cec5SDimitry Andric 55500b57cec5SDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 55510b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 55520b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 55530b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 55540b57cec5SDimitry Andric if (auto GV = *Entry) { 5555349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5556a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 55570b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 55580eae32dcSDimitry Andric GV->getValueType(), Alignment); 55590b57cec5SDimitry Andric } 55600b57cec5SDimitry Andric } 55610b57cec5SDimitry Andric 55620b57cec5SDimitry Andric SmallString<256> MangledNameBuffer; 55630b57cec5SDimitry Andric StringRef GlobalVariableName; 55640b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes LT; 55650b57cec5SDimitry Andric 55660b57cec5SDimitry Andric // Mangle the string literal if that's how the ABI merges duplicate strings. 55670b57cec5SDimitry Andric // Don't do it if they are writable, since we don't want writes in one TU to 55680b57cec5SDimitry Andric // affect strings in another. 55690b57cec5SDimitry Andric if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 55700b57cec5SDimitry Andric !LangOpts.WritableStrings) { 55710b57cec5SDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 55720b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 55730b57cec5SDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 55740b57cec5SDimitry Andric GlobalVariableName = MangledNameBuffer; 55750b57cec5SDimitry Andric } else { 55760b57cec5SDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 55770b57cec5SDimitry Andric GlobalVariableName = Name; 55780b57cec5SDimitry Andric } 55790b57cec5SDimitry Andric 55800b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 55810b57cec5SDimitry Andric if (Entry) 55820b57cec5SDimitry Andric *Entry = GV; 55830b57cec5SDimitry Andric 55840b57cec5SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 55850b57cec5SDimitry Andric QualType()); 55860b57cec5SDimitry Andric 55870b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 55880eae32dcSDimitry Andric GV->getValueType(), Alignment); 55890b57cec5SDimitry Andric } 55900b57cec5SDimitry Andric 55910b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 55920b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node. 55930b57cec5SDimitry Andric ConstantAddress 55940b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 55950b57cec5SDimitry Andric std::string Str; 55960b57cec5SDimitry Andric getContext().getObjCEncodingForType(E->getEncodedType(), Str); 55970b57cec5SDimitry Andric 55980b57cec5SDimitry Andric return GetAddrOfConstantCString(Str); 55990b57cec5SDimitry Andric } 56000b57cec5SDimitry Andric 56010b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 56020b57cec5SDimitry Andric /// the literal and a terminating '\0' character. 56030b57cec5SDimitry Andric /// The result has pointer to array type. 56040b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 56050b57cec5SDimitry Andric const std::string &Str, const char *GlobalName) { 56060b57cec5SDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 56070b57cec5SDimitry Andric CharUnits Alignment = 56080b57cec5SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 56090b57cec5SDimitry Andric 56100b57cec5SDimitry Andric llvm::Constant *C = 56110b57cec5SDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 56120b57cec5SDimitry Andric 56130b57cec5SDimitry Andric // Don't share any string literals if strings aren't constant. 56140b57cec5SDimitry Andric llvm::GlobalVariable **Entry = nullptr; 56150b57cec5SDimitry Andric if (!LangOpts.WritableStrings) { 56160b57cec5SDimitry Andric Entry = &ConstantStringMap[C]; 56170b57cec5SDimitry Andric if (auto GV = *Entry) { 5618349cc55cSDimitry Andric if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5619a7dea167SDimitry Andric GV->setAlignment(Alignment.getAsAlign()); 56200b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 56210eae32dcSDimitry Andric GV->getValueType(), Alignment); 56220b57cec5SDimitry Andric } 56230b57cec5SDimitry Andric } 56240b57cec5SDimitry Andric 56250b57cec5SDimitry Andric // Get the default prefix if a name wasn't specified. 56260b57cec5SDimitry Andric if (!GlobalName) 56270b57cec5SDimitry Andric GlobalName = ".str"; 56280b57cec5SDimitry Andric // Create a global variable for this. 56290b57cec5SDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 56300b57cec5SDimitry Andric GlobalName, Alignment); 56310b57cec5SDimitry Andric if (Entry) 56320b57cec5SDimitry Andric *Entry = GV; 56330b57cec5SDimitry Andric 56340b57cec5SDimitry Andric return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 56350eae32dcSDimitry Andric GV->getValueType(), Alignment); 56360b57cec5SDimitry Andric } 56370b57cec5SDimitry Andric 56380b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 56390b57cec5SDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 56400b57cec5SDimitry Andric assert((E->getStorageDuration() == SD_Static || 56410b57cec5SDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 56420b57cec5SDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 56430b57cec5SDimitry Andric 56440b57cec5SDimitry Andric // If we're not materializing a subobject of the temporary, keep the 56450b57cec5SDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 56460b57cec5SDimitry Andric QualType MaterializedType = Init->getType(); 5647480093f4SDimitry Andric if (Init == E->getSubExpr()) 56480b57cec5SDimitry Andric MaterializedType = E->getType(); 56490b57cec5SDimitry Andric 56500b57cec5SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 56510b57cec5SDimitry Andric 5652fe6060f1SDimitry Andric auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5653fe6060f1SDimitry Andric if (!InsertResult.second) { 5654fe6060f1SDimitry Andric // We've seen this before: either we already created it or we're in the 5655fe6060f1SDimitry Andric // process of doing so. 5656fe6060f1SDimitry Andric if (!InsertResult.first->second) { 5657fe6060f1SDimitry Andric // We recursively re-entered this function, probably during emission of 5658fe6060f1SDimitry Andric // the initializer. Create a placeholder. We'll clean this up in the 5659fe6060f1SDimitry Andric // outer call, at the end of this function. 5660fe6060f1SDimitry Andric llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5661fe6060f1SDimitry Andric InsertResult.first->second = new llvm::GlobalVariable( 5662fe6060f1SDimitry Andric getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5663fe6060f1SDimitry Andric nullptr); 5664fe6060f1SDimitry Andric } 56650eae32dcSDimitry Andric return ConstantAddress( 56660eae32dcSDimitry Andric InsertResult.first->second, 56670eae32dcSDimitry Andric InsertResult.first->second->getType()->getPointerElementType(), Align); 5668fe6060f1SDimitry Andric } 56690b57cec5SDimitry Andric 56700b57cec5SDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 56710b57cec5SDimitry Andric // we need to give each temporary the same name in every translation unit (and 56720b57cec5SDimitry Andric // we also need to make the temporaries externally-visible). 56730b57cec5SDimitry Andric SmallString<256> Name; 56740b57cec5SDimitry Andric llvm::raw_svector_ostream Out(Name); 56750b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 56760b57cec5SDimitry Andric VD, E->getManglingNumber(), Out); 56770b57cec5SDimitry Andric 56780b57cec5SDimitry Andric APValue *Value = nullptr; 5679a7dea167SDimitry Andric if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5680a7dea167SDimitry Andric // If the initializer of the extending declaration is a constant 5681a7dea167SDimitry Andric // initializer, we should have a cached constant initializer for this 5682a7dea167SDimitry Andric // temporary. Note that this might have a different value from the value 5683a7dea167SDimitry Andric // computed by evaluating the initializer if the surrounding constant 5684a7dea167SDimitry Andric // expression modifies the temporary. 5685480093f4SDimitry Andric Value = E->getOrCreateValue(false); 56860b57cec5SDimitry Andric } 56870b57cec5SDimitry Andric 56880b57cec5SDimitry Andric // Try evaluating it now, it might have a constant initializer. 56890b57cec5SDimitry Andric Expr::EvalResult EvalResult; 56900b57cec5SDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 56910b57cec5SDimitry Andric !EvalResult.hasSideEffects()) 56920b57cec5SDimitry Andric Value = &EvalResult.Val; 56930b57cec5SDimitry Andric 56940b57cec5SDimitry Andric LangAS AddrSpace = 56950b57cec5SDimitry Andric VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 56960b57cec5SDimitry Andric 56970b57cec5SDimitry Andric Optional<ConstantEmitter> emitter; 56980b57cec5SDimitry Andric llvm::Constant *InitialValue = nullptr; 56990b57cec5SDimitry Andric bool Constant = false; 57000b57cec5SDimitry Andric llvm::Type *Type; 57010b57cec5SDimitry Andric if (Value) { 57020b57cec5SDimitry Andric // The temporary has a constant initializer, use it. 57030b57cec5SDimitry Andric emitter.emplace(*this); 57040b57cec5SDimitry Andric InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 57050b57cec5SDimitry Andric MaterializedType); 57060b57cec5SDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 57070b57cec5SDimitry Andric Type = InitialValue->getType(); 57080b57cec5SDimitry Andric } else { 57090b57cec5SDimitry Andric // No initializer, the initialization will be provided when we 57100b57cec5SDimitry Andric // initialize the declaration which performed lifetime extension. 57110b57cec5SDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 57120b57cec5SDimitry Andric } 57130b57cec5SDimitry Andric 57140b57cec5SDimitry Andric // Create a global variable for this lifetime-extended temporary. 57150b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 57160b57cec5SDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 57170b57cec5SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 57180b57cec5SDimitry Andric const VarDecl *InitVD; 57190b57cec5SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 57200b57cec5SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 57210b57cec5SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 57220b57cec5SDimitry Andric // class can be defined in multiple translation units. 57230b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 57240b57cec5SDimitry Andric } else { 57250b57cec5SDimitry Andric // There is no need for this temporary to have external linkage if the 57260b57cec5SDimitry Andric // VarDecl has external linkage. 57270b57cec5SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 57280b57cec5SDimitry Andric } 57290b57cec5SDimitry Andric } 57300b57cec5SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 57310b57cec5SDimitry Andric auto *GV = new llvm::GlobalVariable( 57320b57cec5SDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 57330b57cec5SDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 57340b57cec5SDimitry Andric if (emitter) emitter->finalize(GV); 57350b57cec5SDimitry Andric setGVProperties(GV, VD); 5736a7dea167SDimitry Andric GV->setAlignment(Align.getAsAlign()); 57370b57cec5SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 57380b57cec5SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 57390b57cec5SDimitry Andric if (VD->getTLSKind()) 57400b57cec5SDimitry Andric setTLSMode(GV, *VD); 57410b57cec5SDimitry Andric llvm::Constant *CV = GV; 57420b57cec5SDimitry Andric if (AddrSpace != LangAS::Default) 57430b57cec5SDimitry Andric CV = getTargetCodeGenInfo().performAddrSpaceCast( 57440b57cec5SDimitry Andric *this, GV, AddrSpace, LangAS::Default, 57450b57cec5SDimitry Andric Type->getPointerTo( 57460b57cec5SDimitry Andric getContext().getTargetAddressSpace(LangAS::Default))); 5747fe6060f1SDimitry Andric 5748fe6060f1SDimitry Andric // Update the map with the new temporary. If we created a placeholder above, 5749fe6060f1SDimitry Andric // replace it with the new global now. 5750fe6060f1SDimitry Andric llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 5751fe6060f1SDimitry Andric if (Entry) { 5752fe6060f1SDimitry Andric Entry->replaceAllUsesWith( 5753fe6060f1SDimitry Andric llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 5754fe6060f1SDimitry Andric llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 5755fe6060f1SDimitry Andric } 5756fe6060f1SDimitry Andric Entry = CV; 5757fe6060f1SDimitry Andric 57580eae32dcSDimitry Andric return ConstantAddress(CV, Type, Align); 57590b57cec5SDimitry Andric } 57600b57cec5SDimitry Andric 57610b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized 57620b57cec5SDimitry Andric /// properties for an implementation. 57630b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const 57640b57cec5SDimitry Andric ObjCImplementationDecl *D) { 57650b57cec5SDimitry Andric for (const auto *PID : D->property_impls()) { 57660b57cec5SDimitry Andric // Dynamic is just for type-checking. 57670b57cec5SDimitry Andric if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 57680b57cec5SDimitry Andric ObjCPropertyDecl *PD = PID->getPropertyDecl(); 57690b57cec5SDimitry Andric 57700b57cec5SDimitry Andric // Determine which methods need to be implemented, some may have 57710b57cec5SDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 57720b57cec5SDimitry Andric // we want, that just indicates if the decl came from a 57730b57cec5SDimitry Andric // property. What we want to know is if the method is defined in 57740b57cec5SDimitry Andric // this implementation. 5775480093f4SDimitry Andric auto *Getter = PID->getGetterMethodDecl(); 5776480093f4SDimitry Andric if (!Getter || Getter->isSynthesizedAccessorStub()) 57770b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCGetter( 57780b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 5779480093f4SDimitry Andric auto *Setter = PID->getSetterMethodDecl(); 5780480093f4SDimitry Andric if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 57810b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCSetter( 57820b57cec5SDimitry Andric const_cast<ObjCImplementationDecl *>(D), PID); 57830b57cec5SDimitry Andric } 57840b57cec5SDimitry Andric } 57850b57cec5SDimitry Andric } 57860b57cec5SDimitry Andric 57870b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 57880b57cec5SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 57890b57cec5SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 57900b57cec5SDimitry Andric ivar; ivar = ivar->getNextIvar()) 57910b57cec5SDimitry Andric if (ivar->getType().isDestructedType()) 57920b57cec5SDimitry Andric return true; 57930b57cec5SDimitry Andric 57940b57cec5SDimitry Andric return false; 57950b57cec5SDimitry Andric } 57960b57cec5SDimitry Andric 57970b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 57980b57cec5SDimitry Andric ObjCImplementationDecl *D) { 57990b57cec5SDimitry Andric CodeGenFunction CGF(CGM); 58000b57cec5SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 58010b57cec5SDimitry Andric E = D->init_end(); B != E; ++B) { 58020b57cec5SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 58030b57cec5SDimitry Andric Expr *Init = CtorInitExp->getInit(); 58040b57cec5SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 58050b57cec5SDimitry Andric return false; 58060b57cec5SDimitry Andric } 58070b57cec5SDimitry Andric return true; 58080b57cec5SDimitry Andric } 58090b57cec5SDimitry Andric 58100b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization 58110b57cec5SDimitry Andric /// for an implementation. 58120b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 58130b57cec5SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 58140b57cec5SDimitry Andric if (needsDestructMethod(D)) { 58150b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 58160b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5817480093f4SDimitry Andric ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5818480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5819480093f4SDimitry Andric getContext().VoidTy, nullptr, D, 58200b57cec5SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 5821480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5822480093f4SDimitry Andric /*isImplicitlyDeclared=*/true, 58230b57cec5SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 58240b57cec5SDimitry Andric D->addInstanceMethod(DTORMethod); 58250b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 58260b57cec5SDimitry Andric D->setHasDestructors(true); 58270b57cec5SDimitry Andric } 58280b57cec5SDimitry Andric 58290b57cec5SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 58300b57cec5SDimitry Andric // a .cxx_construct. 58310b57cec5SDimitry Andric if (D->getNumIvarInitializers() == 0 || 58320b57cec5SDimitry Andric AllTrivialInitializers(*this, D)) 58330b57cec5SDimitry Andric return; 58340b57cec5SDimitry Andric 58350b57cec5SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 58360b57cec5SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 58370b57cec5SDimitry Andric // The constructor returns 'self'. 5838480093f4SDimitry Andric ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5839480093f4SDimitry Andric getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5840480093f4SDimitry Andric getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 58410b57cec5SDimitry Andric /*isVariadic=*/false, 5842480093f4SDimitry Andric /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 58430b57cec5SDimitry Andric /*isImplicitlyDeclared=*/true, 5844480093f4SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 58450b57cec5SDimitry Andric D->addInstanceMethod(CTORMethod); 58460b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 58470b57cec5SDimitry Andric D->setHasNonZeroConstructors(true); 58480b57cec5SDimitry Andric } 58490b57cec5SDimitry Andric 58500b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec. 58510b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 58520b57cec5SDimitry Andric if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5853480093f4SDimitry Andric LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 58540b57cec5SDimitry Andric ErrorUnsupported(LSD, "linkage spec"); 58550b57cec5SDimitry Andric return; 58560b57cec5SDimitry Andric } 58570b57cec5SDimitry Andric 58580b57cec5SDimitry Andric EmitDeclContext(LSD); 58590b57cec5SDimitry Andric } 58600b57cec5SDimitry Andric 58610b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 58620b57cec5SDimitry Andric for (auto *I : DC->decls()) { 58630b57cec5SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 58640b57cec5SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 58650b57cec5SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 58660b57cec5SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 58670b57cec5SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 58680b57cec5SDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 58690b57cec5SDimitry Andric for (auto *M : OID->methods()) 58700b57cec5SDimitry Andric EmitTopLevelDecl(M); 58710b57cec5SDimitry Andric } 58720b57cec5SDimitry Andric 58730b57cec5SDimitry Andric EmitTopLevelDecl(I); 58740b57cec5SDimitry Andric } 58750b57cec5SDimitry Andric } 58760b57cec5SDimitry Andric 58770b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration. 58780b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) { 58790b57cec5SDimitry Andric // Ignore dependent declarations. 58800b57cec5SDimitry Andric if (D->isTemplated()) 58810b57cec5SDimitry Andric return; 58820b57cec5SDimitry Andric 58835ffd83dbSDimitry Andric // Consteval function shouldn't be emitted. 58845ffd83dbSDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 58855ffd83dbSDimitry Andric if (FD->isConsteval()) 58865ffd83dbSDimitry Andric return; 58875ffd83dbSDimitry Andric 58880b57cec5SDimitry Andric switch (D->getKind()) { 58890b57cec5SDimitry Andric case Decl::CXXConversion: 58900b57cec5SDimitry Andric case Decl::CXXMethod: 58910b57cec5SDimitry Andric case Decl::Function: 58920b57cec5SDimitry Andric EmitGlobal(cast<FunctionDecl>(D)); 58930b57cec5SDimitry Andric // Always provide some coverage mapping 58940b57cec5SDimitry Andric // even for the functions that aren't emitted. 58950b57cec5SDimitry Andric AddDeferredUnusedCoverageMapping(D); 58960b57cec5SDimitry Andric break; 58970b57cec5SDimitry Andric 58980b57cec5SDimitry Andric case Decl::CXXDeductionGuide: 58990b57cec5SDimitry Andric // Function-like, but does not result in code emission. 59000b57cec5SDimitry Andric break; 59010b57cec5SDimitry Andric 59020b57cec5SDimitry Andric case Decl::Var: 59030b57cec5SDimitry Andric case Decl::Decomposition: 59040b57cec5SDimitry Andric case Decl::VarTemplateSpecialization: 59050b57cec5SDimitry Andric EmitGlobal(cast<VarDecl>(D)); 59060b57cec5SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 59070b57cec5SDimitry Andric for (auto *B : DD->bindings()) 59080b57cec5SDimitry Andric if (auto *HD = B->getHoldingVar()) 59090b57cec5SDimitry Andric EmitGlobal(HD); 59100b57cec5SDimitry Andric break; 59110b57cec5SDimitry Andric 59120b57cec5SDimitry Andric // Indirect fields from global anonymous structs and unions can be 59130b57cec5SDimitry Andric // ignored; only the actual variable requires IR gen support. 59140b57cec5SDimitry Andric case Decl::IndirectField: 59150b57cec5SDimitry Andric break; 59160b57cec5SDimitry Andric 59170b57cec5SDimitry Andric // C++ Decls 59180b57cec5SDimitry Andric case Decl::Namespace: 59190b57cec5SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 59200b57cec5SDimitry Andric break; 59210b57cec5SDimitry Andric case Decl::ClassTemplateSpecialization: { 59220b57cec5SDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 59235ffd83dbSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 59245ffd83dbSDimitry Andric if (Spec->getSpecializationKind() == 59255ffd83dbSDimitry Andric TSK_ExplicitInstantiationDefinition && 59260b57cec5SDimitry Andric Spec->hasDefinition()) 59275ffd83dbSDimitry Andric DI->completeTemplateDefinition(*Spec); 59280b57cec5SDimitry Andric } LLVM_FALLTHROUGH; 5929e8d8bef9SDimitry Andric case Decl::CXXRecord: { 5930e8d8bef9SDimitry Andric CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 5931e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) { 5932e8d8bef9SDimitry Andric if (CRD->hasDefinition()) 5933e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 59340b57cec5SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 59350b57cec5SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5936e8d8bef9SDimitry Andric DI->completeUnusedClass(*CRD); 5937e8d8bef9SDimitry Andric } 59380b57cec5SDimitry Andric // Emit any static data members, they may be definitions. 5939e8d8bef9SDimitry Andric for (auto *I : CRD->decls()) 59400b57cec5SDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 59410b57cec5SDimitry Andric EmitTopLevelDecl(I); 59420b57cec5SDimitry Andric break; 5943e8d8bef9SDimitry Andric } 59440b57cec5SDimitry Andric // No code generation needed. 59450b57cec5SDimitry Andric case Decl::UsingShadow: 59460b57cec5SDimitry Andric case Decl::ClassTemplate: 59470b57cec5SDimitry Andric case Decl::VarTemplate: 59480b57cec5SDimitry Andric case Decl::Concept: 59490b57cec5SDimitry Andric case Decl::VarTemplatePartialSpecialization: 59500b57cec5SDimitry Andric case Decl::FunctionTemplate: 59510b57cec5SDimitry Andric case Decl::TypeAliasTemplate: 59520b57cec5SDimitry Andric case Decl::Block: 59530b57cec5SDimitry Andric case Decl::Empty: 59540b57cec5SDimitry Andric case Decl::Binding: 59550b57cec5SDimitry Andric break; 59560b57cec5SDimitry Andric case Decl::Using: // using X; [C++] 59570b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 59580b57cec5SDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 59595ffd83dbSDimitry Andric break; 5960fe6060f1SDimitry Andric case Decl::UsingEnum: // using enum X; [C++] 5961fe6060f1SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 5962fe6060f1SDimitry Andric DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 5963fe6060f1SDimitry Andric break; 59640b57cec5SDimitry Andric case Decl::NamespaceAlias: 59650b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 59660b57cec5SDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 59675ffd83dbSDimitry Andric break; 59680b57cec5SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 59690b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 59700b57cec5SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 59715ffd83dbSDimitry Andric break; 59720b57cec5SDimitry Andric case Decl::CXXConstructor: 59730b57cec5SDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 59740b57cec5SDimitry Andric break; 59750b57cec5SDimitry Andric case Decl::CXXDestructor: 59760b57cec5SDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 59770b57cec5SDimitry Andric break; 59780b57cec5SDimitry Andric 59790b57cec5SDimitry Andric case Decl::StaticAssert: 59800b57cec5SDimitry Andric // Nothing to do. 59810b57cec5SDimitry Andric break; 59820b57cec5SDimitry Andric 59830b57cec5SDimitry Andric // Objective-C Decls 59840b57cec5SDimitry Andric 59850b57cec5SDimitry Andric // Forward declarations, no (immediate) code generation. 59860b57cec5SDimitry Andric case Decl::ObjCInterface: 59870b57cec5SDimitry Andric case Decl::ObjCCategory: 59880b57cec5SDimitry Andric break; 59890b57cec5SDimitry Andric 59900b57cec5SDimitry Andric case Decl::ObjCProtocol: { 59910b57cec5SDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 59920b57cec5SDimitry Andric if (Proto->isThisDeclarationADefinition()) 59930b57cec5SDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 59940b57cec5SDimitry Andric break; 59950b57cec5SDimitry Andric } 59960b57cec5SDimitry Andric 59970b57cec5SDimitry Andric case Decl::ObjCCategoryImpl: 59980b57cec5SDimitry Andric // Categories have properties but don't support synthesize so we 59990b57cec5SDimitry Andric // can ignore them here. 60000b57cec5SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 60010b57cec5SDimitry Andric break; 60020b57cec5SDimitry Andric 60030b57cec5SDimitry Andric case Decl::ObjCImplementation: { 60040b57cec5SDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 60050b57cec5SDimitry Andric EmitObjCPropertyImplementations(OMD); 60060b57cec5SDimitry Andric EmitObjCIvarInitializations(OMD); 60070b57cec5SDimitry Andric ObjCRuntime->GenerateClass(OMD); 60080b57cec5SDimitry Andric // Emit global variable debug information. 60090b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6010480093f4SDimitry Andric if (getCodeGenOpts().hasReducedDebugInfo()) 60110b57cec5SDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 60120b57cec5SDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 60130b57cec5SDimitry Andric break; 60140b57cec5SDimitry Andric } 60150b57cec5SDimitry Andric case Decl::ObjCMethod: { 60160b57cec5SDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 60170b57cec5SDimitry Andric // If this is not a prototype, emit the body. 60180b57cec5SDimitry Andric if (OMD->getBody()) 60190b57cec5SDimitry Andric CodeGenFunction(*this).GenerateObjCMethod(OMD); 60200b57cec5SDimitry Andric break; 60210b57cec5SDimitry Andric } 60220b57cec5SDimitry Andric case Decl::ObjCCompatibleAlias: 60230b57cec5SDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 60240b57cec5SDimitry Andric break; 60250b57cec5SDimitry Andric 60260b57cec5SDimitry Andric case Decl::PragmaComment: { 60270b57cec5SDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 60280b57cec5SDimitry Andric switch (PCD->getCommentKind()) { 60290b57cec5SDimitry Andric case PCK_Unknown: 60300b57cec5SDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 60310b57cec5SDimitry Andric case PCK_Linker: 60320b57cec5SDimitry Andric AppendLinkerOptions(PCD->getArg()); 60330b57cec5SDimitry Andric break; 60340b57cec5SDimitry Andric case PCK_Lib: 60350b57cec5SDimitry Andric AddDependentLib(PCD->getArg()); 60360b57cec5SDimitry Andric break; 60370b57cec5SDimitry Andric case PCK_Compiler: 60380b57cec5SDimitry Andric case PCK_ExeStr: 60390b57cec5SDimitry Andric case PCK_User: 60400b57cec5SDimitry Andric break; // We ignore all of these. 60410b57cec5SDimitry Andric } 60420b57cec5SDimitry Andric break; 60430b57cec5SDimitry Andric } 60440b57cec5SDimitry Andric 60450b57cec5SDimitry Andric case Decl::PragmaDetectMismatch: { 60460b57cec5SDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 60470b57cec5SDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 60480b57cec5SDimitry Andric break; 60490b57cec5SDimitry Andric } 60500b57cec5SDimitry Andric 60510b57cec5SDimitry Andric case Decl::LinkageSpec: 60520b57cec5SDimitry Andric EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 60530b57cec5SDimitry Andric break; 60540b57cec5SDimitry Andric 60550b57cec5SDimitry Andric case Decl::FileScopeAsm: { 60560b57cec5SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 60570b57cec5SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 60580b57cec5SDimitry Andric break; 60590b57cec5SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 60600b57cec5SDimitry Andric if (LangOpts.OpenMPIsDevice) 60610b57cec5SDimitry Andric break; 6062fe6060f1SDimitry Andric // File-scope asm is ignored during device-side SYCL compilation. 6063fe6060f1SDimitry Andric if (LangOpts.SYCLIsDevice) 6064fe6060f1SDimitry Andric break; 60650b57cec5SDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 60660b57cec5SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 60670b57cec5SDimitry Andric break; 60680b57cec5SDimitry Andric } 60690b57cec5SDimitry Andric 60700b57cec5SDimitry Andric case Decl::Import: { 60710b57cec5SDimitry Andric auto *Import = cast<ImportDecl>(D); 60720b57cec5SDimitry Andric 60730b57cec5SDimitry Andric // If we've already imported this module, we're done. 60740b57cec5SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 60750b57cec5SDimitry Andric break; 60760b57cec5SDimitry Andric 60770b57cec5SDimitry Andric // Emit debug information for direct imports. 60780b57cec5SDimitry Andric if (!Import->getImportedOwningModule()) { 60790b57cec5SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 60800b57cec5SDimitry Andric DI->EmitImportDecl(*Import); 60810b57cec5SDimitry Andric } 60820b57cec5SDimitry Andric 60830b57cec5SDimitry Andric // Find all of the submodules and emit the module initializers. 60840b57cec5SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 60850b57cec5SDimitry Andric SmallVector<clang::Module *, 16> Stack; 60860b57cec5SDimitry Andric Visited.insert(Import->getImportedModule()); 60870b57cec5SDimitry Andric Stack.push_back(Import->getImportedModule()); 60880b57cec5SDimitry Andric 60890b57cec5SDimitry Andric while (!Stack.empty()) { 60900b57cec5SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 60910b57cec5SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 60920b57cec5SDimitry Andric continue; 60930b57cec5SDimitry Andric 60940b57cec5SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 60950b57cec5SDimitry Andric EmitTopLevelDecl(D); 60960b57cec5SDimitry Andric 60970b57cec5SDimitry Andric // Visit the submodules of this module. 60980b57cec5SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 60990b57cec5SDimitry Andric SubEnd = Mod->submodule_end(); 61000b57cec5SDimitry Andric Sub != SubEnd; ++Sub) { 61010b57cec5SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 61020b57cec5SDimitry Andric // the initializers. 61030b57cec5SDimitry Andric if ((*Sub)->IsExplicit) 61040b57cec5SDimitry Andric continue; 61050b57cec5SDimitry Andric 61060b57cec5SDimitry Andric if (Visited.insert(*Sub).second) 61070b57cec5SDimitry Andric Stack.push_back(*Sub); 61080b57cec5SDimitry Andric } 61090b57cec5SDimitry Andric } 61100b57cec5SDimitry Andric break; 61110b57cec5SDimitry Andric } 61120b57cec5SDimitry Andric 61130b57cec5SDimitry Andric case Decl::Export: 61140b57cec5SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 61150b57cec5SDimitry Andric break; 61160b57cec5SDimitry Andric 61170b57cec5SDimitry Andric case Decl::OMPThreadPrivate: 61180b57cec5SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 61190b57cec5SDimitry Andric break; 61200b57cec5SDimitry Andric 61210b57cec5SDimitry Andric case Decl::OMPAllocate: 6122fe6060f1SDimitry Andric EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 61230b57cec5SDimitry Andric break; 61240b57cec5SDimitry Andric 61250b57cec5SDimitry Andric case Decl::OMPDeclareReduction: 61260b57cec5SDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 61270b57cec5SDimitry Andric break; 61280b57cec5SDimitry Andric 61290b57cec5SDimitry Andric case Decl::OMPDeclareMapper: 61300b57cec5SDimitry Andric EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 61310b57cec5SDimitry Andric break; 61320b57cec5SDimitry Andric 61330b57cec5SDimitry Andric case Decl::OMPRequires: 61340b57cec5SDimitry Andric EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 61350b57cec5SDimitry Andric break; 61360b57cec5SDimitry Andric 6137e8d8bef9SDimitry Andric case Decl::Typedef: 6138e8d8bef9SDimitry Andric case Decl::TypeAlias: // using foo = bar; [C++11] 6139e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6140e8d8bef9SDimitry Andric DI->EmitAndRetainType( 6141e8d8bef9SDimitry Andric getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6142e8d8bef9SDimitry Andric break; 6143e8d8bef9SDimitry Andric 6144e8d8bef9SDimitry Andric case Decl::Record: 6145e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6146e8d8bef9SDimitry Andric if (cast<RecordDecl>(D)->getDefinition()) 6147e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6148e8d8bef9SDimitry Andric break; 6149e8d8bef9SDimitry Andric 6150e8d8bef9SDimitry Andric case Decl::Enum: 6151e8d8bef9SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 6152e8d8bef9SDimitry Andric if (cast<EnumDecl>(D)->getDefinition()) 6153e8d8bef9SDimitry Andric DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6154e8d8bef9SDimitry Andric break; 6155e8d8bef9SDimitry Andric 61560b57cec5SDimitry Andric default: 61570b57cec5SDimitry Andric // Make sure we handled everything we should, every other kind is a 61580b57cec5SDimitry Andric // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 61590b57cec5SDimitry Andric // function. Need to recode Decl::Kind to do that easily. 61600b57cec5SDimitry Andric assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 61610b57cec5SDimitry Andric break; 61620b57cec5SDimitry Andric } 61630b57cec5SDimitry Andric } 61640b57cec5SDimitry Andric 61650b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 61660b57cec5SDimitry Andric // Do we need to generate coverage mapping? 61670b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 61680b57cec5SDimitry Andric return; 61690b57cec5SDimitry Andric switch (D->getKind()) { 61700b57cec5SDimitry Andric case Decl::CXXConversion: 61710b57cec5SDimitry Andric case Decl::CXXMethod: 61720b57cec5SDimitry Andric case Decl::Function: 61730b57cec5SDimitry Andric case Decl::ObjCMethod: 61740b57cec5SDimitry Andric case Decl::CXXConstructor: 61750b57cec5SDimitry Andric case Decl::CXXDestructor: { 61760b57cec5SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 61775ffd83dbSDimitry Andric break; 61780b57cec5SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 61790b57cec5SDimitry Andric if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 61805ffd83dbSDimitry Andric break; 61810b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 61820b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 61830b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 61840b57cec5SDimitry Andric break; 61850b57cec5SDimitry Andric } 61860b57cec5SDimitry Andric default: 61870b57cec5SDimitry Andric break; 61880b57cec5SDimitry Andric }; 61890b57cec5SDimitry Andric } 61900b57cec5SDimitry Andric 61910b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 61920b57cec5SDimitry Andric // Do we need to generate coverage mapping? 61930b57cec5SDimitry Andric if (!CodeGenOpts.CoverageMapping) 61940b57cec5SDimitry Andric return; 61950b57cec5SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 61960b57cec5SDimitry Andric if (Fn->isTemplateInstantiation()) 61970b57cec5SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 61980b57cec5SDimitry Andric } 61990b57cec5SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 62000b57cec5SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 62010b57cec5SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 62020b57cec5SDimitry Andric else 62030b57cec5SDimitry Andric I->second = false; 62040b57cec5SDimitry Andric } 62050b57cec5SDimitry Andric 62060b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 62070b57cec5SDimitry Andric // We call takeVector() here to avoid use-after-free. 62080b57cec5SDimitry Andric // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 62090b57cec5SDimitry Andric // we deserialize function bodies to emit coverage info for them, and that 62100b57cec5SDimitry Andric // deserializes more declarations. How should we handle that case? 62110b57cec5SDimitry Andric for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 62120b57cec5SDimitry Andric if (!Entry.second) 62130b57cec5SDimitry Andric continue; 62140b57cec5SDimitry Andric const Decl *D = Entry.first; 62150b57cec5SDimitry Andric switch (D->getKind()) { 62160b57cec5SDimitry Andric case Decl::CXXConversion: 62170b57cec5SDimitry Andric case Decl::CXXMethod: 62180b57cec5SDimitry Andric case Decl::Function: 62190b57cec5SDimitry Andric case Decl::ObjCMethod: { 62200b57cec5SDimitry Andric CodeGenPGO PGO(*this); 62210b57cec5SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 62220b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 62230b57cec5SDimitry Andric getFunctionLinkage(GD)); 62240b57cec5SDimitry Andric break; 62250b57cec5SDimitry Andric } 62260b57cec5SDimitry Andric case Decl::CXXConstructor: { 62270b57cec5SDimitry Andric CodeGenPGO PGO(*this); 62280b57cec5SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 62290b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 62300b57cec5SDimitry Andric getFunctionLinkage(GD)); 62310b57cec5SDimitry Andric break; 62320b57cec5SDimitry Andric } 62330b57cec5SDimitry Andric case Decl::CXXDestructor: { 62340b57cec5SDimitry Andric CodeGenPGO PGO(*this); 62350b57cec5SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 62360b57cec5SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 62370b57cec5SDimitry Andric getFunctionLinkage(GD)); 62380b57cec5SDimitry Andric break; 62390b57cec5SDimitry Andric } 62400b57cec5SDimitry Andric default: 62410b57cec5SDimitry Andric break; 62420b57cec5SDimitry Andric }; 62430b57cec5SDimitry Andric } 62440b57cec5SDimitry Andric } 62450b57cec5SDimitry Andric 62465ffd83dbSDimitry Andric void CodeGenModule::EmitMainVoidAlias() { 62475ffd83dbSDimitry Andric // In order to transition away from "__original_main" gracefully, emit an 62485ffd83dbSDimitry Andric // alias for "main" in the no-argument case so that libc can detect when 62495ffd83dbSDimitry Andric // new-style no-argument main is in used. 62505ffd83dbSDimitry Andric if (llvm::Function *F = getModule().getFunction("main")) { 62515ffd83dbSDimitry Andric if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 62525ffd83dbSDimitry Andric F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) 62535ffd83dbSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create("__main_void", F)); 62545ffd83dbSDimitry Andric } 62555ffd83dbSDimitry Andric } 62565ffd83dbSDimitry Andric 62570b57cec5SDimitry Andric /// Turns the given pointer into a constant. 62580b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 62590b57cec5SDimitry Andric const void *Ptr) { 62600b57cec5SDimitry Andric uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 62610b57cec5SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 62620b57cec5SDimitry Andric return llvm::ConstantInt::get(i64, PtrInt); 62630b57cec5SDimitry Andric } 62640b57cec5SDimitry Andric 62650b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 62660b57cec5SDimitry Andric llvm::NamedMDNode *&GlobalMetadata, 62670b57cec5SDimitry Andric GlobalDecl D, 62680b57cec5SDimitry Andric llvm::GlobalValue *Addr) { 62690b57cec5SDimitry Andric if (!GlobalMetadata) 62700b57cec5SDimitry Andric GlobalMetadata = 62710b57cec5SDimitry Andric CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 62720b57cec5SDimitry Andric 62730b57cec5SDimitry Andric // TODO: should we report variant information for ctors/dtors? 62740b57cec5SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 62750b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 62760b57cec5SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 62770b57cec5SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 62780b57cec5SDimitry Andric } 62790b57cec5SDimitry Andric 62800b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked 62810b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 62820b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 62830b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 62840b57cec5SDimitry Andric /// same translation unit. 62850b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 62860b57cec5SDimitry Andric if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 62870b57cec5SDimitry Andric return; 62880b57cec5SDimitry Andric for (auto &I : StaticExternCValues) { 62890b57cec5SDimitry Andric IdentifierInfo *Name = I.first; 62900b57cec5SDimitry Andric llvm::GlobalValue *Val = I.second; 62910b57cec5SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 6292fe6060f1SDimitry Andric addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 62930b57cec5SDimitry Andric } 62940b57cec5SDimitry Andric } 62950b57cec5SDimitry Andric 62960b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 62970b57cec5SDimitry Andric GlobalDecl &Result) const { 62980b57cec5SDimitry Andric auto Res = Manglings.find(MangledName); 62990b57cec5SDimitry Andric if (Res == Manglings.end()) 63000b57cec5SDimitry Andric return false; 63010b57cec5SDimitry Andric Result = Res->getValue(); 63020b57cec5SDimitry Andric return true; 63030b57cec5SDimitry Andric } 63040b57cec5SDimitry Andric 63050b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the 63060b57cec5SDimitry Andric /// current module with the Decls they came from. This is useful for 63070b57cec5SDimitry Andric /// projects using IR gen as a subroutine. 63080b57cec5SDimitry Andric /// 63090b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly 63100b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata 63110b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'. 63120b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() { 63130b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 63140b57cec5SDimitry Andric 63150b57cec5SDimitry Andric for (auto &I : MangledDeclNames) { 63160b57cec5SDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 63170b57cec5SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 63180b57cec5SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 63190b57cec5SDimitry Andric if (Addr) 63200b57cec5SDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 63210b57cec5SDimitry Andric } 63220b57cec5SDimitry Andric } 63230b57cec5SDimitry Andric 63240b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current 63250b57cec5SDimitry Andric /// function. 63260b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() { 63270b57cec5SDimitry Andric if (LocalDeclMap.empty()) return; 63280b57cec5SDimitry Andric 63290b57cec5SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 63300b57cec5SDimitry Andric 63310b57cec5SDimitry Andric // Find the unique metadata ID for this name. 63320b57cec5SDimitry Andric unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 63330b57cec5SDimitry Andric 63340b57cec5SDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 63350b57cec5SDimitry Andric 63360b57cec5SDimitry Andric for (auto &I : LocalDeclMap) { 63370b57cec5SDimitry Andric const Decl *D = I.first; 63380b57cec5SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 63390b57cec5SDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 63400b57cec5SDimitry Andric llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 63410b57cec5SDimitry Andric Alloca->setMetadata( 63420b57cec5SDimitry Andric DeclPtrKind, llvm::MDNode::get( 63430b57cec5SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 63440b57cec5SDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 63450b57cec5SDimitry Andric GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 63460b57cec5SDimitry Andric EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 63470b57cec5SDimitry Andric } 63480b57cec5SDimitry Andric } 63490b57cec5SDimitry Andric } 63500b57cec5SDimitry Andric 63510b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 63520b57cec5SDimitry Andric llvm::NamedMDNode *IdentMetadata = 63530b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 63540b57cec5SDimitry Andric std::string Version = getClangFullVersion(); 63550b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 63560b57cec5SDimitry Andric 63570b57cec5SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 63580b57cec5SDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 63590b57cec5SDimitry Andric } 63600b57cec5SDimitry Andric 63610b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() { 63620b57cec5SDimitry Andric llvm::NamedMDNode *CommandLineMetadata = 63630b57cec5SDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.commandline"); 63640b57cec5SDimitry Andric std::string CommandLine = getCodeGenOpts().RecordCommandLine; 63650b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 63660b57cec5SDimitry Andric 63670b57cec5SDimitry Andric llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 63680b57cec5SDimitry Andric CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 63690b57cec5SDimitry Andric } 63700b57cec5SDimitry Andric 63710b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() { 63720b57cec5SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 63730b57cec5SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 63740b57cec5SDimitry Andric return; 63750b57cec5SDimitry Andric 63760b57cec5SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 63770b57cec5SDimitry Andric if (!CUNode) 63780b57cec5SDimitry Andric return; 63790b57cec5SDimitry Andric 63800b57cec5SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 63810b57cec5SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 63820b57cec5SDimitry Andric auto *CoverageDataFile = 63830b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 63840b57cec5SDimitry Andric auto *CoverageNotesFile = 63850b57cec5SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 63860b57cec5SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 63870b57cec5SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 63880b57cec5SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 63890b57cec5SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 63900b57cec5SDimitry Andric } 63910b57cec5SDimitry Andric } 63920b57cec5SDimitry Andric 63930b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 63940b57cec5SDimitry Andric bool ForEH) { 63950b57cec5SDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 63960b57cec5SDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 63970b57cec5SDimitry Andric // and it's not for EH? 63985ffd83dbSDimitry Andric if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 63995ffd83dbSDimitry Andric (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 64005ffd83dbSDimitry Andric getTriple().isNVPTX())) 64010b57cec5SDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 64020b57cec5SDimitry Andric 64030b57cec5SDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 64040b57cec5SDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 64050b57cec5SDimitry Andric return ObjCRuntime->GetEHType(Ty); 64060b57cec5SDimitry Andric 64070b57cec5SDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 64080b57cec5SDimitry Andric } 64090b57cec5SDimitry Andric 64100b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 64110b57cec5SDimitry Andric // Do not emit threadprivates in simd-only mode. 64120b57cec5SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 64130b57cec5SDimitry Andric return; 64140b57cec5SDimitry Andric for (auto RefExpr : D->varlists()) { 64150b57cec5SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 64160b57cec5SDimitry Andric bool PerformInit = 64170b57cec5SDimitry Andric VD->getAnyInitializer() && 64180b57cec5SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 64190b57cec5SDimitry Andric /*ForRef=*/false); 64200b57cec5SDimitry Andric 64210b57cec5SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 64220b57cec5SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 64230b57cec5SDimitry Andric VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 64240b57cec5SDimitry Andric CXXGlobalInits.push_back(InitFunction); 64250b57cec5SDimitry Andric } 64260b57cec5SDimitry Andric } 64270b57cec5SDimitry Andric 64280b57cec5SDimitry Andric llvm::Metadata * 64290b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 64300b57cec5SDimitry Andric StringRef Suffix) { 64310eae32dcSDimitry Andric if (auto *FnType = T->getAs<FunctionProtoType>()) 64320eae32dcSDimitry Andric T = getContext().getFunctionType( 64330eae32dcSDimitry Andric FnType->getReturnType(), FnType->getParamTypes(), 64340eae32dcSDimitry Andric FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 64350eae32dcSDimitry Andric 64360b57cec5SDimitry Andric llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 64370b57cec5SDimitry Andric if (InternalId) 64380b57cec5SDimitry Andric return InternalId; 64390b57cec5SDimitry Andric 64400b57cec5SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 64410b57cec5SDimitry Andric std::string OutName; 64420b57cec5SDimitry Andric llvm::raw_string_ostream Out(OutName); 64430b57cec5SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 64440b57cec5SDimitry Andric Out << Suffix; 64450b57cec5SDimitry Andric 64460b57cec5SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 64470b57cec5SDimitry Andric } else { 64480b57cec5SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 64490b57cec5SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 64500b57cec5SDimitry Andric } 64510b57cec5SDimitry Andric 64520b57cec5SDimitry Andric return InternalId; 64530b57cec5SDimitry Andric } 64540b57cec5SDimitry Andric 64550b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 64560b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 64570b57cec5SDimitry Andric } 64580b57cec5SDimitry Andric 64590b57cec5SDimitry Andric llvm::Metadata * 64600b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 64610b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 64620b57cec5SDimitry Andric } 64630b57cec5SDimitry Andric 64640b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the 64650b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *' 64660b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to 64670b57cec5SDimitry Andric // 'void *'. 64680b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 64690b57cec5SDimitry Andric if (!Ty->isPointerType()) 64700b57cec5SDimitry Andric return Ty; 64710b57cec5SDimitry Andric 64720b57cec5SDimitry Andric return Ctx.getPointerType( 64730b57cec5SDimitry Andric QualType(Ctx.VoidTy).withCVRQualifiers( 64740b57cec5SDimitry Andric Ty->getPointeeType().getCVRQualifiers())); 64750b57cec5SDimitry Andric } 64760b57cec5SDimitry Andric 64770b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types 64780b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 64790b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 64800b57cec5SDimitry Andric SmallVector<QualType, 8> GeneralizedParams; 64810b57cec5SDimitry Andric for (auto &Param : FnType->param_types()) 64820b57cec5SDimitry Andric GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 64830b57cec5SDimitry Andric 64840b57cec5SDimitry Andric return Ctx.getFunctionType( 64850b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType()), 64860b57cec5SDimitry Andric GeneralizedParams, FnType->getExtProtoInfo()); 64870b57cec5SDimitry Andric } 64880b57cec5SDimitry Andric 64890b57cec5SDimitry Andric if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 64900b57cec5SDimitry Andric return Ctx.getFunctionNoProtoType( 64910b57cec5SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType())); 64920b57cec5SDimitry Andric 64930b57cec5SDimitry Andric llvm_unreachable("Encountered unknown FunctionType"); 64940b57cec5SDimitry Andric } 64950b57cec5SDimitry Andric 64960b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 64970b57cec5SDimitry Andric return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 64980b57cec5SDimitry Andric GeneralizedMetadataIdMap, ".generalized"); 64990b57cec5SDimitry Andric } 65000b57cec5SDimitry Andric 65010b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 65020b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 65030b57cec5SDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 65040b57cec5SDimitry Andric // is not in the trapping mode. 65050b57cec5SDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 65060b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 65070b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 65080b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 65090b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 65100b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 65110b57cec5SDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 65120b57cec5SDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 65130b57cec5SDimitry Andric } 65140b57cec5SDimitry Andric 65150b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 65160b57cec5SDimitry Andric CharUnits Offset, 65170b57cec5SDimitry Andric const CXXRecordDecl *RD) { 65180b57cec5SDimitry Andric llvm::Metadata *MD = 65190b57cec5SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 65200b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 65210b57cec5SDimitry Andric 65220b57cec5SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 65230b57cec5SDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 65240b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 65250b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 65260b57cec5SDimitry Andric 65270b57cec5SDimitry Andric if (NeedAllVtablesTypeId()) { 65280b57cec5SDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 65290b57cec5SDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 65300b57cec5SDimitry Andric } 65310b57cec5SDimitry Andric } 65320b57cec5SDimitry Andric 65330b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 65340b57cec5SDimitry Andric if (!SanStats) 6535a7dea167SDimitry Andric SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 65360b57cec5SDimitry Andric 65370b57cec5SDimitry Andric return *SanStats; 65380b57cec5SDimitry Andric } 653923408297SDimitry Andric 65400b57cec5SDimitry Andric llvm::Value * 65410b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 65420b57cec5SDimitry Andric CodeGenFunction &CGF) { 65430b57cec5SDimitry Andric llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 654423408297SDimitry Andric auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 654523408297SDimitry Andric auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6546fe6060f1SDimitry Andric auto *Call = CGF.EmitRuntimeCall( 654723408297SDimitry Andric CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 654823408297SDimitry Andric return Call; 65490b57cec5SDimitry Andric } 65505ffd83dbSDimitry Andric 65515ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 65525ffd83dbSDimitry Andric QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 65535ffd83dbSDimitry Andric return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 65545ffd83dbSDimitry Andric /* forPointeeType= */ true); 65555ffd83dbSDimitry Andric } 65565ffd83dbSDimitry Andric 65575ffd83dbSDimitry Andric CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 65585ffd83dbSDimitry Andric LValueBaseInfo *BaseInfo, 65595ffd83dbSDimitry Andric TBAAAccessInfo *TBAAInfo, 65605ffd83dbSDimitry Andric bool forPointeeType) { 65615ffd83dbSDimitry Andric if (TBAAInfo) 65625ffd83dbSDimitry Andric *TBAAInfo = getTBAAAccessInfo(T); 65635ffd83dbSDimitry Andric 65645ffd83dbSDimitry Andric // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 65655ffd83dbSDimitry Andric // that doesn't return the information we need to compute BaseInfo. 65665ffd83dbSDimitry Andric 65675ffd83dbSDimitry Andric // Honor alignment typedef attributes even on incomplete types. 65685ffd83dbSDimitry Andric // We also honor them straight for C++ class types, even as pointees; 65695ffd83dbSDimitry Andric // there's an expressivity gap here. 65705ffd83dbSDimitry Andric if (auto TT = T->getAs<TypedefType>()) { 65715ffd83dbSDimitry Andric if (auto Align = TT->getDecl()->getMaxAlignment()) { 65725ffd83dbSDimitry Andric if (BaseInfo) 65735ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 65745ffd83dbSDimitry Andric return getContext().toCharUnitsFromBits(Align); 65755ffd83dbSDimitry Andric } 65765ffd83dbSDimitry Andric } 65775ffd83dbSDimitry Andric 65785ffd83dbSDimitry Andric bool AlignForArray = T->isArrayType(); 65795ffd83dbSDimitry Andric 65805ffd83dbSDimitry Andric // Analyze the base element type, so we don't get confused by incomplete 65815ffd83dbSDimitry Andric // array types. 65825ffd83dbSDimitry Andric T = getContext().getBaseElementType(T); 65835ffd83dbSDimitry Andric 65845ffd83dbSDimitry Andric if (T->isIncompleteType()) { 65855ffd83dbSDimitry Andric // We could try to replicate the logic from 65865ffd83dbSDimitry Andric // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 65875ffd83dbSDimitry Andric // type is incomplete, so it's impossible to test. We could try to reuse 65885ffd83dbSDimitry Andric // getTypeAlignIfKnown, but that doesn't return the information we need 65895ffd83dbSDimitry Andric // to set BaseInfo. So just ignore the possibility that the alignment is 65905ffd83dbSDimitry Andric // greater than one. 65915ffd83dbSDimitry Andric if (BaseInfo) 65925ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 65935ffd83dbSDimitry Andric return CharUnits::One(); 65945ffd83dbSDimitry Andric } 65955ffd83dbSDimitry Andric 65965ffd83dbSDimitry Andric if (BaseInfo) 65975ffd83dbSDimitry Andric *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 65985ffd83dbSDimitry Andric 65995ffd83dbSDimitry Andric CharUnits Alignment; 6600e8d8bef9SDimitry Andric const CXXRecordDecl *RD; 6601e8d8bef9SDimitry Andric if (T.getQualifiers().hasUnaligned()) { 6602e8d8bef9SDimitry Andric Alignment = CharUnits::One(); 6603e8d8bef9SDimitry Andric } else if (forPointeeType && !AlignForArray && 6604e8d8bef9SDimitry Andric (RD = T->getAsCXXRecordDecl())) { 66055ffd83dbSDimitry Andric // For C++ class pointees, we don't know whether we're pointing at a 66065ffd83dbSDimitry Andric // base or a complete object, so we generally need to use the 66075ffd83dbSDimitry Andric // non-virtual alignment. 66085ffd83dbSDimitry Andric Alignment = getClassPointerAlignment(RD); 66095ffd83dbSDimitry Andric } else { 66105ffd83dbSDimitry Andric Alignment = getContext().getTypeAlignInChars(T); 66115ffd83dbSDimitry Andric } 66125ffd83dbSDimitry Andric 66135ffd83dbSDimitry Andric // Cap to the global maximum type alignment unless the alignment 66145ffd83dbSDimitry Andric // was somehow explicit on the type. 66155ffd83dbSDimitry Andric if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 66165ffd83dbSDimitry Andric if (Alignment.getQuantity() > MaxAlign && 66175ffd83dbSDimitry Andric !getContext().isAlignmentRequired(T)) 66185ffd83dbSDimitry Andric Alignment = CharUnits::fromQuantity(MaxAlign); 66195ffd83dbSDimitry Andric } 66205ffd83dbSDimitry Andric return Alignment; 66215ffd83dbSDimitry Andric } 66225ffd83dbSDimitry Andric 66235ffd83dbSDimitry Andric bool CodeGenModule::stopAutoInit() { 66245ffd83dbSDimitry Andric unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 66255ffd83dbSDimitry Andric if (StopAfter) { 66265ffd83dbSDimitry Andric // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 66275ffd83dbSDimitry Andric // used 66285ffd83dbSDimitry Andric if (NumAutoVarInit >= StopAfter) { 66295ffd83dbSDimitry Andric return true; 66305ffd83dbSDimitry Andric } 66315ffd83dbSDimitry Andric if (!NumAutoVarInit) { 66325ffd83dbSDimitry Andric unsigned DiagID = getDiags().getCustomDiagID( 66335ffd83dbSDimitry Andric DiagnosticsEngine::Warning, 66345ffd83dbSDimitry Andric "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 66355ffd83dbSDimitry Andric "number of times ftrivial-auto-var-init=%1 gets applied."); 66365ffd83dbSDimitry Andric getDiags().Report(DiagID) 66375ffd83dbSDimitry Andric << StopAfter 66385ffd83dbSDimitry Andric << (getContext().getLangOpts().getTrivialAutoVarInit() == 66395ffd83dbSDimitry Andric LangOptions::TrivialAutoVarInitKind::Zero 66405ffd83dbSDimitry Andric ? "zero" 66415ffd83dbSDimitry Andric : "pattern"); 66425ffd83dbSDimitry Andric } 66435ffd83dbSDimitry Andric ++NumAutoVarInit; 66445ffd83dbSDimitry Andric } 66455ffd83dbSDimitry Andric return false; 66465ffd83dbSDimitry Andric } 6647fe6060f1SDimitry Andric 6648*2a66634dSDimitry Andric void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 6649*2a66634dSDimitry Andric const Decl *D) const { 6650*2a66634dSDimitry Andric StringRef Tag; 6651*2a66634dSDimitry Andric // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 6652*2a66634dSDimitry Andric // postfix beginning with '.' since the symbol name can be demangled. 6653*2a66634dSDimitry Andric if (LangOpts.HIP) 6654*2a66634dSDimitry Andric Tag = (isa<VarDecl>(D) ? ".static." : ".intern."); 6655*2a66634dSDimitry Andric else 6656*2a66634dSDimitry Andric Tag = (isa<VarDecl>(D) ? "__static__" : "__intern__"); 6657*2a66634dSDimitry Andric OS << Tag << getContext().getCUIDHash(); 6658fe6060f1SDimitry Andric } 6659